Run a virtual iPhone on an Apple Silicon Mac.
Swift
Share the board-node device tree code and trim the sound plugin
Jacky62ee326762a3
diff --git a/Research/Guest/virtio_sound.md b/Research/Guest/virtio_sound.mdindex fc27ad3a..e9d4fe5e 100644--- a/Research/Guest/virtio_sound.md+++ b/Research/Guest/virtio_sound.md@@ -355,11 +355,10 @@ callbacks is the completion of that path. The iOS 27 binaryThree faults in the plugin itself survived everything above. Each was found ona new iPad16,1 / 26.6.2 guest (`audiotest-ipad`) with counters the plugin now-writes to `/var/mobile/vpquery.log` at every stream stop:+writes to `/var/mobile/vpquery.log` each time the stream stops:```-stream 1: 237 writes, 0 starved, 0 bytes dropped, lead 2 period(s)-stream 1: 20.16 s, in 888832 frames (44094/s, hal 44100), out 967436 frames (47993/s)+stream 1: 20.16 s, 237 writes, 0 starved, 0 bytes dropped, in 888832 frames (44094/s, hal 44100), out 967436 frames (47993/s)````writes` are periods handed to the kernel, `starved` the ones that found the@@ -544,9 +543,9 @@ tone does there with no haptic server has not been measured.guest (§6); `vpquery.log` says so when it had to.4. Sound on the host: audible, and still audible after a stop. Beyond theplugin's own defaults (§6) the speaker route needs the VirtualAudio patches- (`virtualaudio_speaker_route_throws.md`). In `vpquery.log`, every- `performStartIO` is followed by a `stopStream` whose counters show `writes`- in proportion to the seconds played, `0 starved`, and `in` at the nominal+ (`virtualaudio_speaker_route_throws.md`). In `vpquery.log`, every stop —+ the second and later ones included — leaves a counter line with `writes` in+ proportion to the seconds played, `0 starved`, and `in` at the nominalrate; `logs.syslog` for audiomxd shows no `Re-anchoring IO timeline` and no`could not establish a timeline`.5. Hardware volume: the plugin answers the pspk route's volume queries with adiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swiftindex 6b41284b..1c79a9d8 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift@@ -90,17 +90,7 @@ public enum CustomFirmwarePostRestoreDeviceTree {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 withBoardAudio(blob, board: board)- return (newBlob, changes, blob.count + delta)- }+ try rewrite(at: url, board: boardURL, dryRun: dryRun, verbose: verbose, edit: withBoardAudio)}/// Make an iPad guest's `devicetree.img4` (or bare `.im4p`) carry the@@ -112,6 +102,18 @@ public enum CustomFirmwarePostRestoreDeviceTree {board boardURL: URL,dryRun: Bool = false,verbose: Bool = true,+ ) throws -> Outcome {+ try rewrite(at: url, board: boardURL, dryRun: dryRun, verbose: verbose, edit: withBoardHaptics)+ }++ /// `rewrite(at:)` with an edit that also takes the flat tree of the board's+ /// device tree file and returns the size change it made.+ private static func rewrite(+ at url: URL,+ board boardURL: URL,+ dryRun: Bool,+ verbose: Bool,+ edit: (Data, Data) throws -> (Data, [Change], Int),) throws -> Outcome {let boardData: Datado {@@ -121,7 +123,7 @@ public enum CustomFirmwarePostRestoreDeviceTree {}let board = try openDeviceTree(boardData, path: boardURL.path).blobreturn try rewrite(at: url, dryRun: dryRun, verbose: verbose) { blob in- let (newBlob, changes, delta) = try withBoardHaptics(blob, board: board)+ let (newBlob, changes, delta) = try edit(blob, board)return (newBlob, changes, blob.count + delta)}}@@ -231,12 +233,7 @@ public enum CustomFirmwarePostRestoreDeviceTree {/// Returns the blob unchanged and no changes when it is already in the/// target state.public static func patchedDeviceTree(_ blob: Data) throws -> (Data, [Change]) {- let (root, end) = try parseNode(blob, at: 0)- guard end == blob.count else {- throw PatcherError.invalidFormat(- "DT parse length mismatch: ended at \(end), blob is \(blob.count)",- )- }+ let root = try parseTree(blob, label: "DT")guard nodeName(root) == "device-tree" else {throw PatcherError.invalidFormat("expected root node 'device-tree', got '\(nodeName(root))'",@@ -297,18 +294,6 @@ public enum CustomFirmwarePostRestoreDeviceTree {/// A tree that already matches, or a board with no audio node, comes back/// unchanged.public static func withBoardAudio(_ blob: Data, board: Data) throws -> (Data, [Change], Int) {- let (root, end) = try parseNode(blob, at: 0)- guard end == blob.count else {- throw PatcherError.invalidFormat(- "DT parse length mismatch: ended at \(end), blob is \(blob.count)",- )- }- let (source, sourceEnd) = try parseNode(board, at: 0)- guard sourceEnd == board.count else {- throw PatcherError.invalidFormat(- "board DT parse length mismatch: ended at \(sourceEnd), blob is \(board.count)",- )- }func acousticID(_ node: Data) -> String {guard let (audio, _) = try? parseNode(node, at: 0),let id = audio.properties.first(where: { $0.name == "acoustic-id" }),@@ -316,15 +301,9 @@ public enum CustomFirmwarePostRestoreDeviceTree {else { return "none" }return String(id.value.loadLE(UInt32.self, at: 0))}- guard let change = DeviceTreePatcher.presentBoardAudio(in: root, from: source) else {- return (blob, [], 0)+ return try withBoardNode(blob, board: board, property: "product/audio", DeviceTreePatcher.presentBoardAudio) {+ ("acoustic-id \(acousticID($0.before))", "acoustic-id \(acousticID($0.after)), \($0.after.count)B")}- let record = Change(- property: "product/audio",- before: "acoustic-id \(acousticID(change.before))",- after: "acoustic-id \(acousticID(change.after)), \(change.after.count)B",- )- return (serializeNode(root), [record], change.after.count - change.before.count)}/// `blob` with `/product/haptics` as the board's flat tree `board` has it,@@ -332,32 +311,45 @@ public enum CustomFirmwarePostRestoreDeviceTree {/// has none. Returns the size change with the changes, as `withBoardAudio`/// does. A tree that already matches comes back unchanged.public static func withBoardHaptics(_ blob: Data, board: Data) throws -> (Data, [Change], Int) {- let (root, end) = try parseNode(blob, at: 0)- guard end == blob.count else {- throw PatcherError.invalidFormat(- "DT parse length mismatch: ended at \(end), blob is \(blob.count)",- )+ func describe(_ node: Data) -> String {+ node.isEmpty ? "absent" : "present, \(node.count)B"}- let (source, sourceEnd) = try parseNode(board, at: 0)- guard sourceEnd == board.count else {- throw PatcherError.invalidFormat(- "board DT parse length mismatch: ended at \(sourceEnd), blob is \(board.count)",- )+ return try withBoardNode(blob, board: board, property: "product/haptics", DeviceTreePatcher.presentBoardHaptics) {+ (describe($0.before), describe($0.after))}- guard let change = DeviceTreePatcher.presentBoardHaptics(in: root, from: source) else {+ }++ /// Parses both flat trees, applies `present` to them, and returns the+ /// serialized result with one change, described by `describe`, and the+ /// size it added.+ private static func withBoardNode(+ _ blob: Data,+ board: Data,+ property: String,+ _ present: (DeviceTreePatcher.DTNode, DeviceTreePatcher.DTNode) -> DeviceTreePatcher.BoardNodeChange?,+ describe: (DeviceTreePatcher.BoardNodeChange) -> (before: String, after: String),+ ) throws -> (Data, [Change], Int) {+ let root = try parseTree(blob, label: "DT")+ let source = try parseTree(board, label: "board DT")+ guard let change = present(root, source) else {return (blob, [], 0)}- func describe(_ node: Data) -> String {- node.isEmpty ? "absent" : "present, \(node.count)B"- }- let record = Change(- property: "product/haptics",- before: describe(change.before),- after: describe(change.after),- )+ let described = describe(change)+ let record = Change(property: property, before: described.before, after: described.after)return (serializeNode(root), [record], change.after.count - change.before.count)}+ /// The root of a flat tree that must fill `blob` exactly.+ private static func parseTree(_ blob: Data, label: String) throws -> DeviceTreePatcher.DTNode {+ let (root, end) = try parseNode(blob, at: 0)+ guard end == blob.count else {+ throw PatcherError.invalidFormat(+ "\(label) parse length mismatch: ended at \(end), blob is \(blob.count)",+ )+ }+ return root+ }+// MARK: - Flat device tree format//diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swiftindex 0b0866b8..ccce8e7a 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift@@ -190,62 +190,58 @@ extension DeviceTreePatcher {}private static func child(of node: DTNode, named name: String) throws -> DTNode {- for child in node.children {- for property in child.properties where property.name == "name" {- if property.value.prefix(while: { $0 != 0 }) == Data(name.utf8) {- return child- }- }+ guard let child = optionalChild(of: node, named: name) else {+ throw PatcherError.patchSiteNotFound("DeviceTree: the board's tree has no \(name) node")}- throw PatcherError.patchSiteNotFound("DeviceTree: the board's tree has no \(name) node")+ return child}- // MARK: - Audio+ private static func optionalChild(of node: DTNode, named name: String) -> DTNode? {+ node.children.first { child in+ child.properties.contains { $0.name == "name" && $0.value.prefix(while: { $0 != 0 }) == Data(name.utf8) }+ }+ }- /// What `presentBoardAudio` changed: the audio node's serialized bytes- /// before and after, empty when there was no node.- struct BoardAudioChange {+ // MARK: - Board Nodes++ /// What `presentBoardNode` changed: the node's serialized bytes before and+ /// after, empty where there was, or now is, no node.+ struct BoardNodeChange {let before: Datalet after: Data}- /// Give `root`'s `/product/audio` the properties of the board's.+ /// Give `root`'s `/product/<name>` the properties of the board's.///- /// The tree's audio node, when there is one, came from- /// `devicetree-cfw-product_audio_node`, which copies the D47 iPhone's. Its- /// `acoustic-id` (8018) names `/Library/Audio/Tunings/AID8018`, which an iPad- /// image does not ship; VirtualAudio then builds no microphone sub-ports, and- /// on an iPad, whose board answers yes to stereo and webcam recording, it- /// throws `PRECONDITION FAILURE` in `RoutingSettings_J98` and never- /// initializes, so the guest has no audio route at all. The board's own node- /// names the tunings its image carries (AID2029 on J820).- ///- /// Every property is copied as the board has it, placeholders included, except- /// `AAPL,phandle`, which is the board tree's and could collide in this one; a- /// property the board's node lacks is removed. The node is added under- /// `/product` when the tree has none. Returns nil when the board has no audio- /// node or the tree already matches it.- static func presentBoardAudio(in root: DTNode, from source: DTNode) -> BoardAudioChange? {- func named(_ node: DTNode, _ name: String) -> DTNode? {- node.children.first { child in- child.properties.contains { $0.name == "name" && $0.value.prefix(while: { $0 != 0 }) == Data(name.utf8) }- }- }+ /// Every property is copied as the board has it, placeholders included,+ /// except `AAPL,phandle`, which is the board tree's and could collide in+ /// this one; a property the board's node lacks is removed. The node is+ /// added under `/product` when the tree has none. Where the board has no+ /// such node the tree's is removed if `removeWhenAbsent`, and otherwise+ /// left. Returns nil when nothing changes.+ private static func presentBoardNode(+ _ name: String,+ in root: DTNode,+ from source: DTNode,+ removeWhenAbsent: Bool,+ ) -> BoardNodeChange? {guard- let sourceProduct = named(source, "product"),- let sourceAudio = named(sourceProduct, "audio"),- let product = named(root, "product")+ let sourceProduct = optionalChild(of: source, named: "product"),+ let product = optionalChild(of: root, named: "product")else { return nil }+ let existing = optionalChild(of: product, named: name)+ guard let sourceNode = optionalChild(of: sourceProduct, named: name) else {+ guard removeWhenAbsent, let existing else { return nil }+ product.children.removeAll { $0 === existing }+ return BoardNodeChange(before: serialize(existing), after: Data())+ }- let copied = sourceAudio.properties.filter { $0.name != "AAPL,phandle" }+ let copied = sourceNode.properties.filter { $0.name != "AAPL,phandle" }func describe(_ properties: [DTProperty]) -> [String: (UInt16, Data)] {Dictionary(properties.map { ($0.name, ($0.flags, $0.value)) }, uniquingKeysWith: { first, _ in first })}-- let existing = named(product, "audio")if let existing {- let current = existing.properties.filter { $0.name != "AAPL,phandle" }- let lhs = describe(current)+ let lhs = describe(existing.properties.filter { $0.name != "AAPL,phandle" })let rhs = describe(copied)if lhs.count == rhs.count, lhs.allSatisfy({ name, entry inrhs[name].map { $0.0 == entry.0 && $0.1 == entry.1 } ?? false@@ -263,16 +259,23 @@ extension DeviceTreePatcher {if existing == nil {product.children.append(node)}- return BoardAudioChange(before: before, after: serialize(node))+ return BoardNodeChange(before: before, after: serialize(node))}- // MARK: - Haptics-- /// What `presentBoardHaptics` changed: the haptics node's serialized bytes- /// before and after, empty where there was, or now is, no node.- struct BoardHapticsChange {- let before: Data- let after: Data+ /// Give `root`'s `/product/audio` the properties of the board's.+ ///+ /// The tree's audio node, when there is one, came from+ /// `devicetree-cfw-product_audio_node`, which copies the D47 iPhone's. Its+ /// `acoustic-id` (8018) names `/Library/Audio/Tunings/AID8018`, which an iPad+ /// image does not ship; VirtualAudio then builds no microphone sub-ports, and+ /// on an iPad, whose board answers yes to stereo and webcam recording, it+ /// throws `PRECONDITION FAILURE` in `RoutingSettings_J98` and never+ /// initializes, so the guest has no audio route at all. The board's own node+ /// names the tunings its image carries (AID2029 on J820).+ ///+ /// Returns nil when the board has no audio node or the tree already matches it.+ static func presentBoardAudio(in root: DTNode, from source: DTNode) -> BoardNodeChange? {+ presentBoardNode("audio", in: root, from: source, removeWhenAbsent: false)}/// Make `root`'s `/product/haptics` what the board's tree has — which for@@ -289,45 +292,9 @@ extension DeviceTreePatcher {/// item with it — the tone's audio never starts. An iPad's tree has no/// haptics node at all, so the real device never asks.///- /// Where the board has a node its properties are copied, as the audio- /// node's are; where it has none the guest's is removed. Returns nil when- /// the tree already matches the board.- static func presentBoardHaptics(in root: DTNode, from source: DTNode) -> BoardHapticsChange? {- func named(_ node: DTNode, _ name: String) -> DTNode? {- node.children.first { child in- child.properties.contains { $0.name == "name" && $0.value.prefix(while: { $0 != 0 }) == Data(name.utf8) }- }- }- guard let sourceProduct = named(source, "product"), let product = named(root, "product") else {- return nil- }- let existing = named(product, "haptics")- guard let sourceHaptics = named(sourceProduct, "haptics") else {- guard let existing else { return nil }- let before = serialize(existing)- product.children.removeAll { $0 === existing }- return BoardHapticsChange(before: before, after: Data())- }-- let copied = sourceHaptics.properties.filter { $0.name != "AAPL,phandle" }- if let existing {- let current = existing.properties.filter { $0.name != "AAPL,phandle" }- if current.count == copied.count, zip(current, copied).allSatisfy({ lhs, rhs in- lhs.name == rhs.name && lhs.flags == rhs.flags && lhs.value == rhs.value- }) {- return nil- }- }- let before = existing.map(serialize) ?? Data()- let node = existing ?? DTNode()- let phandle = node.properties.filter { $0.name == "AAPL,phandle" }- node.properties = copied.map {- DTProperty(name: $0.name, flags: $0.flags, value: $0.value, valueOffset: 0)- } + phandle- if existing == nil {- product.children.append(node)- }- return BoardHapticsChange(before: before, after: serialize(node))+ /// Returns nil when the tree already matches the board.+ static func presentBoardHaptics(in root: DTNode, from source: DTNode) -> BoardNodeChange? {+ presentBoardNode("haptics", in: root, from: source, removeWhenAbsent: true)}/// The flat encoding of one node and its children, for the patch record.@@ -363,35 +330,29 @@ extension DeviceTreePatcher {)}let source = try parsePayload(sourceTree)- if gateAllows(Self.iPadAudioPatch), let change = Self.presentBoardAudio(in: root, from: source) {- patches.append(PatchRecord(- patchID: Self.iPadAudioPatch,- component: component,- fileOffset: 0,- virtualAddress: nil,- originalBytes: change.before,- patchedBytes: change.after,- description: "Set /device-tree/product/audio as on \(device.productType)",- ))- if verbose {- print(" =node : /product/audio as on \(device.productType) (\(change.after.count)B) [\(Self.iPadAudioPatch)]")- }- }- if gateAllows(Self.iPadHapticsPatch), let change = Self.presentBoardHaptics(in: root, from: source) {+ let boardNodes = [+ ("audio", Self.iPadAudioPatch, Self.presentBoardAudio),+ ("haptics", Self.iPadHapticsPatch, Self.presentBoardHaptics),+ ]+ for (name, patchID, present) in boardNodes {+ guard gateAllows(patchID), let change = present(root, source) else { continue }+ let removed = change.after.isEmptypatches.append(PatchRecord(- patchID: Self.iPadHapticsPatch,+ patchID: patchID,component: component,fileOffset: 0,virtualAddress: nil,originalBytes: change.before,patchedBytes: change.after,- description: change.after.isEmpty- ? "Remove /device-tree/product/haptics, which \(device.productType) does not have"- : "Set /device-tree/product/haptics as on \(device.productType)",+ description: removed+ ? "Remove /device-tree/product/\(name), which \(device.productType) does not have"+ : "Set /device-tree/product/\(name) as on \(device.productType)",))if verbose {- let what = change.after.isEmpty ? "-node : /product/haptics, absent on" : "=node : /product/haptics as on"- print(" \(what) \(device.productType) [\(Self.iPadHapticsPatch)]")+ let what = removed+ ? "-node : /product/\(name), absent on \(device.productType)"+ : "=node : /product/\(name) as on \(device.productType) (\(change.after.count)B)"+ print(" \(what) [\(patchID)]")}}for edit in try Self.guestEdits(from: source) {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swiftindex 22ecd346..47a2c060 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift@@ -11,79 +11,40 @@ import Testing@Suite("iPad audio node from the board tree")struct CustomFirmwareBoardAudioTests {- // MARK: - A flat device tree-- private struct Node {- var properties: [(name: String, flags: UInt16, value: Data)]- var children: [Node] = []- }-- private static func node(- _ name: String,- _ properties: [(String, Data)] = [],- flags: [String: UInt16] = [:],- children: [Node] = [],- ) -> Node {- Node(- properties: [("name", 0, Data((name + "\0").utf8))]- + properties.map { ($0.0, flags[$0.0] ?? 0, $0.1) },- children: children,- )- }-- private static func uint32(_ value: UInt32) -> Data {- withUnsafeBytes(of: value.littleEndian) { Data($0) }- }-- private static func serialize(_ node: Node) -> Data {- var out = uint32(UInt32(node.properties.count)) + uint32(UInt32(node.children.count))- for (name, flags, value) in node.properties {- var field = Data(name.utf8)- field.append(contentsOf: [UInt8](repeating: 0, count: 32 - field.count))- out.append(field)- out.append(contentsOf: withUnsafeBytes(of: UInt16(value.count).littleEndian) { Array($0) })- out.append(contentsOf: withUnsafeBytes(of: flags.littleEndian) { Array($0) })- out.append(value)- out.append(contentsOf: [UInt8](repeating: 0, count: (4 - value.count % 4) % 4))- }- for child in node.children {- out.append(serialize(child))- }- return out- }+ private typealias Node = FlatDeviceTreeNodeprivate static func tree(audio: Node?) -> Data {- let product = node(+ let product = Node("product",[("product-name", Data("iPad\0".utf8))],children: audio.map { [$0] } ?? [],)- return serialize(node("device-tree", [("model", Data("iPad17,3\0\0".utf8))], children: [- node("chosen"),+ return Node("device-tree", [("model", Data("iPad17,3\0\0".utf8))], children: [+ Node("chosen"),product,- ]))+ ]).serialized}/// The D47 node `devicetree-cfw-product_audio_node` adds.- private static let iPhoneAudio = node("audio", [- ("acoustic-id", uint32(8018)),- ("stereo-sound-recording", uint32(1)),- ("supports-spatial-audio-capture", uint32(1)),+ private static let iPhoneAudio = Node("audio", [+ ("acoustic-id", Node.uint32(8018)),+ ("stereo-sound-recording", Node.uint32(1)),+ ("supports-spatial-audio-capture", Node.uint32(1)),])/// J820's, trimmed: its own acoustic ID, a placeholder, and the board's phandle.- private static let boardAudio = node("audio", [- ("AAPL,phandle", uint32(395)),- ("acoustic-id", uint32(2029)),+ private static let boardAudio = Node("audio", [+ ("AAPL,phandle", Node.uint32(395)),+ ("acoustic-id", Node.uint32(2029)),("speaker-thiele-small", Data("syscfg/SpTS\0".utf8)),- ("stereo-sound-recording", uint32(1)),+ ("stereo-sound-recording", Node.uint32(1)),], flags: ["speaker-thiele-small": 0x8000])/// What the guest's node should become: the board's, without its phandle.- private static let presentedAudio = node("audio", [- ("acoustic-id", uint32(2029)),+ private static let presentedAudio = Node("audio", [+ ("acoustic-id", Node.uint32(2029)),("speaker-thiele-small", Data("syscfg/SpTS\0".utf8)),- ("stereo-sound-recording", uint32(1)),+ ("stereo-sound-recording", Node.uint32(1)),], flags: ["speaker-thiele-small": 0x8000])// MARK: - Tests@@ -101,13 +62,13 @@ struct CustomFirmwareBoardAudioTests {@Test func `keeps the guest's own phandle`() throws {var iPhone = Self.iPhoneAudio- iPhone.properties.append(("AAPL,phandle", 0, Self.uint32(77)))+ iPhone.properties.append(("AAPL,phandle", 0, Node.uint32(77)))let (patched, _, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(Self.tree(audio: iPhone),board: Self.tree(audio: Self.boardAudio),)var expected = Self.presentedAudio- expected.properties.append(("AAPL,phandle", 0, Self.uint32(77)))+ expected.properties.append(("AAPL,phandle", 0, Node.uint32(77)))#expect(patched == Self.tree(audio: expected))}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardHapticsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardHapticsTests.swiftindex 8e954546..881dd1c6 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardHapticsTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardHapticsTests.swift@@ -13,66 +13,33 @@ import Testing@Suite("iPad haptics node from the board tree")struct CustomFirmwareBoardHapticsTests {- // MARK: - A flat device tree-- private struct Node {- var properties: [(name: String, flags: UInt16, value: Data)]- var children: [Node] = []- }-- private static func node(_ name: String, _ properties: [(String, Data)] = [], children: [Node] = []) -> Node {- Node(- properties: [("name", 0, Data((name + "\0").utf8))] + properties.map { ($0.0, 0, $0.1) },- children: children,- )- }-- private static func uint32(_ value: UInt32) -> Data {- withUnsafeBytes(of: value.littleEndian) { Data($0) }- }-- private static func serialize(_ node: Node) -> Data {- var out = uint32(UInt32(node.properties.count)) + uint32(UInt32(node.children.count))- for (name, flags, value) in node.properties {- var field = Data(name.utf8)- field.append(contentsOf: [UInt8](repeating: 0, count: 32 - field.count))- out.append(field)- out.append(contentsOf: withUnsafeBytes(of: UInt16(value.count).littleEndian) { Array($0) })- out.append(contentsOf: withUnsafeBytes(of: flags.littleEndian) { Array($0) })- out.append(value)- out.append(contentsOf: [UInt8](repeating: 0, count: (4 - value.count % 4) % 4))- }- for child in node.children {- out.append(serialize(child))- }- return out- }+ private typealias Node = FlatDeviceTreeNode/// A tree whose `/product` holds `maps`, then `haptics` when given, then/// `util` — the node sits between siblings, as it does on vphone600.private static func tree(haptics: Node?) -> Data {- let product = node(+ let product = Node("product",[("product-name", Data("iPad\0".utf8))],- children: [node("maps", [("regulatory", uint32(1))])]+ children: [Node("maps", [("regulatory", Node.uint32(1))])]+ (haptics.map { [$0] } ?? [])- + [node("util", [("ramdisk", uint32(0))])],+ + [Node("util", [("ramdisk", Node.uint32(0))])],)- return serialize(node("device-tree", [("model", Data("iPad16,1\0".utf8))], children: [product]))+ return Node("device-tree", [("model", Data("iPad16,1\0".utf8))], children: [product]).serialized}/// What vphone600 carries.- private static let guestHaptics = node("haptics", [- ("closed-loop", uint32(1)),- ("supports-3rd-party-haptics", uint32(1)),- ("AAPL,phandle", uint32(100)),+ private static let guestHaptics = Node("haptics", [+ ("closed-loop", Node.uint32(1)),+ ("supports-3rd-party-haptics", Node.uint32(1)),+ ("AAPL,phandle", Node.uint32(100)),])/// A board that does have an actuator.- private static let boardHaptics = node("haptics", [- ("closed-loop", uint32(1)),- ("supports-3rd-party-haptics", uint32(0)),- ("AAPL,phandle", uint32(7)),+ private static let boardHaptics = Node("haptics", [+ ("closed-loop", Node.uint32(1)),+ ("supports-3rd-party-haptics", Node.uint32(0)),+ ("AAPL,phandle", Node.uint32(7)),])// MARK: - Tests@@ -119,17 +86,17 @@ struct CustomFirmwareBoardHapticsTests {board: Self.tree(haptics: Self.boardHaptics),)#expect(changes.first?.after.hasPrefix("present") == true)- let expected = Self.node("haptics", [- ("closed-loop", Self.uint32(1)),- ("supports-3rd-party-haptics", Self.uint32(0)),- ("AAPL,phandle", Self.uint32(100)),+ let expected = Node("haptics", [+ ("closed-loop", Node.uint32(1)),+ ("supports-3rd-party-haptics", Node.uint32(0)),+ ("AAPL,phandle", Node.uint32(100)),])#expect(patched == Self.tree(haptics: expected))}@Test func `a tree that already matches the board's node is left alone`() throws {var matching = Self.boardHaptics- matching.properties[3].value = Self.uint32(100)+ matching.properties[3].value = Node.uint32(100)let original = Self.tree(haptics: matching)let (patched, changes, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardHaptics(original,diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/FlatDeviceTreeNode.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/FlatDeviceTreeNode.swiftnew file mode 100644index 00000000..39249ebb--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/FlatDeviceTreeNode.swift@@ -0,0 +1,47 @@+// FlatDeviceTreeNode.swift — device trees for tests, in the flat format a restored tree uses.+//+// Per node: u32 property count, u32 child count, then each property as a+// 32-byte name, u16 length, u16 flags and the value padded to four bytes, then+// each child. Built here so a test runs the patcher's parse, edit and+// serialization on real bytes.++import Foundation++struct FlatDeviceTreeNode {+ var properties: [(name: String, flags: UInt16, value: Data)]+ var children: [FlatDeviceTreeNode] = []++ /// A node called `name`, with `properties` in order after its `name`+ /// property; `flags` gives the ones that are not 0.+ init(+ _ name: String,+ _ properties: [(String, Data)] = [],+ flags: [String: UInt16] = [:],+ children: [FlatDeviceTreeNode] = [],+ ) {+ self.properties = [("name", 0, Data((name + "\0").utf8))]+ + properties.map { ($0.0, flags[$0.0] ?? 0, $0.1) }+ self.children = children+ }++ static func uint32(_ value: UInt32) -> Data {+ withUnsafeBytes(of: value.littleEndian) { Data($0) }+ }++ var serialized: Data {+ var out = Self.uint32(UInt32(properties.count)) + Self.uint32(UInt32(children.count))+ for (name, flags, value) in properties {+ var field = Data(name.utf8)+ field.append(contentsOf: [UInt8](repeating: 0, count: 32 - field.count))+ out.append(field)+ out.append(contentsOf: withUnsafeBytes(of: UInt16(value.count).littleEndian) { Array($0) })+ out.append(contentsOf: withUnsafeBytes(of: flags.littleEndian) { Array($0) })+ out.append(value)+ out.append(contentsOf: [UInt8](repeating: 0, count: (4 - value.count % 4) % 4))+ }+ for child in children {+ out.append(child.serialized)+ }+ return out+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 1373a2f5..900a4aac 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -1151,9 +1151,9 @@ struct VPhoneCustomFirmwareInstaller {}/// `includeIdentity` is false for an environment update, which carries- /// only the board audio and haptics repairs. `boardDeviceTree` is the iPad's own device- /// tree, staged from the VM's `FirmwareOriginals`, or nil for an iPhone- /// guest or a VM patched before `fw patch` kept it.+ /// only the board audio and haptics repairs. `boardDeviceTree` is the+ /// iPad's own device tree, staged from the VM's `FirmwareOriginals`, or nil+ /// for an iPhone guest or a VM patched before `fw patch` kept it.private func patchPreboot(volumes: [[String: Any]],work: WorkDirectory,@@ -1183,9 +1183,11 @@ struct VPhoneCustomFirmwareInstaller {}}let spoofBuild = includeIdentity ? self.spoofBuild : nil- let boardAudio = boardDeviceTree != nil && on(FirmwareGuestSystemPatchSet.prebootBoardAudio)- let boardHaptics = boardDeviceTree != nil && on(FirmwareGuestSystemPatchSet.prebootBoardHaptics)- guard rewriteIdentity || boardAudio || boardHaptics || !(spoofBuild ?? "").isEmpty else { return }+ let boardVerbs = boardDeviceTree == nil ? [] : [+ (FirmwareGuestSystemPatchSet.prebootBoardAudio, "patch-dt-board-audio"),+ (FirmwareGuestSystemPatchSet.prebootBoardHaptics, "patch-dt-board-haptics"),+ ].filter { on($0.0) }.map(\.1)+ guard rewriteIdentity || !boardVerbs.isEmpty || !(spoofBuild ?? "").isEmpty else { return }guardlet preboot = volumes.first(where: { ($0["Roles"] as? [String])?.contains("Preboot") == true }),let device = preboot["DeviceIdentifier"] as? String@@ -1213,23 +1215,10 @@ struct VPhoneCustomFirmwareInstaller {if rewriteIdentity {try patchCopy(of: deviceTree, in: root, work: work, verb: "patch-post-restore-dt")}- if boardAudio, let boardDeviceTree {- try patchCopy(- of: deviceTree,- in: root,- work: work,- verb: "patch-dt-board-audio",- arguments: [boardDeviceTree.path],- )- }- if boardHaptics, let boardDeviceTree {- try patchCopy(- of: deviceTree,- in: root,- work: work,- verb: "patch-dt-board-haptics",- arguments: [boardDeviceTree.path],- )+ if let boardDeviceTree {+ for verb in boardVerbs {+ try patchCopy(of: deviceTree, in: root, work: work, verb: verb, arguments: [boardDeviceTree.path])+ }}if let build = spoofBuild {let version = "Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist"diff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.mindex 2dda87dd..e5cbc063 100644--- a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m@@ -13,9 +13,10 @@// with the async write selector; the virtio device paces playback on the host.//// Optional settings in the `com.apple.coreaudio` preference domain, read-// once when audiomxd loads the plugin, exist for diagnosing routing:+// once when audiomxd loads the plugin:// VPhoneVirtIOSoundTransportType four-character transport ("usb ", "bltn")// VPhoneVirtIOSoundDeviceUID HAL device UID (default "PuffinOutput")+// VPhoneVirtIOSoundNominalRate 44100 to start at the alternate rate// VPhoneVirtIOSoundLeadPeriods periods of silence queued ahead of the// mix at each start, 0 to 8@@ -221,22 +222,19 @@ static void VPEnsureVirtualAudioProduct(void) {}/// How many periods of silence go to the device before the mix at each start.-static const uint32_t kDefaultLeadPeriods = 2;-static const uint32_t kMaximumLeadPeriods = 8;+static const int kDefaultLeadPeriods = 2;+static const int kMaximumLeadPeriods = 8;static uint32_t VPLeadPeriods(void) {CFPropertyListRef value = CFPreferencesCopyAppValue(CFSTR("VPhoneVirtIOSoundLeadPeriods"), kSettingsDomain);- int periods = (int)kDefaultLeadPeriods;+ int periods = kDefaultLeadPeriods;if (value && CFGetTypeID(value) == CFNumberGetTypeID()) {CFNumberGetValue(value, kCFNumberIntType, &periods);}if (value) {CFRelease(value);}- if (periods < 0) {- return 0;- }- return (uint32_t)periods > kMaximumLeadPeriods ? kMaximumLeadPeriods : (uint32_t)periods;+ return (uint32_t)MAX(0, MIN(periods, kMaximumLeadPeriods));}/// The nominal rate the device boots with, for testing how VirtualAudio picks@@ -273,52 +271,42 @@ typedef struct {_Atomic uint64_t periodCount;_Atomic uint64_t seed;_Atomic uint64_t hostTicksPerPeriod;- _Atomic uint32_t periodFrames;+ /// Set once, by `VPClockConfigure`.+ uint32_t periodFrames;} VPClock;-static void VPClockConfigure(VPClock *clock, double sampleRate) {- uint32_t periodFrames = (UInt32)(sampleRate * kTimestampPeriodSeconds);- mach_timebase_info_data_t timebase;- mach_timebase_info(&timebase);- double hostTicksPerSecond = 1e9 * timebase.denom / timebase.numer;- double hostTicksPerPeriod = hostTicksPerSecond * periodFrames / sampleRate;- uint64_t bits;- memcpy(&bits, &hostTicksPerPeriod, sizeof(bits));- atomic_init(&clock->anchorHostTime, mach_absolute_time());- atomic_init(&clock->periodCount, 0);- atomic_init(&clock->seed, 1);- atomic_init(&clock->hostTicksPerPeriod, bits);- atomic_init(&clock->periodFrames, periodFrames);+static void VPClockAnchor(VPClock *clock) {+ atomic_store(&clock->periodCount, 0);+ atomic_store(&clock->anchorHostTime, mach_absolute_time());+ atomic_fetch_add(&clock->seed, 1);}/// Re-derives how long a period lasts at a new nominal rate and re-anchors./// The period keeps its frame count. Rate changes arrive while I/O is/// stopped.static void VPClockSetRate(VPClock *clock, double sampleRate) {- uint32_t periodFrames = atomic_load(&clock->periodFrames);mach_timebase_info_data_t timebase;mach_timebase_info(&timebase);double hostTicksPerSecond = 1e9 * timebase.denom / timebase.numer;- double hostTicksPerPeriod = hostTicksPerSecond * periodFrames / sampleRate;+ double hostTicksPerPeriod = hostTicksPerSecond * clock->periodFrames / sampleRate;uint64_t bits;memcpy(&bits, &hostTicksPerPeriod, sizeof(bits));atomic_store(&clock->hostTicksPerPeriod, bits);- atomic_store(&clock->periodCount, 0);- atomic_store(&clock->anchorHostTime, mach_absolute_time());- atomic_fetch_add(&clock->seed, 1);+ VPClockAnchor(clock);}-static void VPClockAnchor(VPClock *clock) {- atomic_store(&clock->periodCount, 0);- atomic_store(&clock->anchorHostTime, mach_absolute_time());- atomic_fetch_add(&clock->seed, 1);+/// Fixes the period at `kTimestampPeriodSeconds` of the rate the device+/// starts at; the device publishes `periodFrames` as its timestamp period.+static void VPClockConfigure(VPClock *clock, double sampleRate) {+ memset(clock, 0, sizeof(*clock));+ clock->periodFrames = (uint32_t)(sampleRate * kTimestampPeriodSeconds);+ VPClockSetRate(clock, sampleRate);}static void VPClockZeroTimestamp(VPClock *clock, Float64 *sampleTime, UInt64 *hostTime, UInt64 *seed) {uint64_t anchor = atomic_load(&clock->anchorHostTime);uint64_t count = atomic_load(&clock->periodCount);uint64_t ticksBits = atomic_load(&clock->hostTicksPerPeriod);- uint32_t periodFrames = atomic_load(&clock->periodFrames);double hostTicksPerPeriod;memcpy(&hostTicksPerPeriod, &ticksBits, sizeof(hostTicksPerPeriod));uint64_t now = mach_absolute_time();@@ -326,12 +314,11 @@ static void VPClockZeroTimestamp(VPClock *clock, Float64 *sampleTime, UInt64 *hocount = (uint64_t)((now - anchor) / hostTicksPerPeriod);atomic_store(&clock->periodCount, count);}- *sampleTime = (Float64)count * periodFrames;+ *sampleTime = (Float64)count * clock->periodFrames;*hostTime = anchor + (UInt64)(count * hostTicksPerPeriod);// The seed names the timeline, not the timestamp: it moves only when the- // clock is re-anchored. The HAL reads a changed seed as a discontinuity- // and re-anchors its own IO timeline, audibly, so a seed that moved with- // every period made every period a glitch.+ // clock is re-anchored, which is the one time the HAL should re-anchor+ // its own.*seed = atomic_load(&clock->seed);}@@ -396,23 +383,24 @@ typedef struct {float *scratch;uint32_t bytesPerFrame;uint32_t wireRate;- /// Bytes the ring refused because the device had not returned the space.- _Atomic uint64_t *dropped;- /// Frames the HAL handed over, and bytes that went into the ring.- _Atomic uint64_t *framesIn;- _Atomic uint64_t *bytesOut;+ /// Since the last device start: frames the HAL handed over, bytes that+ /// went into the ring, and bytes the ring refused because the device had+ /// not returned the space.+ _Atomic uint64_t framesIn;+ _Atomic uint64_t bytesOut;+ _Atomic uint64_t dropped;} VPMixState;static void VPMixRingWrite(VPMixState *mix, const void *bytes, uint32_t length) {if (VPVirtIOSoundRingWrite(mix->ring, bytes, length)) {- atomic_fetch_add_explicit(mix->bytesOut, length, memory_order_relaxed);+ atomic_fetch_add_explicit(&mix->bytesOut, length, memory_order_relaxed);} else {- atomic_fetch_add_explicit(mix->dropped, length, memory_order_relaxed);+ atomic_fetch_add_explicit(&mix->dropped, length, memory_order_relaxed);}}static int VPMixWrite(VPMixState *mix, void *buffer, UInt32 frameCount) {- atomic_fetch_add_explicit(mix->framesIn, frameCount, memory_order_relaxed);+ atomic_fetch_add_explicit(&mix->framesIn, frameCount, memory_order_relaxed);uint32_t halRate = atomic_load(mix->halRate);if (halRate == mix->wireRate) {VPMixRingWrite(mix, buffer, frameCount * mix->bytesPerFrame);@@ -486,14 +474,11 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UI/// Periods of silence queued ahead of the mix at each device start.uint32_t _leadPeriods;void *_silence;- /// Since the last device start: writes handed to the device, how many of- /// them found it with nothing left to play, and bytes the ring refused.+ /// Since the last device start: when it was, writes handed to the device,+ /// and how many of them found it with nothing left to play.+ uint64_t _startedAt;uint64_t _submissions;uint64_t _starved;- _Atomic uint64_t _dropped;- _Atomic uint64_t _framesIn;- _Atomic uint64_t _bytesOut;- uint64_t _startedAt;/// The rate CoreAudio runs the stream at, which is the wire rate until a/// 44100 aggregate switches the device. The mix block reads it, the rate/// change writes it, both lock-free.@@ -546,7 +531,7 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UI_leadPeriods = VPLeadPeriods();_silence = calloc(1, _periodBytes);_resampleScratch = malloc(kResampleScratchFrames * format.bytesPerFrame);- if (!_resampleScratch) {+ if (!_silence || !_resampleScratch) {IONotificationPortDestroy(_port);VPVirtIOSoundRingDestroy(&_ring);return nil;@@ -599,17 +584,14 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UI.scratch = _resampleScratch,.bytesPerFrame = format.bytesPerFrame,.wireRate = (uint32_t)format.sampleRate,- .dropped = &_dropped,- .framesIn = &_framesIn,- .bytesOut = &_bytesOut,};[self installMixBlock];os_log(VPLog(), "stream %u: %.0f Hz, %u channels, %u-bit %{public}s, period %u bytes",streamID, format.sampleRate, format.channels, format.bitsPerChannel,format.isFloat ? "float" : "integer", _periodBytes);- VPLogToFile("stream %u: %.0f Hz, %u channels, %u-bit %s, period %u bytes",+ VPLogToFile("stream %u: %.0f Hz, %u channels, %u-bit %s, period %u bytes, lead %u period(s)",streamID, format.sampleRate, format.channels, format.bitsPerChannel,- format.isFloat ? "float" : "integer", _periodBytes);+ format.isFloat ? "float" : "integer", _periodBytes, _leadPeriods);return self;}@@ -723,11 +705,10 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UI_reportedTransferError = NO;_submissions = 0;_starved = 0;- atomic_store(&_dropped, 0);- atomic_store(&_framesIn, 0);- atomic_store(&_bytesOut, 0);+ atomic_store(&_mix.framesIn, 0);+ atomic_store(&_mix.bytesOut, 0);+ atomic_store(&_mix.dropped, 0);_startedAt = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);- [self queueLead];return YES;}@@ -739,23 +720,32 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UI/// the device still draining tops up what the drain consumed.- (void)queueLead {dispatch_assert_queue(_queue);- if (!_silence) {- return;- }uint32_t queued = (uint32_t)(VPVirtIOSoundRingInFlight(&_ring) / _periodBytes);- BOOL wrote = NO;for (uint32_t period = queued; period < _leadPeriods; period++) {- wrote = VPVirtIOSoundRingWrite(&_ring, _silence, _periodBytes) || wrote;- }- if (wrote) {- [self submitPending:YES];+ VPVirtIOSoundRingWrite(&_ring, _silence, _periodBytes);}+ [self submitPending:YES];}- (UInt32)queuedLatencyFrames {return (_leadPeriods + 1) * (_periodBytes / _format.bytesPerFrame);}+/// One line per run of the device, for telling a gap on the host (`starved`)+/// from an unhappy HAL clock (`in` far from the nominal rate) from a full+/// ring (`dropped`).+- (void)logCounters {+ double seconds = (double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - _startedAt) / 1e9;+ uint64_t framesIn = atomic_load(&_mix.framesIn);+ uint64_t framesOut = atomic_load(&_mix.bytesOut) / _format.bytesPerFrame;+ VPLogToFile("stream %u: %.2f s, %llu writes, %llu starved, %llu bytes dropped, "+ "in %llu frames (%.0f/s, hal %u), out %llu frames (%.0f/s)",+ _streamID, seconds, (unsigned long long)_submissions, (unsigned long long)_starved,+ (unsigned long long)atomic_load(&_mix.dropped),+ (unsigned long long)framesIn, seconds > 0 ? framesIn / seconds : 0, atomic_load(&_halRate),+ (unsigned long long)framesOut, seconds > 0 ? framesOut / seconds : 0);+}+- (void)stopDevice {dispatch_assert_queue(_queue);[self callSelector:kVPVirtIOSoundSelectorStop];@@ -814,13 +804,10 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UI- (void)startStream {dispatch_sync(_queue, ^{- VPLogToFile("stream %u: startStream in state %d, %llu bytes in flight", self->_streamID,- (int)self->_state, (unsigned long long)VPVirtIOSoundRingInFlight(&self->_ring));- if (self->_state == VPStreamStateIdle) {- if (![self startDevice]) {- return;- }- } else if (self->_state == VPStreamStateDraining) {+ if (self->_state == VPStreamStateIdle && ![self startDevice]) {+ return;+ }+ if (self->_state != VPStreamStateRunning) {[self queueLead];}self->_state = VPStreamStateRunning;@@ -843,20 +830,10 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UI- (void)stopStream {dispatch_sync(_queue, ^{- VPLogToFile("stream %u: stopStream in state %d, %llu bytes in flight", self->_streamID,- (int)self->_state, (unsigned long long)VPVirtIOSoundRingInFlight(&self->_ring));- VPLogToFile("stream %u: %llu writes, %llu starved, %llu bytes dropped, lead %u period(s)", self->_streamID,- (unsigned long long)self->_submissions, (unsigned long long)self->_starved,- (unsigned long long)atomic_load(&self->_dropped), self->_leadPeriods);- double seconds = (double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - self->_startedAt) / 1e9;- uint64_t framesIn = atomic_load(&self->_framesIn);- uint64_t framesOut = atomic_load(&self->_bytesOut) / self->_format.bytesPerFrame;- VPLogToFile("stream %u: %.2f s, in %llu frames (%.0f/s, hal %u), out %llu frames (%.0f/s)", self->_streamID,- seconds, (unsigned long long)framesIn, seconds > 0 ? framesIn / seconds : 0, atomic_load(&self->_halRate),- (unsigned long long)framesOut, seconds > 0 ? framesOut / seconds : 0);if (self->_state != VPStreamStateRunning) {return;}+ [self logCounters];[self submitPending:YES];self->_state = VPStreamStateDraining;if (VPVirtIOSoundRingInFlight(&self->_ring) == 0) {@@ -977,7 +954,6 @@ static uint32_t VPStreamCount(io_service_t service) {if (_alternateRate > 0 && override == _alternateRate) {nominalRate = _alternateRate;}- UInt32 periodFrames = (UInt32)(nominalRate * kTimestampPeriodSeconds);VPClockConfigure(&_clock, nominalRate);_clockRate = nominalRate;self.deviceName = @"vphone Speaker";@@ -991,10 +967,12 @@ static uint32_t VPStreamCount(io_service_t service) {self.samplingRate = nominalRate;self.outputSafetyOffset = kSafetyOffsetFrames;// What the stream queues ahead of the host, so the HAL presents video- // against when the sound is heard, not when it is written.- self.outputLatency = latencyFrames;+ // against when the sound is heard, not when it is written. Set once, in+ // frames of the rate the device starts at, so after a rate change it is+ // off by the ratio of the rates.+ self.outputLatency = (UInt32)(latencyFrames * nominalRate / sampleRate);self.transportType = VPTransportType();- self.timestampPeriod = periodFrames;+ self.timestampPeriod = _clock.periodFrames;[self installIOBlocks];UInt32 transport = self.transportType;@@ -1050,13 +1028,6 @@ static uint32_t VPStreamCount(io_service_t service) {if (result == kAudioHardwareNoError) {VPClockAnchor(&_clock);}- VPLogToFile("performStartIO -> %d (clock %.0f)", result, _clockRate);- return result;-}--- (int)performStopIO {- int result = [super performStopIO];- VPLogToFile("performStopIO -> %d", result);return result;}