From 7c3499d5a23f1f21d2ac06e881f3aec0f2b8016d Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:01:49 -0500 Subject: [PATCH] Play original guest PCM through the native macOS audio engine Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/main.swift | 76 +++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 3 deletions(-) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 1736afa..6918a74 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -5,6 +5,7 @@ // by native Metal) and shows the verified read-back frame. No other executable can run. import AppKit +import AVFoundation import CXenora import Foundation import SwiftUI @@ -113,12 +114,13 @@ struct AudioVfsFrame { let samples: UInt32 let totalAudioBytes: UInt64 let rgba: [UInt8] + let pcm: [UInt8] - static func run() -> AudioVfsFrame { + static func run(captureAudio: Bool = false) -> AudioVfsFrame { var session: xenora_session = 0 var status = xenora_session_create(XENORA_ABI_VERSION, &session) guard status == XENORA_OK else { - return AudioVfsFrame(status: status, width: 0, height: 0, samples: 0, totalAudioBytes: 0, rgba: []) + return AudioVfsFrame(status: status, width: 0, height: 0, samples: 0, totalAudioBytes: 0, rgba: [], pcm: []) } defer { _ = xenora_session_destroy(session) } var rgba = [UInt8](repeating: 0, count: 16) @@ -133,13 +135,25 @@ struct AudioVfsFrame { var underruns: UInt32 = 0 var total: UInt64 = 0 _ = xenora_session_audio_status(session, &queued, &underruns, &total) + var pcm: [UInt8] = [] + if captureAudio && status == XENORA_OK && queued > 0 && queued <= 256 * 1024 { + pcm = [UInt8](repeating: 0, count: Int(queued)) + var read: UInt64 = 0 + let readStatus = pcm.withUnsafeMutableBufferPointer { buffer in + xenora_session_audio_read(session, buffer.baseAddress, UInt64(buffer.count), &read) + } + if readStatus != XENORA_OK || read != UInt64(queued) { + pcm.removeAll() + } + } return AudioVfsFrame( status: status, width: Int(width), height: Int(height), samples: samples, totalAudioBytes: total, - rgba: status == XENORA_OK ? rgba : [] + rgba: status == XENORA_OK ? rgba : [], + pcm: pcm ) } @@ -158,6 +172,46 @@ struct AudioVfsFrame { } } +private enum FixturePlaybackError: Error { + case invalidPCM + case timedOut +} + +private func playFixturePCM(_ pcm: [UInt8]) throws -> Int { + // The embedded audio/VFS fixture submits mono 48 kHz S16LE frames. + guard !pcm.isEmpty, pcm.count.isMultiple(of: 2), + let format = AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 1), + let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(pcm.count / 2)), + let samples = buffer.floatChannelData?[0] else { + throw FixturePlaybackError.invalidPCM + } + buffer.frameLength = buffer.frameCapacity + for frame in 0..