diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..5f9b5ef --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Unified diff context lines include a required leading space on blank lines. +patches/wine11/*.patch -whitespace diff --git a/Fixtures/Windows/d3d11-clear.cpp b/Fixtures/Windows/d3d11-clear.cpp index b781909..07298df 100644 --- a/Fixtures/Windows/d3d11-clear.cpp +++ b/Fixtures/Windows/d3d11-clear.cpp @@ -3,6 +3,7 @@ #include #include #include +#include using Microsoft::WRL::ComPtr; @@ -12,7 +13,9 @@ static LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wparam, LPA return DefWindowProcW(window, message, wparam, lparam); } -int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { +int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int show) { + const bool smoke = std::wcscmp(commandLine, L"--smoke") == 0; + unsigned frames = 0; WNDCLASSW klass{}; klass.lpfnWndProc = WindowProc; klass.hInstance = instance; klass.lpszClassName = L"IndieD3D11Fixture"; klass.hCursor = LoadCursor(nullptr, IDC_ARROW); if (!RegisterClassW(&klass)) return 10; @@ -28,7 +31,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { D3D_FEATURE_LEVEL level{}; HRESULT result = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &swap, &chain, &device, &level, &context); - if (FAILED(result)) { MessageBoxW(window, L"D3D11CreateDeviceAndSwapChain failed", L"Indie", MB_ICONERROR); return 20; } + if (FAILED(result)) { if (!smoke) MessageBoxW(window, L"D3D11CreateDeviceAndSwapChain failed", L"Indie", MB_ICONERROR); return 20; } ComPtr buffer; ComPtr target; if (FAILED(chain->GetBuffer(0, IID_PPV_ARGS(&buffer))) || FAILED(device->CreateRenderTargetView(buffer.Get(), nullptr, &target))) return 21; ShowWindow(window, show); @@ -41,6 +44,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { context->OMSetRenderTargets(1, target.GetAddressOf(), nullptr); context->ClearRenderTargetView(target.Get(), color); if (FAILED(chain->Present(1, 0))) return 22; + if (smoke && ++frames == 120) DestroyWindow(window); } - return 0; + return smoke && frames != 120 ? 23 : 0; } diff --git a/Fixtures/Windows/d3d12-clear.cpp b/Fixtures/Windows/d3d12-clear.cpp index c9d0228..9027ff1 100644 --- a/Fixtures/Windows/d3d12-clear.cpp +++ b/Fixtures/Windows/d3d12-clear.cpp @@ -3,6 +3,7 @@ #include #include #include +#include using Microsoft::WRL::ComPtr; static constexpr UINT FrameCount = 2; @@ -13,7 +14,9 @@ static LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wparam, LPA return DefWindowProcW(window, message, wparam, lparam); } -int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { +int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int show) { + const bool smoke = std::wcscmp(commandLine, L"--smoke") == 0; + unsigned frames = 0; WNDCLASSW klass{}; klass.lpfnWndProc = WindowProc; klass.hInstance = instance; klass.lpszClassName = L"IndieD3D12Fixture"; klass.hCursor = LoadCursor(nullptr, IDC_ARROW); if (!RegisterClassW(&klass)) return 10; @@ -25,7 +28,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { ComPtr device; if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 20; if (FAILED(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { - MessageBoxW(window, L"D3D12CreateDevice failed", L"Indie", MB_ICONERROR); return 21; + if (!smoke) MessageBoxW(window, L"D3D12CreateDevice failed", L"Indie", MB_ICONERROR); return 21; } D3D12_COMMAND_QUEUE_DESC queueDescription{}; @@ -98,13 +101,15 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { ++fenceValue; queue->Signal(fence.Get(), fenceValue); if (fence->GetCompletedValue() < fenceValue) { fence->SetEventOnCompletion(fenceValue, fenceEvent); - WaitForSingleObject(fenceEvent, INFINITE); + if (WaitForSingleObject(fenceEvent, smoke ? 10000 : INFINITE) != WAIT_OBJECT_0) { CloseHandle(fenceEvent); return 32; } } + if (smoke && ++frames == 120) DestroyWindow(window); } ++fenceValue; queue->Signal(fence.Get(), fenceValue); if (fence->GetCompletedValue() < fenceValue) { - fence->SetEventOnCompletion(fenceValue, fenceEvent); WaitForSingleObject(fenceEvent, INFINITE); + fence->SetEventOnCompletion(fenceValue, fenceEvent); + if (WaitForSingleObject(fenceEvent, smoke ? 10000 : INFINITE) != WAIT_OBJECT_0) { CloseHandle(fenceEvent); return 32; } } CloseHandle(fenceEvent); - return 0; + return smoke && frames != 120 ? 33 : 0; } diff --git a/Fixtures/Windows/win32-smoke.cpp b/Fixtures/Windows/win32-smoke.cpp index a5fe976..45c72b9 100644 --- a/Fixtures/Windows/win32-smoke.cpp +++ b/Fixtures/Windows/win32-smoke.cpp @@ -1,8 +1,10 @@ #include +#include static LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_KEYDOWN && wparam == VK_ESCAPE) { DestroyWindow(window); return 0; } if (message == WM_DESTROY) { PostQuitMessage(0); return 0; } + if (message == WM_TIMER && wparam == 1) { DestroyWindow(window); return 0; } if (message == WM_PAINT) { PAINTSTRUCT paint{}; HDC dc = BeginPaint(window, &paint); @@ -20,7 +22,7 @@ static LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wparam, LPA return DefWindowProcW(window, message, wparam, lparam); } -int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { +int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int show) { WNDCLASSW klass{}; klass.lpfnWndProc = WindowProc; klass.hInstance = instance; klass.lpszClassName = L"IndieSmokeFixture"; klass.hCursor = LoadCursor(nullptr, IDC_ARROW); if (!RegisterClassW(&klass)) return 10; @@ -28,6 +30,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { CW_USEDEFAULT, CW_USEDEFAULT, 800, 450, nullptr, nullptr, instance, nullptr); if (!window) return 11; ShowWindow(window, show); + if (std::wcscmp(commandLine, L"--smoke") == 0 && !SetTimer(window, 1, 2000, nullptr)) return 12; MSG message{}; while (GetMessageW(&message, nullptr, 0, 0) > 0) { TranslateMessage(&message); DispatchMessageW(&message); } return static_cast(message.wParam); diff --git a/Sources/IndieCatalog/SteamAccountLibrary.swift b/Sources/IndieCatalog/SteamAccountLibrary.swift index 227b802..ef9410e 100644 --- a/Sources/IndieCatalog/SteamAccountLibrary.swift +++ b/Sources/IndieCatalog/SteamAccountLibrary.swift @@ -201,8 +201,10 @@ public enum SteamStoreMetadataService { .init(name: "l", value: AppLanguage.steamLanguage), .init(name: "cc", value: "cn"), ] - guard let url = components.url, - let (data, response) = try? await session.data(from: url), + guard let url = components.url else { return nil } + var request = URLRequest(url: url) + request.timeoutInterval = 15 + guard let (data, response) = try? await session.data(for: request), (response as? HTTPURLResponse)?.statusCode == 200, let envelope = try? IndieJSON.decoder().decode([String: StoreEnvelope].self, from: data), let result = envelope[String(appID)], result.success, let details = result.data, diff --git a/Sources/IndieCatalog/SteamLibraryReader.swift b/Sources/IndieCatalog/SteamLibraryReader.swift new file mode 100644 index 0000000..c96ea65 --- /dev/null +++ b/Sources/IndieCatalog/SteamLibraryReader.swift @@ -0,0 +1,62 @@ +import Foundation + +/// Serializes filesystem work away from the UI actor. Download manifests can +/// refresh frequently while account information and activity use a slower cadence. +public actor SteamLibraryReader { + public struct Snapshot: Sendable { + public let records: [SteamGame] + public let readyAppIDs: Set + public let accountGames: [SteamAccountGame] + public let activities: [UInt64: SteamGameActivity] + public let libraries: [SteamLibraryLocation] + } + private var root: URL? + private var lastFullRead: Date? + private var lastRecordRead: Date? + private var records: [SteamGame] = [] + private var accountGames: [SteamAccountGame] = [] + private var activities: [UInt64: SteamGameActivity] = [:] + private var libraries: [SteamLibraryLocation] = [] + + public init() {} + + public func read(steamRoot: URL, bottleRoot: URL, force: Bool = false, now: Date = Date()) throws -> Snapshot { + let steamApps = steamRoot.appendingPathComponent("steamapps") + if force || root != steamRoot || lastRecordRead.map({ now.timeIntervalSince($0) >= 1 }) != false { + records = FileManager.default.fileExists(atPath: steamApps.path) + ? try SteamScanner.scan(steamApps: steamApps) : [] + lastRecordRead = now + } + if force || root != steamRoot || lastFullRead.map({ now.timeIntervalSince($0) >= 5 }) != false { + accountGames = try SteamAccountLibraryScanner.scan(steamRoot: steamRoot, installed: records) + activities = SteamActivityScanner.scan(steamRoot: steamRoot) + libraries = SteamLibraryLocation.load(steamRoot: steamRoot, bottleRoot: bottleRoot) + root = steamRoot + lastFullRead = now + } + // Installation readiness changes faster than the account scan cadence. + let installedIDs = Set(records.filter(\.isReadyToPlay).map(\.appID)) + let games = accountGames.map { + SteamAccountGame(appID: $0.appID, name: $0.name, playtimeMinutes: $0.playtimeMinutes, + lastPlayed: $0.lastPlayed, isInstalled: installedIDs.contains($0.appID), + localArtworkDirectory: $0.localArtworkDirectory, headerImageURL: $0.headerImageURL, + description: $0.description) + } + return Snapshot(records: records, readyAppIDs: installedIDs, accountGames: games, activities: activities, libraries: libraries) + } +} + +public struct SteamMetadataRetryPolicy: Sendable { + private var failures: [UInt64: (attempts: Int, retryAt: Date)] = [:] + public init() {} + public func canAttempt(_ appID: UInt64, now: Date = Date()) -> Bool { + failures[appID].map { now >= $0.retryAt } ?? true + } + public mutating func failed(_ appID: UInt64, now: Date = Date()) { + let attempts = min((failures[appID]?.attempts ?? 0) + 1, 6) + let delay = min(300.0, 10.0 * pow(2, Double(attempts - 1))) + failures[appID] = (attempts, now.addingTimeInterval(delay)) + } + public mutating func succeeded(_ appID: UInt64) { failures[appID] = nil } + public mutating func reset() { failures.removeAll() } +} diff --git a/Sources/IndieCatalog/SteamStoreSearchState.swift b/Sources/IndieCatalog/SteamStoreSearchState.swift new file mode 100644 index 0000000..16e7882 --- /dev/null +++ b/Sources/IndieCatalog/SteamStoreSearchState.swift @@ -0,0 +1,35 @@ +import Foundation + +/// A response may update the UI only if it belongs to the active search. +public struct SteamStoreSearchState: Sendable, Equatable { + public enum Phase: Sendable, Equatable { case idle, waiting, loading, results, empty, failed(String) } + public private(set) var query = "" + public private(set) var phase: Phase = .idle + public private(set) var results: [SteamStoreItem] = [] + private var requestID = UUID() + public init() {} + public var isLoading: Bool { phase == .loading } + public var completed: Bool { phase == .results || phase == .empty } + public var error: String? { if case .failed(let message) = phase { message } else { nil } } + + public mutating func reset(_ query: String) { + requestID = UUID() + self.query = query.trimmingCharacters(in: .whitespacesAndNewlines) + phase = self.query.count < 2 ? .idle : .waiting + results = [] + } + public mutating func begin(_ query: String) -> UUID { + reset(query) + phase = .loading + return requestID + } + public mutating func complete(_ items: [SteamStoreItem], requestID: UUID) { + guard self.requestID == requestID, phase == .loading else { return } + results = items + phase = items.isEmpty ? .empty : .results + } + public mutating func fail(_ message: String, requestID: UUID) { + guard self.requestID == requestID, phase == .loading else { return } + phase = .failed(message) + } +} diff --git a/Sources/IndieCore/Models.swift b/Sources/IndieCore/Models.swift index 47015e1..0b74967 100644 --- a/Sources/IndieCore/Models.swift +++ b/Sources/IndieCore/Models.swift @@ -326,6 +326,7 @@ public struct GameConfiguration: Codable, Hashable, Sendable, Identifiable { public var controllerMode: ControllerMode public var controllerRumble: Bool public var frameInterpolation: Bool? + public var spatialAudioDiagnostics: Bool? public var arguments: [String] public var updatedAt: Date @@ -340,6 +341,7 @@ public struct GameConfiguration: Codable, Hashable, Sendable, Identifiable { controllerMode: ControllerMode = .automatic, controllerRumble: Bool = true, frameInterpolation: Bool? = nil, + spatialAudioDiagnostics: Bool? = nil, arguments: [String] = [], updatedAt: Date = Date() ) { @@ -353,6 +355,7 @@ public struct GameConfiguration: Codable, Hashable, Sendable, Identifiable { self.controllerMode = controllerMode self.controllerRumble = controllerRumble self.frameInterpolation = frameInterpolation + self.spatialAudioDiagnostics = spatialAudioDiagnostics self.arguments = arguments self.updatedAt = updatedAt } @@ -363,7 +366,8 @@ public struct GameConfiguration: Codable, Hashable, Sendable, Identifiable { public var isCustomized: Bool { virtualDesktop != nil || preferredRenderer != nil || syncBackend != .automatic || metalHUD != .inherit || metalFX != .inherit || metal4 != .inherit || - controllerMode != .automatic || !controllerRumble || frameInterpolation == true || !arguments.isEmpty + controllerMode != .automatic || !controllerRumble || frameInterpolation == true || + spatialAudioDiagnostics == true || !arguments.isEmpty } } diff --git a/Sources/IndieCore/Resources/en.lproj/Localizable.strings b/Sources/IndieCore/Resources/en.lproj/Localizable.strings index 4827a79..f616b70 100644 --- a/Sources/IndieCore/Resources/en.lproj/Localizable.strings +++ b/Sources/IndieCore/Resources/en.lproj/Localizable.strings @@ -597,3 +597,81 @@ "重试安装" = "Retry Installation"; "Steam 尚未联机,请打开 Steam 客户端恢复连接后重试" = "Steam is not connected. Open Steam to restore the connection, then retry"; "Steam 未联机" = "Steam disconnected"; + +"正在运行" = "Running"; + +"当前使用" = "Current selection"; + +"使用此版本" = "Use this version"; + +"删除 Wine 版本?" = "Delete Wine version?"; + +"当前使用的版本用于下一次启动;切换前请先退出游戏和 Windows Steam。删除会移到废纸篓,保留游戏和容器。" = "The selected version is used on the next launch. Quit games and Windows Steam before switching. Deleted versions move to Trash; games and bottles are kept."; + +"将 %@ 移到废纸篓。游戏和容器不会被删除。" = "Move %@ to Trash. Games and bottles will be kept."; + +"正在切换 Wine…" = "Switching Wine…"; + +"请先退出游戏和 Windows Steam,再切换 Wine" = "Quit games and Windows Steam before switching Wine"; + +"游戏引擎只能选择 Mac Gaming Uncle Wine 版本" = "Select a Mac Gaming Uncle Wine version for the game engine"; + +"Wine 已切换为 %@" = "Wine switched to %@"; + +"正在删除 Wine…" = "Deleting Wine…"; + +"请先切换到其他 Wine,再删除当前使用的版本" = "Switch to another Wine before deleting the current selection"; + +"Wine 已移到废纸篓,游戏和容器已保留" = "Wine moved to Trash; games and bottles kept"; + +"只能删除应用管理的已安装 Wine 版本" = "Only installed Wine versions managed by this app can be deleted"; + +"这个 Wine 仍在运行,请先退出游戏和 Windows Steam" = "This Wine is still running. Quit games and Windows Steam first"; + +"正在搜索 Steam 商店…" = "Searching the Steam store…"; + +"搜索失败" = "Search failed"; + +"没有找到匹配的游戏" = "No matching games"; + +"请输入至少两个字符" = "Enter at least two characters"; + +"试试游戏的英文名或更短的关键词" = "Try the English title or a shorter search term"; + +"即将搜索…" = "Search starting…"; + +"返回精选" = "Back to featured"; + +"精选游戏" = "Featured games"; + +"没有匹配的游戏" = "No matching games"; + +"调整搜索关键词或筛选条件" = "Change your search or filters"; + +"显示全部游戏" = "Show all games"; + +"正在补全游戏名称与封面…" = "Loading game names and artwork…"; + +"兼容性需实测" = "Compatibility needs testing"; + +"Steam 已连接" = "Steam connected"; + +"在 Steam 中获取" = "Get it in Steam"; + +"上一组游戏" = "Previous games"; + +"下一组游戏" = "Next games"; + +"你的游戏" = "Your games"; + +"商店分类" = "Store category"; + +"清除搜索" = "Clear search"; + +"游戏库筛选" = "Library filter"; + +"最小化窗口" = "Minimize Window"; + +"最大化或恢复窗口" = "Zoom / Restore Window"; + +"进入或退出全屏" = "Enter / Exit Full Screen"; diff --git a/Sources/IndieCore/Resources/zh-Hans.lproj/Localizable.strings b/Sources/IndieCore/Resources/zh-Hans.lproj/Localizable.strings index 5cf309d..afb0999 100644 --- a/Sources/IndieCore/Resources/zh-Hans.lproj/Localizable.strings +++ b/Sources/IndieCore/Resources/zh-Hans.lproj/Localizable.strings @@ -597,3 +597,81 @@ "重试安装" = "重试安装"; "Steam 尚未联机,请打开 Steam 客户端恢复连接后重试" = "Steam 尚未联机,请打开 Steam 客户端恢复连接后重试"; "Steam 未联机" = "Steam 未联机"; + +"正在运行" = "正在运行"; + +"当前使用" = "当前使用"; + +"使用此版本" = "使用此版本"; + +"删除 Wine 版本?" = "删除 Wine 版本?"; + +"当前使用的版本用于下一次启动;切换前请先退出游戏和 Windows Steam。删除会移到废纸篓,保留游戏和容器。" = "当前使用的版本用于下一次启动;切换前请先退出游戏和 Windows Steam。删除会移到废纸篓,保留游戏和容器。"; + +"将 %@ 移到废纸篓。游戏和容器不会被删除。" = "将 %@ 移到废纸篓。游戏和容器不会被删除。"; + +"正在切换 Wine…" = "正在切换 Wine…"; + +"请先退出游戏和 Windows Steam,再切换 Wine" = "请先退出游戏和 Windows Steam,再切换 Wine"; + +"游戏引擎只能选择 Mac Gaming Uncle Wine 版本" = "游戏引擎只能选择 Mac Gaming Uncle Wine 版本"; + +"Wine 已切换为 %@" = "Wine 已切换为 %@"; + +"正在删除 Wine…" = "正在删除 Wine…"; + +"请先切换到其他 Wine,再删除当前使用的版本" = "请先切换到其他 Wine,再删除当前使用的版本"; + +"Wine 已移到废纸篓,游戏和容器已保留" = "Wine 已移到废纸篓,游戏和容器已保留"; + +"只能删除应用管理的已安装 Wine 版本" = "只能删除应用管理的已安装 Wine 版本"; + +"这个 Wine 仍在运行,请先退出游戏和 Windows Steam" = "这个 Wine 仍在运行,请先退出游戏和 Windows Steam"; + +"正在搜索 Steam 商店…" = "正在搜索 Steam 商店…"; + +"搜索失败" = "搜索失败"; + +"没有找到匹配的游戏" = "没有找到匹配的游戏"; + +"请输入至少两个字符" = "请输入至少两个字符"; + +"试试游戏的英文名或更短的关键词" = "试试游戏的英文名或更短的关键词"; + +"即将搜索…" = "即将搜索…"; + +"返回精选" = "返回精选"; + +"精选游戏" = "精选游戏"; + +"没有匹配的游戏" = "没有匹配的游戏"; + +"调整搜索关键词或筛选条件" = "调整搜索关键词或筛选条件"; + +"显示全部游戏" = "显示全部游戏"; + +"正在补全游戏名称与封面…" = "正在补全游戏名称与封面…"; + +"兼容性需实测" = "兼容性需实测"; + +"Steam 已连接" = "Steam 已连接"; + +"在 Steam 中获取" = "在 Steam 中获取"; + +"上一组游戏" = "上一组游戏"; + +"下一组游戏" = "下一组游戏"; + +"你的游戏" = "你的游戏"; + +"商店分类" = "商店分类"; + +"清除搜索" = "清除搜索"; + +"游戏库筛选" = "游戏库筛选"; + +"最小化窗口" = "最小化窗口"; + +"最大化或恢复窗口" = "最大化或恢复窗口"; + +"进入或退出全屏" = "进入或退出全屏"; diff --git a/Sources/IndieRuntime/CommunityIndieWineBootstrapper.swift b/Sources/IndieRuntime/CommunityIndieWineBootstrapper.swift index c59e783..abd1b12 100644 --- a/Sources/IndieRuntime/CommunityIndieWineBootstrapper.swift +++ b/Sources/IndieRuntime/CommunityIndieWineBootstrapper.swift @@ -101,6 +101,20 @@ public actor CommunityIndieWineBootstrapper { return isCompleteRuntime(nested) ? nested : source } + /// Recognize our extracted build without misclassifying arbitrary Wine + /// distributions. Keeps the managed identity and full prerelease version + /// when the user imports through the application's general Wine picker. + static func managedBuildRoot(in source: URL) -> URL? { + for root in [source, source.appendingPathComponent("wine-runtime", isDirectory: true)] { + guard isCompleteRuntime(root), runtimeVersion(in: root) != nil, + let data = try? Data(contentsOf: root.appendingPathComponent("source.lock.json")), + let lock = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + lock["runtime"] as? String == "Mac Gaming Uncle Wine 11" else { continue } + return root + } + return nil + } + public static func isCompleteRuntime(_ root: URL) -> Bool { LocalWineImporter.findWine(in: root) != nil && FileManager.default.isExecutableFile(atPath: root.appendingPathComponent("bin/wineserver").path) && diff --git a/Sources/IndieRuntime/LocalWineImporter.swift b/Sources/IndieRuntime/LocalWineImporter.swift index 66e0849..e53071f 100644 --- a/Sources/IndieRuntime/LocalWineImporter.swift +++ b/Sources/IndieRuntime/LocalWineImporter.swift @@ -18,6 +18,9 @@ public actor LocalWineImporter { } public func importRuntime(from source: URL) async throws -> LocalWineRuntime { + if let managed = CommunityIndieWineBootstrapper.managedBuildRoot(in: source) { + return try await CommunityIndieWineBootstrapper(paths: paths).installLocalBuild(from: managed) + } try paths.createDirectories() guard let sourceWine = Self.findWine(in: source) else { throw IndieError.notFound(L("所选目录中没有 Wine 可执行文件")) @@ -94,6 +97,30 @@ public actor LocalWineImporter { }.sorted { $0.manifest.version > $1.manifest.version } } + /// Only remove an installed version owned by this importer. Moving to Trash + /// leaves the user's bottles and games intact and allows recovery. + public func removeRuntime(_ runtime: LocalWineRuntime) throws { + let expected = paths.runtimes.appendingPathComponent(runtime.manifest.id) + .appendingPathComponent(runtime.manifest.version.description).standardizedFileURL + let root = runtime.root.standardizedFileURL + guard root == expected, + root.resolvingSymlinksInPath().deletingLastPathComponent().deletingLastPathComponent() + == paths.runtimes.resolvingSymlinksInPath(), + installed().contains(where: { $0.id == runtime.id && $0.root.standardizedFileURL == root }) else { + throw IndieError.invalidData(L("只能删除应用管理的已安装 Wine 版本")) + } + guard !WineProcessReaper.hasRunningProcesses(runtimeRoot: root) else { + throw IndieError.invalidData(L("这个 Wine 仍在运行,请先退出游戏和 Windows Steam")) + } + try FileManager.default.trashItem(at: root, resultingItemURL: nil) + } + + public static func selectedGamingRuntime(in runtimes: [LocalWineRuntime], preferredID: String?) -> LocalWineRuntime? { + let candidates = runtimes.filter { $0.manifest.id == CommunityIndieWineBootstrapper.runtimeID } + .sorted { $0.manifest.version > $1.manifest.version } + return candidates.first { $0.id == preferredID } ?? candidates.first + } + public static func findWine(in root: URL) -> URL? { let directCandidates = [ root.appendingPathComponent("bin/wine64"), root.appendingPathComponent("bin/wine"), diff --git a/Sources/IndieRuntime/SpatialAudioDiagnostics.swift b/Sources/IndieRuntime/SpatialAudioDiagnostics.swift new file mode 100644 index 0000000..ccdb656 --- /dev/null +++ b/Sources/IndieRuntime/SpatialAudioDiagnostics.swift @@ -0,0 +1,8 @@ +public enum SpatialAudioDiagnostics { + public static func environment(enabled: Bool) -> [String: String] { + enabled ? [ + "WINEDEBUG": "-all,+mmdevapi,+coreaudio", + "SWITCHYARD_SPATIAL_AUDIO_PROFILE": "1", + ] : [:] + } +} diff --git a/Sources/IndieRuntime/WineProcessReaper.swift b/Sources/IndieRuntime/WineProcessReaper.swift index 41986c4..52c4ce6 100644 --- a/Sources/IndieRuntime/WineProcessReaper.swift +++ b/Sources/IndieRuntime/WineProcessReaper.swift @@ -3,6 +3,9 @@ import Darwin import Foundation public enum WineProcessReaper { + public static func hasRunningProcesses(runtimeRoot: URL) -> Bool { + !processes(runtimeRoot: runtimeRoot).isEmpty + } /// Terminates processes whose real host executable belongs to Mac Gaming Uncle's /// private Wine runtime. This is a fallback for orphaned Wine clients that /// no longer respond to `wineserver -k` after the parent app has exited. @@ -39,15 +42,16 @@ public enum WineProcessReaper { ) guard byteCount > 0 else { return [] } let count = min(Int(byteCount) / MemoryLayout.size, pids.count) - let prefix = runtimeRoot.standardizedFileURL.path + "/" + let prefix = runtimeRoot.resolvingSymlinksInPath().standardizedFileURL.path + "/" var result: [(Int32, URL)] = [] for pid in pids.prefix(count) where pid > 1 && pid != getpid() { var pathBuffer = [CChar](repeating: 0, count: Int(MAXPATHLEN) * 4) guard proc_pidpath(pid, &pathBuffer, UInt32(pathBuffer.count)) > 0 else { continue } let bytes = pathBuffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) } let path = String(decoding: bytes, as: UTF8.self) - guard path.hasPrefix(prefix) else { continue } - result.append((pid, URL(fileURLWithPath: path))) + let executable = URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL + guard executable.path.hasPrefix(prefix) else { continue } + result.append((pid, executable)) } return result } diff --git a/Sources/MacGamingUncleApp/ContentView.swift b/Sources/MacGamingUncleApp/ContentView.swift index e10722c..d1b3632 100644 --- a/Sources/MacGamingUncleApp/ContentView.swift +++ b/Sources/MacGamingUncleApp/ContentView.swift @@ -54,7 +54,7 @@ struct ContentView: View { .background(WindowPlacementReader().frame(width: 0, height: 0)) .task { while !Task.isCancelled { - model.syncSteamLibrary() + await model.syncSteamLibrary() do { try await Task.sleep(for: .seconds(model.steamDownloads.isEmpty && model.steamInstallationRequests.isEmpty ? 5 : 1)) } catch { return } } @@ -826,11 +826,16 @@ struct AdvancedSettingsView: View { private struct RuntimeSettingsContent: View { @EnvironmentObject private var model: MacGamingUncleAppModel + @State private var pendingWineDeletion: LocalWineRuntime? var body: some View { ScrollView { VStack(alignment: .leading, spacing: 18) { advancedSection(title: L("Wine 运行环境"), detail: L("Mac Gaming Uncle 自行从 LGPL 源码构建 Wine 11 新 WoW64 运行时;不封装或分发 CrossOver 应用。")) { - ForEach(model.wineRuntimes) { runtime in componentRow(name: runtime.manifest.displayName, status: L("已安装")) } + ForEach(model.wineRuntimes) { runtime in + wineRow(runtime) + } + Text(L("当前使用的版本用于下一次启动;切换前请先退出游戏和 Windows Steam。删除会移到废纸篓,保留游戏和容器。")) + .font(.caption).foregroundStyle(.secondary) HStack { Button(L("自动安装最新版本")) { Task { await model.prepareEnvironment() } }.buttonStyle(.borderedProminent) Button(L("导入本地 Wine")) { chooseWine() } @@ -863,6 +868,27 @@ private struct RuntimeSettingsContent: View { } .padding(24) } + .task { + while !Task.isCancelled { + model.refreshWineUsage() + do { try await Task.sleep(for: .seconds(2)) } + catch { break } + } + } + .alert(L("删除 Wine 版本?"), isPresented: Binding( + get: { pendingWineDeletion != nil }, + set: { if !$0 { pendingWineDeletion = nil } } + )) { + Button(L("取消"), role: .cancel) { pendingWineDeletion = nil } + Button(L("删除"), role: .destructive) { + if let runtime = pendingWineDeletion { + Task { await model.deleteWineRuntime(runtime) } + } + pendingWineDeletion = nil + } + } message: { + Text(L("将 \(pendingWineDeletion?.manifest.displayName ?? "") 移到废纸篓。游戏和容器不会被删除。")) + } } private func advancedSection(title: String, detail: String, @ViewBuilder content: () -> Content) -> some View { VStack(alignment: .leading, spacing: 12) { @@ -871,6 +897,26 @@ private struct RuntimeSettingsContent: View { .frame(maxWidth: .infinity, alignment: .leading).padding(18) .background(IndiePalette.surface, in: RoundedRectangle(cornerRadius: 14)).overlay(RoundedRectangle(cornerRadius: 14).stroke(IndiePalette.border)) } + private func wineRow(_ runtime: LocalWineRuntime) -> some View { + let selected = model.gamingWineRuntime?.id == runtime.id + let running = model.runningWineRuntimeIDs.contains(runtime.id) + return HStack { + VStack(alignment: .leading, spacing: 4) { + Text(runtime.manifest.displayName).font(.system(size: 13.5, weight: .medium)) + Text(runtime.manifest.version.description).font(.caption).foregroundStyle(.secondary) + } + Spacer() + if running { Text(L("正在运行")).foregroundStyle(IndiePalette.green) } + if selected { Label(L("当前使用"), systemImage: "checkmark.circle.fill").foregroundStyle(IndiePalette.green) } + if !selected && runtime.manifest.id == CommunityIndieWineBootstrapper.runtimeID { + Button(L("使用此版本")) { Task { await model.selectWineRuntime(runtime) } } + .disabled(model.isWorking || !model.runningWineRuntimeIDs.isEmpty) + } + Button(L("删除"), role: .destructive) { pendingWineDeletion = runtime } + .disabled(model.isWorking || selected || running) + }.font(.system(size: 12.5)) + } + private func componentRow(name: String, status: String) -> some View { HStack { Image(systemName: "checkmark.circle.fill").foregroundStyle(IndiePalette.green); Text(name).font(.system(size: 13.5, weight: .medium)); Spacer(); Text(status).font(.system(size: 12.5)).foregroundStyle(IndiePalette.secondaryText) } } diff --git a/Sources/MacGamingUncleApp/FocusDeckHomeView.swift b/Sources/MacGamingUncleApp/FocusDeckHomeView.swift index 0966f4d..16cb4e9 100644 --- a/Sources/MacGamingUncleApp/FocusDeckHomeView.swift +++ b/Sources/MacGamingUncleApp/FocusDeckHomeView.swift @@ -17,10 +17,11 @@ struct FocusDeckHomeView: View { if let game = selectedGame ?? games.first { ScrollView { VStack(spacing: 0) { - hero(game, height: max(480, min(590, geometry.size.height * 0.61))) + hero(game, height: max(560, min(650, geometry.size.height * 0.68)), width: geometry.size.width) detailPanels(game) .padding(.horizontal, 28).padding(.top, 18).padding(.bottom, 14) } + .frame(width: geometry.size.width) .frame(minHeight: geometry.size.height) } .scrollIndicators(.hidden) @@ -36,10 +37,10 @@ struct FocusDeckHomeView: View { .onChange(of: model.steamAccountGames.map(\.appID)) { _, _ in chooseInitialGame() } } - private func hero(_ game: SteamAccountGame, height: CGFloat) -> some View { + private func hero(_ game: SteamAccountGame, height: CGFloat, width: CGFloat) -> some View { ZStack(alignment: .bottom) { heroArtwork(game) - .frame(maxWidth: .infinity, minHeight: height, maxHeight: height).clipped() + .frame(width: width, height: height).clipped() LinearGradient( stops: [ @@ -57,7 +58,7 @@ struct FocusDeckHomeView: View { .font(.system(size: 13, weight: .semibold)).foregroundStyle(Color.white.opacity(0.72)) Text(game.name) .font(.system(size: 46, weight: .bold, design: .rounded)) - .tracking(-0.8).lineLimit(1) + .tracking(-0.8).lineLimit(2).minimumScaleFactor(0.75).help(game.name) HStack(spacing: 20) { Label(playtime(game.playtimeMinutes), systemImage: "clock") if let date = game.lastPlayed { @@ -66,11 +67,11 @@ struct FocusDeckHomeView: View { } .font(.system(size: 14, weight: .medium)).foregroundStyle(Color.white.opacity(0.67)) HStack(spacing: 24) { - Label(L("兼容性优秀"), systemImage: "checkmark.seal.fill") - .foregroundStyle(IndiePalette.green) + Label(L("兼容性需实测"), systemImage: "questionmark.circle") + .foregroundStyle(Color.white.opacity(0.72)) Label( - model.steamSessionManager.state == .running ? L("云存档已同步") : L("Steam 待连接"), - systemImage: model.steamSessionManager.state == .running ? "cloud.fill" : "cloud" + model.steamSessionManager.state == .running ? L("Steam 已连接") : L("Steam 待连接"), + systemImage: model.steamSessionManager.state == .running ? "checkmark.circle" : "network" ) .foregroundStyle(Color.white.opacity(0.72)) } @@ -94,53 +95,48 @@ struct FocusDeckHomeView: View { Spacer(minLength: 28) gameCarousel + .frame(width: max(0, width - 116)) .padding(.horizontal, 58).padding(.bottom, 14) } - .frame(height: height) + .frame(width: width, height: height) } - .frame(height: height) + .frame(width: width, height: height) } private var gameCarousel: some View { - ScrollView(.horizontal) { - HStack(spacing: 14) { - ForEach(games) { game in - Button { withAnimation(.easeOut(duration: 0.2)) { selection = game.appID } } label: { - ZStack(alignment: .bottomLeading) { - AsyncImage(url: game.coverImageURL) { phase in - if case .success(let image) = phase { - image.resizable().scaledToFill() - } else { - AsyncImage(url: game.headerImageURL) { image in - image.resizable().scaledToFill() - } placeholder: { - IndiePalette.surfaceStrong.overlay( - Image(systemName: "gamecontroller.fill") - .font(.system(size: 24)).foregroundStyle(IndiePalette.secondaryText) - ) - } - } + GameCarouselView(title: L("你的游戏"), items: games, cardWidth: 132) { game in + Button { withAnimation(.easeOut(duration: 0.2)) { selection = game.appID } } label: { + ZStack(alignment: .bottomLeading) { + AsyncImage(url: game.coverImageURL) { phase in + if case .success(let image) = phase { + image.resizable().scaledToFill() + } else { + AsyncImage(url: game.headerImageURL) { image in + image.resizable().scaledToFill() + } placeholder: { + IndiePalette.surfaceStrong.overlay( + Image(systemName: "gamecontroller.fill") + .font(.system(size: 24)).foregroundStyle(IndiePalette.secondaryText) + ) } - .frame(width: 132, height: 186).clipped() - LinearGradient(colors: [.clear, Color.black.opacity(0.76)], startPoint: .center, endPoint: .bottom) - Text(game.name).font(.system(size: 11.5, weight: .semibold)).lineLimit(2) - .padding(9) } - .frame(width: 132, height: 186) - .clipShape(RoundedRectangle(cornerRadius: 10)) - .overlay(RoundedRectangle(cornerRadius: 10).stroke( - selection == game.appID ? IndiePalette.blue : Color.white.opacity(0.14), - lineWidth: selection == game.appID ? 2 : 1 - )) - .shadow(color: selection == game.appID ? IndiePalette.blue.opacity(0.34) : .clear, radius: 12) - .scaleEffect(selection == game.appID ? 1.035 : 1) } - .buttonStyle(.plain).accessibilityLabel(game.name) + .frame(width: 132, height: 186).clipped() + LinearGradient(colors: [.clear, Color.black.opacity(0.76)], startPoint: .center, endPoint: .bottom) + Text(game.name).font(.system(size: 11.5, weight: .semibold)).lineLimit(2) + .padding(9) } + .frame(width: 132, height: 186) + .clipShape(RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).stroke( + selection == game.appID ? IndiePalette.blue : Color.white.opacity(0.14), + lineWidth: selection == game.appID ? 2 : 1 + )) + .shadow(color: selection == game.appID ? IndiePalette.blue.opacity(0.34) : .clear, radius: 12) + .scaleEffect(selection == game.appID ? 1.035 : 1) } - .padding(.vertical, 10) + .buttonStyle(.plain).accessibilityLabel(game.name).help(game.name) } - .scrollIndicators(.hidden) } @ViewBuilder @@ -237,7 +233,7 @@ struct FocusDeckHomeView: View { } description: { Text(L("Steam 登录后会自动同步游戏库,首次同步可能需要一些时间。")) } actions: { - Button(L("同步游戏库")) { model.syncSteamLibrary() }.buttonStyle(.borderedProminent) + Button(L("同步游戏库")) { Task { await model.syncSteamLibrary() } }.buttonStyle(.borderedProminent) Button(L("Steam 登录窗口")) { Task { await model.launchSteam() } } .disabled(model.isWorking || model.onboardingBusy) Text(model.status).font(.caption).foregroundStyle(.secondary) diff --git a/Sources/MacGamingUncleApp/GameCarouselView.swift b/Sources/MacGamingUncleApp/GameCarouselView.swift new file mode 100644 index 0000000..7365f81 --- /dev/null +++ b/Sources/MacGamingUncleApp/GameCarouselView.swift @@ -0,0 +1,58 @@ +import IndieCore +import SwiftUI + +struct GameCarouselView: View where Item.ID: Sendable { + let title: String + let items: [Item] + let cardWidth: CGFloat + let card: (Item) -> Card + @State private var leadingID: Item.ID? + @State private var pageSize = 3 + + init(title: String, items: [Item], cardWidth: CGFloat, @ViewBuilder card: @escaping (Item) -> Card) { + self.title = title + var seen = Set() + self.items = items.filter { seen.insert($0.id).inserted } + self.cardWidth = cardWidth + self.card = card + } + + private var index: Int { items.firstIndex { $0.id == leadingID } ?? 0 } + private var lastPageIndex: Int { max(0, items.count - pageSize) } + + var body: some View { + let measuredCardWidth = cardWidth + return VStack(alignment: .leading, spacing: 13) { + HStack { + Text(title).font(.system(size: 19, weight: .semibold)) + Spacer() + Text(L("\(items.count) 款")).font(.caption).foregroundStyle(IndiePalette.secondaryText) + Button { move(-pageSize) } label: { Image(systemName: "chevron.left") } + .disabled(index == 0).help(L("上一组游戏")).accessibilityLabel(L("上一组游戏")) + Button { move(pageSize) } label: { Image(systemName: "chevron.right") } + .disabled(index >= lastPageIndex).help(L("下一组游戏")).accessibilityLabel(L("下一组游戏")) + } + .buttonStyle(.bordered) + ScrollView(.horizontal) { + HStack(spacing: 14) { + ForEach(items) { item in card(item).frame(width: cardWidth).id(item.id) } + } + .scrollTargetLayout().padding(.vertical, 10) + } + .frame(maxWidth: .infinity) + .scrollTargetBehavior(.viewAligned) + .scrollPosition(id: $leadingID, anchor: .leading) + .scrollIndicators(.visible) + .onGeometryChange(for: Int.self) { max(1, Int(($0.size.width + 14) / (measuredCardWidth + 14))) } action: { pageSize = $0 } + } + .onChange(of: items.map(\.id)) { _, ids in + if !ids.contains(where: { $0 == leadingID }) { leadingID = ids.first } + } + } + + private func move(_ offset: Int) { + guard !items.isEmpty else { return } + let target = min(max(0, index + offset), lastPageIndex) + withAnimation(.easeInOut(duration: 0.25)) { leadingID = items[target].id } + } +} diff --git a/Sources/MacGamingUncleApp/GameSettingsView.swift b/Sources/MacGamingUncleApp/GameSettingsView.swift index 5f6a5d1..3703a43 100644 --- a/Sources/MacGamingUncleApp/GameSettingsView.swift +++ b/Sources/MacGamingUncleApp/GameSettingsView.swift @@ -140,6 +140,15 @@ struct GameSettingsView: View { .font(.caption).foregroundStyle(.secondary) } + Section(L("音频诊断")) { + Toggle(L("记录空间音频诊断日志"), isOn: Binding( + get: { configuration.spatialAudioDiagnostics == true }, + set: { configuration.spatialAudioDiagnostics = $0 ? true : nil } + )) + Text(L("用于确认游戏是否提交空间音频对象。日志会增加运行开销;短时测试结束后关闭,并重新启动游戏。")) + .font(.caption).foregroundStyle(.secondary) + } + Section(L("启动参数")) { TextEditor(text: $argumentLines).font(.system(.body, design: .monospaced)).frame(minHeight: 70) Text(L("每行一个参数;仅应用于这个游戏。")) diff --git a/Sources/MacGamingUncleApp/MacGamingUncleAppModel.swift b/Sources/MacGamingUncleApp/MacGamingUncleAppModel.swift index 88e641b..9511092 100644 --- a/Sources/MacGamingUncleApp/MacGamingUncleAppModel.swift +++ b/Sources/MacGamingUncleApp/MacGamingUncleAppModel.swift @@ -36,14 +36,27 @@ final class MacGamingUncleAppModel: ObservableObject { @Published var steamAccountGames: [SteamAccountGame] = [] @Published var steamActivities: [UInt64: SteamGameActivity] = [:] @Published var steamStoreCatalog: SteamStoreCatalog? - @Published var steamStoreSearchResults: [SteamStoreItem] = [] + @Published private(set) var steamSearchState = SteamStoreSearchState() + var steamStoreSearchResults: [SteamStoreItem] { steamSearchState.results } @Published var steamStoreSelectedAppID: UInt64? @Published var isSteamStoreLoading = false @Published var steamStoreError: String? + var isSteamSearchLoading: Bool { steamSearchState.isLoading } + var steamSearchQuery: String { steamSearchState.query } + var steamSearchCompleted: Bool { steamSearchState.completed } + var steamSearchError: String? { steamSearchState.error } + private var steamSearchTask: Task<[SteamStoreItem], Error>? + private let steamLibraryReader = SteamLibraryReader() + private var steamMetadataRetry = SteamMetadataRetryPolicy() + private var steamMetadataCacheLoaded = false + private var steamMetadataCacheLoadTask: Task<[UInt64: SteamStoreMetadataService.Metadata], Never>? + @Published private(set) var isSteamMetadataLoading = false @Published var requestedDestination: String? @Published var bottles: [BottleRecord] = [] @Published var d3dMetal: [ImportedD3DMetal] = [] @Published var wineRuntimes: [LocalWineRuntime] = [] + @Published private(set) var selectedWineRuntimeID = UserDefaults.standard.string(forKey: "selectedWineRuntimeID") + @Published private(set) var runningWineRuntimeIDs: Set = [] @Published var rendererOverlays: [RendererOverlay] = [] @Published var gameConfigurations: [String: GameConfiguration] = [:] @Published var isWorking = false @@ -82,8 +95,43 @@ final class MacGamingUncleAppModel: ObservableObject { private var preferredD3DMetal: ImportedD3DMetal? { d3dMetal.first { $0.rendererRoot != nil } } - private var gamingWineRuntime: LocalWineRuntime? { - wineRuntimes.first { $0.manifest.id == CommunityIndieWineBootstrapper.runtimeID } + var gamingWineRuntime: LocalWineRuntime? { + LocalWineImporter.selectedGamingRuntime(in: wineRuntimes, preferredID: selectedWineRuntimeID) + } + + func refreshWineUsage() { + runningWineRuntimeIDs = Set(wineRuntimes.filter { + WineProcessReaper.hasRunningProcesses(runtimeRoot: $0.root) + }.map(\.id)) + } + + func selectWineRuntime(_ runtime: LocalWineRuntime) async { + await perform(L("正在切换 Wine…")) { + self.refreshWineUsage() + guard self.runningWineRuntimeIDs.isEmpty else { + throw IndieError.invalidData(L("请先退出游戏和 Windows Steam,再切换 Wine")) + } + guard self.wineRuntimes.contains(runtime), + runtime.manifest.id == CommunityIndieWineBootstrapper.runtimeID else { + throw IndieError.unsupported(L("游戏引擎只能选择 Mac Gaming Uncle Wine 版本")) + } + self.selectedWineRuntimeID = runtime.id + UserDefaults.standard.set(runtime.id, forKey: "selectedWineRuntimeID") + self.steamSessionManager.didStop() + self.status = L("Wine 已切换为 \(runtime.manifest.version)") + } + } + + func deleteWineRuntime(_ runtime: LocalWineRuntime) async { + await perform(L("正在删除 Wine…")) { + guard runtime.id != self.gamingWineRuntime?.id else { + throw IndieError.invalidData(L("请先切换到其他 Wine,再删除当前使用的版本")) + } + try await self.wineImporter.removeRuntime(runtime) + self.wineRuntimes = await self.wineImporter.installed() + self.refreshWineUsage() + self.status = L("Wine 已移到废纸篓,游戏和容器已保留") + } } var gptkRuntimeVersion: String? { preferredD3DMetal?.version ?? preferredGPTKRuntime?.version } var d3dMetalRuntimeAvailable: Bool { @@ -298,7 +346,7 @@ final class MacGamingUncleAppModel: ObservableObject { } steamSessionManager.didLaunch(.init(bottleID: bottle.id, runtimeID: runtime.manifest.id, environment: plan.environment, virtualDesktop: nil), reused: false) - try scanDefaultSteamLibrary() + try await scanDefaultSteamLibrary() UserDefaults.standard.set(true, forKey: "firstRunSteamLoginCompleted") onboardingStage = .complete requestedDestination = "library" @@ -327,7 +375,7 @@ final class MacGamingUncleAppModel: ObservableObject { var loadedRecipes = try RecipeRepository.builtIn().recipes loadedRecipes.append(contentsOf: try RecipeRepository.load(from: paths.recipes).recipes) recipeRepository = RecipeRepository(recipes: loadedRecipes) - try scanDefaultSteamLibrary() + try await scanDefaultSteamLibrary() if self.steamSessionManager.state == .running, (self.steamBottle.map { SteamCompatibilityManager.isLoggedOn(in: $0) } != true) { self.steamSessionManager.didStop() @@ -456,7 +504,7 @@ final class MacGamingUncleAppModel: ObservableObject { guard SteamDownloadBridge.permitsPlay( manifestReady: (try? SteamScanner.refreshed(game).isReadyToPlay) == true, download: self.steamBridgeDownloads[game.appID]) else { - try self.scanDefaultSteamLibrary() + try await self.scanDefaultSteamLibrary() throw IndieError.invalidData(L("游戏尚未安装完成,请等待 Steam 完成下载和校验")) } guard let bottle = self.steamBottle else { @@ -570,6 +618,9 @@ final class MacGamingUncleAppModel: ObservableObject { } var gameEnvironment = environment + gameEnvironment.merge(SpatialAudioDiagnostics.environment( + enabled: configuration.spatialAudioDiagnostics == true + )) { _, configured in configured } gameEnvironment.merge( ControllerLaunchEnvironment.make( mode: configuration.controllerMode, @@ -770,10 +821,13 @@ final class MacGamingUncleAppModel: ObservableObject { } func rescanSteam() { - do { - try scanDefaultSteamLibrary() - status = steamGames.isEmpty ? L("尚未发现已安装的 Steam 游戏") : L("发现 \(steamGames.count) 个 Steam 游戏") - } catch { present(error) } + Task { + do { + steamMetadataRetry.reset() + try await scanDefaultSteamLibrary() + status = steamGames.isEmpty ? L("尚未发现已安装的 Steam 游戏") : L("发现 \(steamGames.count) 个 Steam 游戏") + } catch { present(error) } + } } func installSteamGame(appID: UInt64, library: SteamLibraryLocation? = nil) async { @@ -858,7 +912,7 @@ final class MacGamingUncleAppModel: ObservableObject { steamInstallationRequests[appID] = .confirmation steamClientNotice = L("Steam 需要额外确认。仅在你点击“在 Steam 中查看”时打开客户端") case .failed(let code): - try? scanDefaultSteamLibrary() + try? await scanDefaultSteamLibrary() if steamGames.contains(where: { $0.appID == appID }) { steamInstallationRequests[appID] = nil steamClientNotice = L("游戏已完成安装和校验") @@ -885,7 +939,7 @@ final class MacGamingUncleAppModel: ObservableObject { steamClientNotice = L("Steam 后台连接失败。可重试或打开 Steam;更新兼容组件后需退出并重新打开 Steam") } } - syncSteamLibrary() + await syncSteamLibrary() } private func downloadBridge() -> SteamDownloadBridge? { @@ -933,7 +987,7 @@ final class MacGamingUncleAppModel: ObservableObject { let windowsPath = try WinePath.windowsPath(for:root,in:bottle) try await bridge.addLibrary(windowsPath:windowsPath) refreshSteamLibraryLocations() - syncSteamLibrary() + await syncSteamLibrary() } catch { steamStorageError = error.localizedDescription } } @@ -965,7 +1019,7 @@ final class MacGamingUncleAppModel: ObservableObject { self.steamInstallationRequests[game.appID] = nil self.steamBridgeDownloads[game.appID] = nil self.steamDownloadSpeeds[game.appID] = nil - try self.scanDefaultSteamLibrary() + try await self.scanDefaultSteamLibrary() self.steamClientNotice = L("游戏已卸载,可随时重新安装") return } @@ -988,7 +1042,7 @@ final class MacGamingUncleAppModel: ObservableObject { // Never keep an obsolete percent/paused state after disconnect or client restart. self.steamBridgeDownloads = [:] } - try? self.scanDefaultSteamLibrary() + try? await self.scanDefaultSteamLibrary(force: false) let now = Date() let pendingIDs = Set(self.steamDownloads.map(\.appID)) self.downloadByteSamples = self.downloadByteSamples.filter { pendingIDs.contains($0.key) } @@ -1031,6 +1085,7 @@ final class MacGamingUncleAppModel: ObservableObject { } func loadNativeSteamStore(force: Bool = false) async { + guard !isSteamStoreLoading else { return } if !force, steamStoreCatalog != nil, let loadedAt = steamStoreLoadedAt, Date().timeIntervalSince(loadedAt) < 15 * 60 { return } isSteamStoreLoading = true @@ -1051,16 +1106,27 @@ final class MacGamingUncleAppModel: ObservableObject { } } + func resetSteamSearch(_ query: String) { + steamSearchTask?.cancel() + steamSearchTask = nil + steamSearchState.reset(query) + } + func searchNativeSteamStore(_ query: String) async { let term = query.trimmingCharacters(in: .whitespacesAndNewlines) - guard term.count >= 2 else { steamStoreSearchResults = []; return } - isSteamStoreLoading = true - steamStoreError = nil - defer { isSteamStoreLoading = false } + if term == steamSearchQuery, isSteamSearchLoading || steamSearchCompleted { return } + resetSteamSearch(term) + guard term.count >= 2 else { return } + let requestID = steamSearchState.begin(term) + let task = Task { try await SteamNativeStoreService.search(term) } + steamSearchTask = task do { - steamStoreSearchResults = try await SteamNativeStoreService.search(term) + let results = try await task.value + guard !task.isCancelled else { return } + steamSearchState.complete(results, requestID: requestID) } catch { - steamStoreError = L("搜索失败:\(error.localizedDescription)") + guard !task.isCancelled else { return } + steamSearchState.fail(L("搜索失败:\(error.localizedDescription)"), requestID: requestID) } } @@ -1187,6 +1253,9 @@ final class MacGamingUncleAppModel: ObservableObject { } else if renderer == .wineD3D { try await provider.configureWineD3DGraphics(in: bottle) } + environment.merge(SpatialAudioDiagnostics.environment( + enabled: configuration.spatialAudioDiagnostics == true + )) { _, configured in configured } let profile = LaunchProfile( runtimeID: runtime.manifest.id, preferredRenderer: renderer, @@ -1288,43 +1357,52 @@ final class MacGamingUncleAppModel: ObservableObject { status = L("操作失败") } - private func scanDefaultSteamLibrary() throws { + private func scanDefaultSteamLibrary(force: Bool = true) async throws { guard let bottle = steamBottle else { return } - refreshSteamLibraryLocations() - let previousIDs = steamAccountGames.map(\.appID) - let steamApps = bottle.root.appendingPathComponent("drive_c/Program Files (x86)/Steam/steamapps", isDirectory: true) - let records = FileManager.default.fileExists(atPath: steamApps.path) - ? try SteamScanner.scan(steamApps: steamApps) : [] - steamGames = records.filter { - SteamDownloadBridge.permitsPlay(manifestReady: $0.isReadyToPlay, download: steamBridgeDownloads[$0.appID]) + let snapshot = try await steamLibraryReader.read( + steamRoot: SteamCompatibilityManager.steamRoot(in: bottle), bottleRoot: bottle.root, force: force) + guard steamBottle?.id == bottle.id, !Task.isCancelled else { return } + if !steamMetadataCacheLoaded { + let cacheURL = paths.steamCatalogCache + if steamMetadataCacheLoadTask == nil { + steamMetadataCacheLoadTask = Task.detached(priority: .utility) { + SteamStoreMetadataCache.load(from: cacheURL) + } + } + let cached = await steamMetadataCacheLoadTask?.value ?? [:] + if !steamMetadataCacheLoaded { + steamMetadataCache = cached + steamMetadataCacheLoaded = true + steamMetadataCacheLoadTask = nil + } } - steamDownloads = records.filter { - !SteamDownloadBridge.permitsPlay(manifestReady: $0.isReadyToPlay, download: steamBridgeDownloads[$0.appID]) && $0.appID != 228980 + let records = snapshot.records + let playable = records.filter { + SteamDownloadBridge.permitsPlay(manifestReady: snapshot.readyAppIDs.contains($0.appID), download: steamBridgeDownloads[$0.appID]) } - steamAccountGames = try SteamAccountLibraryScanner.scan( - steamRoot: SteamCompatibilityManager.steamRoot(in: bottle), - installed: records - ) - steamActivities = SteamActivityScanner.scan( - steamRoot: SteamCompatibilityManager.steamRoot(in: bottle) - ) - steamMetadataCache = SteamStoreMetadataCache.load(from: paths.steamCatalogCache) - for index in steamAccountGames.indices { - guard let metadata = steamMetadataCache[steamAccountGames[index].appID] else { continue } - steamAccountGames[index].name = metadata.name - steamAccountGames[index].headerImageURL = metadata.headerImageURL - steamAccountGames[index].description = metadata.description + let downloading = records.filter { + !SteamDownloadBridge.permitsPlay(manifestReady: snapshot.readyAppIDs.contains($0.appID), download: steamBridgeDownloads[$0.appID]) && $0.appID != 228980 } - if previousIDs != steamAccountGames.map(\.appID) || steamMetadataTask == nil { - scheduleSteamMetadataHydration() + if steamGames != playable { steamGames = playable } + if steamDownloads != downloading { steamDownloads = downloading } + var accountGames = snapshot.accountGames + for index in accountGames.indices { + guard let metadata = steamMetadataCache[accountGames[index].appID] else { continue } + accountGames[index].name = metadata.name + accountGames[index].headerImageURL = metadata.headerImageURL + accountGames[index].description = metadata.description } + if steamAccountGames != accountGames { steamAccountGames = accountGames } + if steamActivities != snapshot.activities { steamActivities = snapshot.activities } + if steamLibraries != snapshot.libraries { steamLibraries = snapshot.libraries } + scheduleSteamMetadataHydration() } - func syncSteamLibrary() { + func syncSteamLibrary() async { guard !onboardingBusy, !isWorking else { return } pollSteamDownloads() do { - try scanDefaultSteamLibrary() + try await scanDefaultSteamLibrary(force: false) if !steamAccountGames.isEmpty { status = L("已同步 \(steamAccountGames.count) 款账户游戏") } else { @@ -1336,13 +1414,18 @@ final class MacGamingUncleAppModel: ObservableObject { } private func scheduleSteamMetadataHydration() { - steamMetadataTask?.cancel() + guard steamMetadataTask == nil else { return } let appIDs = steamAccountGames - .filter { steamMetadataCache[$0.appID] == nil } + .filter { steamMetadataCache[$0.appID] == nil && steamMetadataRetry.canAttempt($0.appID) } .map(\.appID) guard !appIDs.isEmpty else { return } + isSteamMetadataLoading = true steamMetadataTask = Task { [weak self] in guard let self else { return } + defer { + self.steamMetadataTask = nil + self.isSteamMetadataLoading = false + } for offset in stride(from: 0, to: appIDs.count, by: 8) { if Task.isCancelled { return } let chunk = Array(appIDs[offset..= 2 else { return } + do { try await Task.sleep(for: .milliseconds(350)) } + catch { return } + await model.searchNativeSteamStore(searchTerm) + } + .onChange(of: search) { _, value in + model.resetSteamSearch(value) + selectedItem = nil + } + .onDisappear { model.resetSteamSearch("") } .onAppear { selectRequestedItem() } .onChange(of: model.steamStoreSelectedAppID) { _, _ in selectRequestedItem() } .onChange(of: displayItems.map(\.id)) { _, ids in @@ -72,39 +88,80 @@ struct NativeSteamStoreView: View { } } + @ViewBuilder + private var searchStatus: some View { + if model.isSteamSearchLoading { + VStack(spacing: 14) { ProgressView(); Text(L("正在搜索 Steam 商店…")) } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + ContentUnavailableView { + Label(model.steamSearchError != nil ? L("搜索失败") : + (model.steamSearchCompleted ? L("没有找到匹配的游戏") : L("搜索 Steam 商店")), + systemImage: model.steamSearchError != nil ? "wifi.exclamationmark" : "magnifyingglass") + } description: { + Text(model.steamSearchError ?? (searchTerm.count < 2 ? L("请输入至少两个字符") : + (model.steamSearchCompleted ? L("试试游戏的英文名或更短的关键词") : L("即将搜索…")))) + } actions: { + if model.steamSearchError != nil { + Button(L("重试")) { Task { await model.searchNativeSteamStore(searchTerm) } } + } + Button(L("返回精选")) { search = ""; model.resetSteamSearch("") } + } + } + } + private var storeToolbar: some View { - HStack(spacing: 18) { - VStack(alignment: .leading, spacing: 3) { - Text(L("商店")).font(.system(size: 26, weight: .bold, design: .rounded)) - Text(L("由 Steam 官方商店数据提供")).font(.caption).foregroundStyle(IndiePalette.secondaryText) + ViewThatFits(in: .horizontal) { + HStack(spacing: 18) { + storeTitle + storeCategories + Spacer(minLength: 18) + storeSearchControls } - Picker("", selection: $selection) { - Text(L("精选")).tag(NativeStoreSection.featured) - Text(L("畅销")).tag(NativeStoreSection.topSellers) - Text(L("优惠")).tag(NativeStoreSection.specials) - Text(L("新品")).tag(NativeStoreSection.newReleases) + VStack(alignment: .leading, spacing: 14) { + HStack { storeTitle; Spacer(); storeCategories } + HStack { Spacer(); storeSearchControls } } - .pickerStyle(.segmented).frame(width: 300) - Spacer() + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 28).padding(.vertical, 16) + .background(IndiePalette.topBar.opacity(0.86)) + } + + private var storeTitle: some View { + VStack(alignment: .leading, spacing: 3) { + Text(L("商店")).font(.system(size: 26, weight: .bold, design: .rounded)) + Text(L("由 Steam 官方商店数据提供")).font(.caption).foregroundStyle(IndiePalette.secondaryText) + }.fixedSize(horizontal: true, vertical: false) + } + + private var storeCategories: some View { + Picker(L("商店分类"), selection: $selection) { + Text(L("精选")).tag(NativeStoreSection.featured) + Text(L("畅销")).tag(NativeStoreSection.topSellers) + Text(L("优惠")).tag(NativeStoreSection.specials) + Text(L("新品")).tag(NativeStoreSection.newReleases) + }.pickerStyle(.segmented).labelsHidden().frame(width: 300) + } + + private var storeSearchControls: some View { + HStack(spacing: 12) { HStack(spacing: 8) { Image(systemName: "magnifyingglass").foregroundStyle(IndiePalette.secondaryText) TextField(L("搜索 Steam 商店"), text: $search) .textFieldStyle(.plain).onSubmit { Task { await model.searchNativeSteamStore(search) } } if !search.isEmpty { - Button { search = ""; model.steamStoreSearchResults = [] } label: { - Image(systemName: "xmark.circle.fill") - }.buttonStyle(.plain).foregroundStyle(IndiePalette.secondaryText) + Button { search = ""; model.resetSteamSearch("") } label: { Image(systemName: "xmark.circle.fill") } + .buttonStyle(.plain).foregroundStyle(IndiePalette.secondaryText).help(L("清除搜索")) } } .padding(.horizontal, 12).frame(width: 280, height: 36) .background(IndiePalette.surface, in: RoundedRectangle(cornerRadius: 9)) Button(L("搜索")) { Task { await model.searchNativeSteamStore(search) } } - .buttonStyle(.borderedProminent).disabled(search.count < 2) - Button { Task { await model.loadNativeSteamStore(force: true) } } label: { - Image(systemName: "arrow.clockwise") - }.buttonStyle(.plain).help(L("刷新商店")) - } - .padding(.horizontal, 28).frame(height: 76).background(IndiePalette.topBar.opacity(0.86)) + .buttonStyle(.borderedProminent).disabled(searchTerm.count < 2 || model.isSteamSearchLoading) + Button { Task { await model.loadNativeSteamStore(force: true) } } label: { Image(systemName: "arrow.clockwise") } + .buttonStyle(.plain).help(L("刷新商店")).disabled(model.isSteamStoreLoading) + }.fixedSize(horizontal: true, vertical: false) } private func storeHero(_ item: SteamStoreItem) -> some View { @@ -112,9 +169,11 @@ struct NativeSteamStoreView: View { AsyncImage(url: URL(string: "https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/\(item.id)/page_bg_raw.jpg")) { phase in if case .success(let image) = phase { image.resizable().scaledToFill() - } else { + } else if case .failure = phase { AsyncImage(url: item.imageURL) { image in image.resizable().scaledToFill() } placeholder: { IndiePalette.surfaceStrong } + } else { + IndiePalette.surfaceStrong } } .frame(maxWidth: .infinity, minHeight: 350, maxHeight: 350).clipped() @@ -128,8 +187,9 @@ struct NativeSteamStoreView: View { ) LinearGradient(colors: [.clear, IndiePalette.canvas.opacity(0.92)], startPoint: .center, endPoint: .bottom) VStack(alignment: .leading, spacing: 12) { - Text(L("STEAM 精选")).font(.system(size: 12, weight: .bold)).foregroundStyle(IndiePalette.blue) + Text(sectionTitle).font(.system(size: 12, weight: .bold)).foregroundStyle(IndiePalette.blue) Text(item.name).font(.system(size: 36, weight: .bold, design: .rounded)).lineLimit(2) + .minimumScaleFactor(0.8).help(item.name) priceView(item) HStack(spacing: 11) { if let offline = model.offlineLibrary(for:item.id) { @@ -145,7 +205,8 @@ struct NativeSteamStoreView: View { .buttonStyle(.borderedProminent).controlSize(.large) .disabled(model.isWorking || model.gameLaunchStates[item.id]?.blocksLaunch == true) } else { - Button(L("安装游戏"), systemImage: "arrow.down.circle") { + Button(model.steamAccountGames.contains(where: { $0.appID == item.id }) ? L("安装游戏") : L("在 Steam 中获取"), + systemImage: model.steamAccountGames.contains(where: { $0.appID == item.id }) ? "arrow.down.circle" : "cart") { Task { await model.installSteamGame(appID: item.id) } } .buttonStyle(.borderedProminent).controlSize(.large) @@ -163,14 +224,8 @@ struct NativeSteamStoreView: View { } private func storeSection(title: String, items: [SteamStoreItem]) -> some View { - VStack(alignment: .leading, spacing: 13) { - HStack { Text(title).font(.system(size: 19, weight: .semibold)); Spacer(); Text(L("\(items.count) 款")).font(.caption).foregroundStyle(IndiePalette.secondaryText) } - ScrollView(.horizontal) { - HStack(spacing: 14) { - ForEach(items.prefix(20)) { item in storeCard(item) } - }.padding(.vertical, 3) - }.scrollIndicators(.hidden) - }.padding(.horizontal, 28) + GameCarouselView(title: title, items: items, cardWidth: 258) { storeCard($0) } + .padding(.horizontal, 28) } private func storeCard(_ item: SteamStoreItem) -> some View { @@ -179,7 +234,8 @@ struct NativeSteamStoreView: View { AsyncImage(url: item.imageURL) { image in image.resizable().scaledToFill() } placeholder: { IndiePalette.surfaceStrong } .frame(width: 238, height: 112).clipped() - Text(item.name).font(.system(size: 13.5, weight: .semibold)).lineLimit(1) + Text(item.name).font(.system(size: 13.5, weight: .semibold)).lineLimit(2) + .frame(height: 36, alignment: .topLeading).help(item.name) HStack { priceView(item); Spacer(); if item.discountPercent > 0 { Text("-\(item.discountPercent)%").foregroundStyle(IndiePalette.green) } } .font(.caption) } @@ -204,7 +260,7 @@ struct NativeSteamStoreView: View { private var sectionTitle: String { if !search.isEmpty { return L("搜索结果") } return switch selection { - case .featured: L("为你推荐") + case .featured: L("精选游戏") case .topSellers: L("热销商品") case .specials: L("特别优惠") case .newReleases: L("新品推荐") diff --git a/Sources/MacGamingUncleApp/Resources/en.lproj/Localizable.strings b/Sources/MacGamingUncleApp/Resources/en.lproj/Localizable.strings index 2ad57fa..095ccde 100644 --- a/Sources/MacGamingUncleApp/Resources/en.lproj/Localizable.strings +++ b/Sources/MacGamingUncleApp/Resources/en.lproj/Localizable.strings @@ -36,3 +36,6 @@ "settings.channel" = "Update channel"; "settings.metalHUD" = "Enable Metal HUD by default"; "settings.privacy" = "Mac Gaming Uncle collects no telemetry. Compatibility recipes update from an auditable Git repository."; +"音频诊断" = "Audio diagnostics"; +"记录空间音频诊断日志" = "Record spatial audio diagnostic logs"; +"用于确认游戏是否提交空间音频对象。日志会增加运行开销;短时测试结束后关闭,并重新启动游戏。" = "Confirm whether the game submits spatial audio objects. Logging adds overhead; turn it off after a short test and restart the game."; diff --git a/Sources/MacGamingUncleApp/Resources/zh-Hans.lproj/Localizable.strings b/Sources/MacGamingUncleApp/Resources/zh-Hans.lproj/Localizable.strings index d45bf16..74a9649 100644 --- a/Sources/MacGamingUncleApp/Resources/zh-Hans.lproj/Localizable.strings +++ b/Sources/MacGamingUncleApp/Resources/zh-Hans.lproj/Localizable.strings @@ -36,3 +36,6 @@ "settings.channel" = "更新通道"; "settings.metalHUD" = "默认启用 Metal HUD"; "settings.privacy" = "Mac Gaming Uncle 不收集遥测数据。兼容配方通过可审计的 Git 仓库更新。"; +"音频诊断" = "音频诊断"; +"记录空间音频诊断日志" = "记录空间音频诊断日志"; +"用于确认游戏是否提交空间音频对象。日志会增加运行开销;短时测试结束后关闭,并重新启动游戏。" = "用于确认游戏是否提交空间音频对象。日志会增加运行开销;短时测试结束后关闭,并重新启动游戏。"; diff --git a/Sources/MacGamingUncleApp/SteamShellLibraryView.swift b/Sources/MacGamingUncleApp/SteamShellLibraryView.swift index 6990f52..b142828 100644 --- a/Sources/MacGamingUncleApp/SteamShellLibraryView.swift +++ b/Sources/MacGamingUncleApp/SteamShellLibraryView.swift @@ -32,6 +32,14 @@ struct SteamShellLibraryView: View { Divider().overlay(IndiePalette.border) if model.steamAccountGames.isEmpty { emptyState + } else if games.isEmpty { + ContentUnavailableView { + Label(L("没有匹配的游戏"), systemImage: "magnifyingglass") + } description: { + Text(L("调整搜索关键词或筛选条件")) + } actions: { + Button(L("显示全部游戏")) { search = ""; filter = .all } + } } else { HStack(spacing: 0) { gameList.frame(width: 285) @@ -56,26 +64,51 @@ struct SteamShellLibraryView: View { } private var libraryHeader: some View { - HStack(spacing: 16) { - VStack(alignment: .leading, spacing: 3) { - Text(L("游戏库")).font(.system(size: 26, weight: .bold, design: .rounded)) - Text(L("\(model.steamAccountGames.count) 款账户游戏 · \(model.steamGames.filter { $0.appID != 228980 }.count) 款已安装")) - .font(.caption).foregroundStyle(IndiePalette.secondaryText) + ViewThatFits(in: .horizontal) { + HStack(spacing: 16) { + libraryTitle + librarySession + Spacer(minLength: 16) + libraryControls + } + VStack(alignment: .leading, spacing: 14) { + HStack { libraryTitle; Spacer(); librarySession } + HStack { Spacer(); libraryControls } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 24).padding(.vertical, 16) + .background(IndiePalette.sidebar.opacity(0.82)) + } + + private var libraryTitle: some View { + VStack(alignment: .leading, spacing: 3) { + Text(L("游戏库")).font(.system(size: 26, weight: .bold, design: .rounded)) + Text(L("\(model.steamAccountGames.count) 款账户游戏 · \(model.steamGames.filter { $0.appID != 228980 }.count) 款已安装")) + .font(.caption).foregroundStyle(IndiePalette.secondaryText) + }.fixedSize(horizontal: true, vertical: false) + } + + private var librarySession: some View { + HStack { + if model.isSteamMetadataLoading { + ProgressView().controlSize(.small).help(L("正在补全游戏名称与封面…")) } SteamSessionIndicator(manager: model.steamSessionManager) - Spacer() + }.fixedSize(horizontal: true, vertical: false) + } + + private var libraryControls: some View { + HStack(spacing: 16) { Button(L("存储与游戏库"),systemImage:"externaldrive") { model.showSteamStorage = true } - Picker("", selection: $filter) { + Picker(L("游戏库筛选"), selection: $filter) { Text(L("全部")).tag(SteamLibraryFilter.all) Text(L("已安装")).tag(SteamLibraryFilter.installed) Text(L("最近玩过")).tag(SteamLibraryFilter.recent) - } - .pickerStyle(.segmented).frame(width: 250) + }.pickerStyle(.segmented).labelsHidden().frame(width: 250) TextField(L("搜索游戏库"), text: $search).textFieldStyle(.roundedBorder).frame(width: 210) Button(L("刷新"), systemImage: "arrow.clockwise") { model.rescanSteam() } - } - .padding(.horizontal, 24).frame(height: 78) - .background(IndiePalette.sidebar.opacity(0.82)) + }.fixedSize(horizontal: true, vertical: false) } private var gameList: some View { @@ -87,7 +120,7 @@ struct SteamShellLibraryView: View { } .frame(width: 54, height: 31).clipShape(RoundedRectangle(cornerRadius: 4)) VStack(alignment: .leading, spacing: 3) { - Text(game.name).lineLimit(1).font(.system(size: 13.5, weight: .medium)) + Text(game.name).lineLimit(2).font(.system(size: 13.5, weight: .medium)).help(game.name) Text(model.offlineLibrary(for:game.appID) != nil ? L("磁盘未连接") : model.steamDownloads.first(where: { $0.appID == game.appID })?.installationLabel ?? (game.isInstalled ? L("已安装") : playtime(game.playtimeMinutes))) .font(.caption2).foregroundStyle(game.isInstalled ? IndiePalette.green : IndiePalette.secondaryText) @@ -113,7 +146,8 @@ struct SteamShellLibraryView: View { .frame(maxWidth: .infinity, minHeight: 300, maxHeight: 360).clipped() LinearGradient(colors: [.clear, IndiePalette.canvas.opacity(0.98)], startPoint: .center, endPoint: .bottom) VStack(alignment: .leading, spacing: 9) { - Text(game.name).font(.system(size: 34, weight: .bold, design: .rounded)).shadow(radius: 8) + Text(game.name).font(.system(size: 34, weight: .bold, design: .rounded)) + .lineLimit(2).minimumScaleFactor(0.8).help(game.name).shadow(radius: 8) HStack(spacing: 15) { Label(playtime(game.playtimeMinutes), systemImage: "clock") if let date = game.lastPlayed { Label(L("上次游玩 \(AppLanguage.date(date))"), systemImage: "calendar") } diff --git a/Sources/MacGamingUncleApp/WindowOperationCommands.swift b/Sources/MacGamingUncleApp/WindowOperationCommands.swift new file mode 100644 index 0000000..4b8c546 --- /dev/null +++ b/Sources/MacGamingUncleApp/WindowOperationCommands.swift @@ -0,0 +1,26 @@ +import AppKit +import IndieCore +import SwiftUI + +/// Use the responder chain so commands operate on the active native window. +/// Close (Command-W) remains the standard File menu command. +struct WindowOperationCommands: Commands { + var body: some Commands { + CommandGroup(replacing: .windowSize) { + Button(L("最小化窗口")) { + NSApp.sendAction(#selector(NSWindow.performMiniaturize(_:)), to: nil, from: nil) + } + .keyboardShortcut("m", modifiers: .command) + + Button(L("最大化或恢复窗口")) { + NSApp.sendAction(#selector(NSWindow.performZoom(_:)), to: nil, from: nil) + } + .keyboardShortcut("m", modifiers: [.control, .command]) + + Button(L("进入或退出全屏")) { + NSApp.sendAction(#selector(NSWindow.toggleFullScreen(_:)), to: nil, from: nil) + } + .keyboardShortcut("f", modifiers: [.control, .command]) + } + } +} diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index a1df0da..bb5f9ec 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -13,6 +13,7 @@ Indie does not redistribute these components in this repository. When users or r | Steam | Store client and game delivery | Valve/Steam terms; user-installed only | | Steam WebHelper wrapper | Forces Wine-compatible CEF process mode | MIT, copyright 2026 notpop | | Indie Wine 11 runtime | Wine 11 macOS host, new WoW64, MSync and Indie patches | Wine LGPL-2.1-or-later; corresponding CodeWeavers FOSS source and patch set are published with the runtime | +| Switchyard Wine spatial audio patches | Windows object audio to CoreAudio Spatial Mixer; author jungwuk-ryu, exact source commits in docs/SPATIAL_AUDIO.md | LGPL-2.1-or-later | | FreeType | Wine font rendering | FreeType License or GPL-2.0-only | | GnuTLS, GMP, Nettle | Wine TLS and cryptography support | LGPL-2.1-or-later / LGPL-3.0-or-later and component-specific notices | | libinotify-kqueue | kqueue-backed filesystem notifications for wineserver | MIT | diff --git a/Tests/IndieCatalogTests/SteamLibraryRefreshTests.swift b/Tests/IndieCatalogTests/SteamLibraryRefreshTests.swift index a598fd9..5cbac64 100644 --- a/Tests/IndieCatalogTests/SteamLibraryRefreshTests.swift +++ b/Tests/IndieCatalogTests/SteamLibraryRefreshTests.swift @@ -21,12 +21,15 @@ final class SteamLibraryRefreshTests: XCTestCase { XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("steamapps").path)) } - func testLocalAccountCacheReadOnly() throws { + func testLocalAccountCacheReadOnly() async throws { guard let path = ProcessInfo.processInfo.environment["INDIE_TEST_STEAM_ROOT"] else { throw XCTSkip("Opt-in read-only check of a local Steam cache") } let games = try SteamAccountLibraryScanner.scan(steamRoot: URL(fileURLWithPath: path), installed: []) XCTAssertFalse(games.isEmpty) - print("Local Steam cache: \(games.count) games") + let snapshot = try await SteamLibraryReader().read( + steamRoot: URL(fileURLWithPath: path), bottleRoot: URL(fileURLWithPath: path), force: true) + XCTAssertTrue(Set(games.map(\.appID)).isSubset(of: Set(snapshot.accountGames.map(\.appID)))) + print("Local Steam cache: \(snapshot.accountGames.count) games") } } diff --git a/Tests/IndieCatalogTests/SteamRefreshPolicyTests.swift b/Tests/IndieCatalogTests/SteamRefreshPolicyTests.swift new file mode 100644 index 0000000..5de5c55 --- /dev/null +++ b/Tests/IndieCatalogTests/SteamRefreshPolicyTests.swift @@ -0,0 +1,106 @@ +import Foundation +import XCTest +@testable import IndieCatalog + +final class SteamRefreshPolicyTests: XCTestCase { + func testSearchIgnoresOlderResponseAndResponseAfterClear() { + var state = SteamStoreSearchState() + let older = state.begin("first") + let newer = state.begin("second") + state.complete([], requestID: older) + XCTAssertEqual(state.phase, .loading) + state.fail("old failure", requestID: older) + XCTAssertNil(state.error) + state.complete([], requestID: newer) + XCTAssertEqual(state.phase, .empty) + XCTAssertTrue(state.completed) + XCTAssertNil(state.error) + let pending = state.begin("third") + state.reset("") + state.fail("late failure", requestID: pending) + XCTAssertEqual(state.phase, .idle) + } + + func testSearchFailureIsDistinctFromNoResultsAndCanRetry() { + var state = SteamStoreSearchState() + state.reset(" portal ") + XCTAssertEqual(state.query, "portal") + XCTAssertEqual(state.phase, .waiting) + let request = state.begin("portal") + state.fail("offline", requestID: request) + XCTAssertFalse(state.completed) + XCTAssertFalse(state.isLoading) + XCTAssertEqual(state.error, "offline") + let retry = state.begin("portal") + state.complete([], requestID: retry) + XCTAssertEqual(state.phase, .empty) + XCTAssertNil(state.error) + } + + func testRetryBackoffIsBoundedAndSuccessClearsFailure() { + var retry = SteamMetadataRetryPolicy() + let now = Date(timeIntervalSince1970: 1000) + XCTAssertTrue(retry.canAttempt(42, now: now)) + retry.failed(42, now: now) + XCTAssertFalse(retry.canAttempt(42, now: now.addingTimeInterval(9))) + XCTAssertTrue(retry.canAttempt(42, now: now.addingTimeInterval(10))) + XCTAssertTrue(retry.canAttempt(43, now: now)) + for _ in 0..<10 { retry.failed(42, now: now) } + XCTAssertFalse(retry.canAttempt(42, now: now.addingTimeInterval(299))) + XCTAssertTrue(retry.canAttempt(42, now: now.addingTimeInterval(300))) + retry.succeeded(42) + XCTAssertTrue(retry.canAttempt(42, now: now)) + retry.failed(42, now: now) + retry.reset() + XCTAssertTrue(retry.canAttempt(42, now: now)) + } + + func testAccountScanCadenceForceRefreshAndRootChange() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let config = root.appendingPathComponent("userdata/123/config/localconfig.vdf") + try FileManager.default.createDirectory(at: config.deletingLastPathComponent(), withIntermediateDirectories: true) + func write(_ appID: Int) throws { + try "\"UserLocalConfigStore\" { \"Software\" { \"Valve\" { \"Steam\" { \"apps\" { \"\(appID)\" { \"Playtime\" \"120\" } } } } } }" + .write(to: config, atomically: true, encoding: .utf8) + } + let reader = SteamLibraryReader() + let now = Date(timeIntervalSince1970: 1000) + try write(42) + let initial = try await reader.read(steamRoot: root, bottleRoot: root, now: now) + XCTAssertEqual(initial.accountGames.map(\.appID), [42]) + try write(43) + let frequent = try await reader.read(steamRoot: root, bottleRoot: root, now: now.addingTimeInterval(1)) + XCTAssertEqual(frequent.accountGames.map(\.appID), [42]) + let full = try await reader.read(steamRoot: root, bottleRoot: root, now: now.addingTimeInterval(5)) + XCTAssertEqual(full.accountGames.map(\.appID), [43]) + try write(44) + let forced = try await reader.read(steamRoot: root, bottleRoot: root, force: true, now: now.addingTimeInterval(5.1)) + XCTAssertEqual(forced.accountGames.map(\.appID), [44]) + let other = try await reader.read(steamRoot: root.appendingPathComponent("other"), bottleRoot: root, now: now.addingTimeInterval(5.2)) + XCTAssertTrue(other.accountGames.isEmpty) + } + + func testDownloadReadinessUpdatesBeforeFullAccountScan() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let apps = root.appendingPathComponent("steamapps") + try FileManager.default.createDirectory(at: apps.appendingPathComponent("common/Test"), withIntermediateDirectories: true) + let manifest = apps.appendingPathComponent("appmanifest_42.acf") + func write(_ ready: Bool) throws { + try "\"AppState\" { \"appid\" \"42\" \"name\" \"Test\" \"installdir\" \"Test\" \"buildid\" \"123\" \"StateFlags\" \"\(ready ? 4 : 6)\" \"BytesToDownload\" \"100\" \"BytesDownloaded\" \"\(ready ? 100 : 10)\" }" + .write(to: manifest, atomically: true, encoding: .utf8) + } + let reader = SteamLibraryReader() + let now = Date(timeIntervalSince1970: 1000) + try write(false) + let first = try await reader.read(steamRoot: root, bottleRoot: root, now: now) + XCTAssertFalse(first.readyAppIDs.contains(42)) + try write(true) + let cached = try await reader.read(steamRoot: root, bottleRoot: root, now: now.addingTimeInterval(0.5)) + XCTAssertFalse(cached.readyAppIDs.contains(42)) + let ready = try await reader.read(steamRoot: root, bottleRoot: root, now: now.addingTimeInterval(1)) + XCTAssertTrue(ready.readyAppIDs.contains(42)) + XCTAssertTrue(ready.accountGames.first?.isInstalled == true) + } +} diff --git a/Tests/IndieCoreTests/FrameInterpolationTests.swift b/Tests/IndieCoreTests/FrameInterpolationTests.swift index abb6f1e..b576960 100644 --- a/Tests/IndieCoreTests/FrameInterpolationTests.swift +++ b/Tests/IndieCoreTests/FrameInterpolationTests.swift @@ -22,11 +22,16 @@ final class FrameInterpolationTests: XCTestCase { let encoded = try IndieJSON.encoder().encode(original) let decoded = try IndieJSON.decoder().decode(GameConfiguration.self, from: encoded) XCTAssertNil(decoded.frameInterpolation) + XCTAssertNil(decoded.spatialAudioDiagnostics) XCTAssertFalse(decoded.isCustomized) var enabled = original enabled.frameInterpolation = true XCTAssertTrue(enabled.isCustomized) XCTAssertEqual(try IndieJSON.decoder().decode(GameConfiguration.self, from: IndieJSON.encoder().encode(enabled)).frameInterpolation, true) XCTAssertNil(GameConfiguration.steam(appID: 219990).frameInterpolation) + var diagnostic = original + diagnostic.spatialAudioDiagnostics = true + XCTAssertTrue(diagnostic.isCustomized) + XCTAssertEqual(try IndieJSON.decoder().decode(GameConfiguration.self, from: IndieJSON.encoder().encode(diagnostic)).spatialAudioDiagnostics, true) } } diff --git a/Tests/IndieCoreTests/IndieCoreTests.swift b/Tests/IndieCoreTests/IndieCoreTests.swift index 41a0173..4d6a0a7 100644 --- a/Tests/IndieCoreTests/IndieCoreTests.swift +++ b/Tests/IndieCoreTests/IndieCoreTests.swift @@ -41,6 +41,7 @@ final class IndieCoreTests: XCTestCase { let first = GameConfiguration( id: "steam:10", virtualDesktop: .init(width: 1920, height: 1080), metalHUD: .enabled, controllerMode: .enhanced, + spatialAudioDiagnostics: true, updatedAt: Date(timeIntervalSince1970: 1_000_000) ) let second = GameConfiguration( diff --git a/Tests/IndieRuntimeTests/IndieRuntimeTests.swift b/Tests/IndieRuntimeTests/IndieRuntimeTests.swift index 0d62ce7..9dfc55f 100644 --- a/Tests/IndieRuntimeTests/IndieRuntimeTests.swift +++ b/Tests/IndieRuntimeTests/IndieRuntimeTests.swift @@ -235,14 +235,19 @@ final class IndieRuntimeTests: XCTestCase { for executable in ["bin/wine", "bin/wineserver"] { try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: payload.appendingPathComponent(executable).path) } - try Data("11.0.2\n".utf8).write(to: payload.appendingPathComponent("runtime-version.txt")) + try Data("11.0.3-spatial.2\n".utf8).write(to: payload.appendingPathComponent("runtime-version.txt")) + try Data(#"{"runtime":"Mac Gaming Uncle Wine 11"}"#.utf8).write(to: payload.appendingPathComponent("source.lock.json")) - let installed = try await CommunityIndieWineBootstrapper(paths: paths).installLocalBuild( + let installed = try await LocalWineImporter(paths: paths).importRuntime( from: payload.deletingLastPathComponent() ) - XCTAssertEqual(installed.manifest.version, SemanticVersion(major: 11, minor: 0, patch: 2)) + XCTAssertEqual(installed.manifest.id, CommunityIndieWineBootstrapper.runtimeID) + XCTAssertEqual(installed.manifest.channel, .experimental) + XCTAssertEqual(installed.manifest.version, SemanticVersion(major: 11, minor: 0, patch: 3, prerelease: "spatial.2")) XCTAssertTrue(CommunityIndieWineBootstrapper.hasControllerSupport(installed.root)) - XCTAssertEqual(installed.root.lastPathComponent, "11.0.2") + XCTAssertEqual(installed.root.lastPathComponent, "11.0.3-spatial.2") + try Data(#"{"runtime":"Other Wine"}"#.utf8).write(to: payload.appendingPathComponent("source.lock.json")) + XCTAssertNil(CommunityIndieWineBootstrapper.managedBuildRoot(in: payload.deletingLastPathComponent())) } func testControllerRuntimeRejectsSDLFreePayload() async throws { @@ -321,11 +326,13 @@ final class IndieRuntimeTests: XCTestCase { directX: .d3d12, antiCheat: .none, importedLibraries: ["d3d12.dll"] ) let fallback = "\(external.path):\(runtimeLibraries.path)" + var environment = ["WINEDLLPATH_PREPEND": bridge.path, "DYLD_FALLBACK_LIBRARY_PATH": fallback] + environment.merge(SpatialAudioDiagnostics.environment(enabled: true)) { _, diagnostic in diagnostic } let plan = try LaunchPlanBuilder.build( executable: root.appendingPathComponent("game.exe"), bottle: bottle, profile: LaunchProfile( runtimeID: "org.indie.wine11", preferredRenderer: .d3dMetal, - environment: ["WINEDLLPATH_PREPEND": bridge.path, "DYLD_FALLBACK_LIBRARY_PATH": fallback] + environment: environment ), analysis: analysis, recipe: nil, installed: InstalledRenderers(available: [.d3dMetal], overlayPaths: [.d3dMetal: bridge]) @@ -333,6 +340,12 @@ final class IndieRuntimeTests: XCTestCase { XCTAssertEqual(plan.environment["WINEDLLPATH_PREPEND"], bridge.path) XCTAssertEqual(plan.environment["WINEDLLPATH"], bridge.path) XCTAssertEqual(plan.environment["DYLD_FALLBACK_LIBRARY_PATH"], fallback) + let relayed = SteamCompatibilityManager.relayEnvironment(for: plan.environment) + XCTAssertEqual(relayed["WINEDEBUG"], "-all,+mmdevapi,+coreaudio") + XCTAssertEqual(relayed["SWITCHYARD_SPATIAL_AUDIO_PROFILE"], "1") + XCTAssertEqual(relayed["WINEDLLPATH_PREPEND"], bridge.path) + XCTAssertEqual(relayed["DYLD_FALLBACK_LIBRARY_PATH"], fallback) + XCTAssertTrue(SpatialAudioDiagnostics.environment(enabled: false).isEmpty) } func testLocalWineImporterFindsNestedBundleLayout() throws { diff --git a/Tests/IndieRuntimeTests/PackagedWineIntegrationTests.swift b/Tests/IndieRuntimeTests/PackagedWineIntegrationTests.swift new file mode 100644 index 0000000..4752699 --- /dev/null +++ b/Tests/IndieRuntimeTests/PackagedWineIntegrationTests.swift @@ -0,0 +1,105 @@ +import Foundation +import XCTest +@testable import IndieCore +@testable import IndieRuntime + +final class PackagedWineIntegrationTests: XCTestCase { + func testPackagedRuntimeWithImportedD3DMetal() async throws { + let settings = ProcessInfo.processInfo.environment + guard let source = settings["INDIE_TEST_WINE_RUNTIME"], + let renderer = settings["INDIE_TEST_D3DMETAL_ROOT"] else { + throw XCTSkip("Set INDIE_TEST_WINE_RUNTIME and INDIE_TEST_D3DMETAL_ROOT for real GPU fixtures") + } + let root = FileManager.default.temporaryDirectory.appendingPathComponent("indie-d3dmetal-integration-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: root) } + let installed = try await LocalWineImporter(paths: IndiePaths(root: root.appendingPathComponent("data"))) + .importRuntime(from: URL(fileURLWithPath: source, isDirectory: true)) + let provider = WineRuntimeProvider(manifest: installed.manifest, root: installed.root) + let bottle = BottleRecord(name: "D3DMetal smoke", root: root.appendingPathComponent("bottle"), runtimeID: installed.manifest.id) + let rendererRoot = URL(fileURLWithPath: renderer, isDirectory: true) + let subprocess = Subprocess() + do { + try await provider.initializeBottle(bottle) + try D3DMetalRendererPreparer.installBridge(rendererRoot: rendererRoot, version: "integration", bottle: bottle) + var environment = try D3DMetalLaunchEnvironment.make(rendererRoot: rendererRoot, runtimeRoot: installed.root, + metalHUD: false, metalFX: false, metal4: false) + environment["WINEDEBUG"] = "-all,err+all,+loaddll,+winemac" + environment["DYLD_PRINT_LIBRARIES"] = "1" + let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + let fixtureDirectory = bottle.root.appendingPathComponent("drive_c/mgu-fixtures", isDirectory: true) + try FileManager.default.createDirectory(at: fixtureDirectory, withIntermediateDirectories: true) + for (name, directX) in [("indie-d3d11-fixture", DirectXVersion.d3d11), ("indie-d3d12-fixture", DirectXVersion.d3d12)] { + let sourceFixture = repo.appendingPathComponent(".build/windows-fixtures/\(name).exe") + let executable = fixtureDirectory.appendingPathComponent("\(name).exe") + try FileManager.default.copyItem(at: sourceFixture, to: executable) + XCTAssertTrue(FileManager.default.isExecutableFile(atPath: executable.path), executable.path) + let analysis = GameAnalysis(identity: GameIdentity(executableName: executable.lastPathComponent), + architecture: .x86_64, directX: directX, antiCheat: .none, importedLibraries: []) + let plan = try LaunchPlanBuilder.build(executable: executable, + windowsExecutablePath: try WinePath.windowsPath(for: executable, in: bottle), bottle: bottle, + profile: LaunchProfile(runtimeID: installed.manifest.id, preferredRenderer: .d3dMetal, + arguments: ["--smoke"], environment: environment), + analysis: analysis, recipe: nil, + installed: InstalledRenderers(available: [.d3dMetal], overlayPaths: [.d3dMetal: rendererRoot.appendingPathComponent("wine")])) + let result = try await subprocess.run(provider.wineBinary, arguments: provider.launchArguments(for: plan), + environment: plan.environment.merging(["DYLD_LIBRARY_PATH": installed.root.appendingPathComponent("lib").path]) { _, host in host }, + timeout: .seconds(60), requireSuccess: false) + if let destination = settings["INDIE_TEST_D3DMETAL_LOGS"] { + let directory = URL(fileURLWithPath: destination, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try (result.stdout + result.stderr).write(to: directory.appendingPathComponent("\(name).log"), atomically: true, encoding: .utf8) + } + XCTAssertEqual(result.status, 0, "\(name): \(result.stderr.suffix(3000))") + XCTAssertTrue(result.stderr.contains("libd3dshared.dylib"), "\(name) must load the imported D3DMetal library") + } + } catch { + await provider.stopBottle(bottle) + throw error + } + await provider.stopBottle(bottle) + } + + /// Opt-in: installs a real extracted runtime through the product importer, + /// then initializes a disposable bottle through the product provider. + func testPackagedRuntimeImportAndBottleInitialization() async throws { + guard let source = ProcessInfo.processInfo.environment["INDIE_TEST_WINE_RUNTIME"] else { + throw XCTSkip("Set INDIE_TEST_WINE_RUNTIME to an extracted complete runtime") + } + let root = FileManager.default.temporaryDirectory.appendingPathComponent("indie-runtime-integration-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: root) } + let paths = IndiePaths(root: root.appendingPathComponent("应用 数据")) + let installed = try await LocalWineImporter(paths: paths).importRuntime( + from: URL(fileURLWithPath: source, isDirectory: true) + ) + let provider = WineRuntimeProvider(manifest: installed.manifest, root: installed.root) + let bottle = BottleRecord(name: "Packaged smoke", root: root.appendingPathComponent("测试 容器"), runtimeID: installed.manifest.id) + let subprocess = Subprocess() + let environment = ["WINEPREFIX": bottle.root.path, + "DYLD_LIBRARY_PATH": installed.root.appendingPathComponent("lib").path, + "WINEDEBUG": "-all"] + let items = await provider.probeInstallation(at: installed.root) + XCTAssertEqual(items.first?.severity, .pass) + XCTAssertTrue(CommunityIndieWineBootstrapper.hasControllerSupport(installed.root)) + XCTAssertEqual(installed.manifest.id, CommunityIndieWineBootstrapper.runtimeID) + XCTAssertEqual(installed.manifest.channel, .experimental) + let version = try String(contentsOf: installed.root.appendingPathComponent("runtime-version.txt"), encoding: .utf8) + XCTAssertEqual(installed.manifest.version.description, version.trimmingCharacters(in: .whitespacesAndNewlines)) + do { + try await provider.initializeBottle(bottle) + let result = try await subprocess.run(provider.wineBinary, + arguments: ["cmd", "/c", "echo MGU_PACKAGED_RUNTIME_OK"], + environment: environment, timeout: .seconds(30)) + XCTAssertTrue(result.stdout.contains("MGU_PACKAGED_RUNTIME_OK")) + } catch { + _ = try? await subprocess.run(provider.wineserverBinary, arguments: ["-k"], + environment: environment, timeout: .seconds(10)) + _ = try? await subprocess.run(provider.wineserverBinary, arguments: ["-w"], + environment: environment, timeout: .seconds(10)) + throw error + } + _ = try await subprocess.run(provider.wineserverBinary, arguments: ["-k"], + environment: environment, timeout: .seconds(10)) + _ = try await subprocess.run(provider.wineserverBinary, arguments: ["-w"], + environment: environment, timeout: .seconds(10)) + } +} diff --git a/Tests/IndieRuntimeTests/WineRuntimeManagementTests.swift b/Tests/IndieRuntimeTests/WineRuntimeManagementTests.swift new file mode 100644 index 0000000..6368310 --- /dev/null +++ b/Tests/IndieRuntimeTests/WineRuntimeManagementTests.swift @@ -0,0 +1,80 @@ +import Foundation +import XCTest +@testable import IndieCore +@testable import IndieRuntime + +final class WineRuntimeManagementTests: XCTestCase { + private func runtime(_ root: URL, version: Int = 9, managed: Bool = true) -> LocalWineRuntime { + let manifest = RuntimeManifest( + id: managed ? CommunityIndieWineBootstrapper.runtimeID : "org.indie.wine.local", + displayName: "Wine", version: SemanticVersion(major: 11, minor: 0, patch: version), + channel: .experimental, hostArchitecture: .x86_64, + minimumMacOS: SemanticVersion(major: 15, minor: 0), + capabilities: RuntimeCapabilities(architectures: [.x86_64], renderers: [.wineD3D], + supportsWoW64: true, supportsMSync: true), artifacts: [], licenses: [], + publishedAt: Date(), signature: nil) + return LocalWineRuntime(manifest: manifest, root: root, importedAt: Date()) + } + + func testExplicitSelectionAndMissingSelectionFallback() { + let older = runtime(URL(fileURLWithPath: "/older"), version: 2) + let newer = runtime(URL(fileURLWithPath: "/newer")) + let generic = runtime(URL(fileURLWithPath: "/generic"), version: 99, managed: false) + let installed = [generic, older, newer] + XCTAssertEqual(LocalWineImporter.selectedGamingRuntime(in: installed, preferredID: older.id), older) + XCTAssertEqual(LocalWineImporter.selectedGamingRuntime(in: installed, preferredID: "deleted"), newer) + XCTAssertEqual(LocalWineImporter.selectedGamingRuntime(in: installed, preferredID: generic.id), newer) + XCTAssertNil(LocalWineImporter.selectedGamingRuntime(in: [generic], preferredID: nil)) + } + + func testDeletionRejectsExternalDirectory() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let external = root.appendingPathComponent("external") + try FileManager.default.createDirectory(at: external, withIntermediateDirectories: true) + let importer = LocalWineImporter(paths: IndiePaths(root: root.appendingPathComponent("data"))) + do { + try await importer.removeRuntime(runtime(external)) + XCTFail("Must reject unmanaged directories") + } catch { XCTAssertTrue(FileManager.default.fileExists(atPath: external.path)) } + } + + func testDeletionRejectsSymlinkOutsideRuntimeDirectory() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let paths = IndiePaths(root: root.appendingPathComponent("data")) + let external = root.appendingPathComponent("external") + let expected = paths.runtimes.appendingPathComponent(CommunityIndieWineBootstrapper.runtimeID).appendingPathComponent("11.0.9") + try FileManager.default.createDirectory(at: external, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: expected.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: expected, withDestinationURL: external) + let value = runtime(expected) + try IndieJSON.encoder().encode(value).write(to: external.appendingPathComponent("local-runtime.json")) + do { + try await LocalWineImporter(paths: paths).removeRuntime(value) + XCTFail("Must reject an escaping symlink") + } catch { XCTAssertTrue(FileManager.default.fileExists(atPath: external.path)) } + } + + func testDeletionRejectsRunningRuntime() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let paths = IndiePaths(root: root) + let directory = paths.runtimes.appendingPathComponent(CommunityIndieWineBootstrapper.runtimeID).appendingPathComponent("11.0.9") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let executable = directory.appendingPathComponent("sleep") + try FileManager.default.copyItem(at: URL(fileURLWithPath: "/bin/sleep"), to: executable) + let value = runtime(directory) + try IndieJSON.encoder().encode(value).write(to: directory.appendingPathComponent("local-runtime.json")) + let process = Process() + process.executableURL = executable + process.arguments = ["30"] + try process.run() + defer { if process.isRunning { process.terminate() }; process.waitUntilExit() } + XCTAssertTrue(WineProcessReaper.hasRunningProcesses(runtimeRoot: directory)) + do { + try await LocalWineImporter(paths: paths).removeRuntime(value) + XCTFail("Must reject a running version") + } catch { XCTAssertTrue(FileManager.default.fileExists(atPath: directory.path)) } + } +} diff --git a/docs/RUNTIME_SUPPLY_CHAIN.md b/docs/RUNTIME_SUPPLY_CHAIN.md index a8993d8..830c400 100644 --- a/docs/RUNTIME_SUPPLY_CHAIN.md +++ b/docs/RUNTIME_SUPPLY_CHAIN.md @@ -12,7 +12,7 @@ Manifest Schema 位于 `Schemas/runtime-manifest.schema.json`。签名内容是移除 `signature` 字段后,通过 `IndieJSON` sorted-keys 编码得到的字节。Release 私钥不得进入仓库或 CI 日志;客户端只内置公钥。 -当前研究预览默认使用 `scripts/build-indie-wine11.sh` 生成的 Mac Gaming Uncle Wine 11 运行时。输入锁定为 CodeWeavers CrossOver 26.3.0 对应 FOSS 源码包(其中 Wine 为 11.0)、Nettle 3.10、SDL2 2.32.10 官方源码和仓库内的三项可审计补丁;不从 CrossOver 应用程序中提取或分发任何二进制。运行时包含新 WoW64、MSync、FreeType、GnuTLS、GMP、Nettle 与 SDL2 winebus 手柄桥接,不包含 D3DMetal。Release URL、体积和 SHA-256 固定在 `CommunityIndieWineBootstrapper` 中,安装前逐项验证。 +当前研究预览默认使用 `scripts/build-indie-wine11.sh` 生成的 Mac Gaming Uncle Wine 11 运行时。输入锁定为 CodeWeavers CrossOver 26.3.0 对应 FOSS 源码包(其中 Wine 为 11.0)、Nettle 3.10、SDL2 2.32.10 官方源码和仓库内的六项可审计补丁(含实验空间音频移植);不从 CrossOver 应用程序中提取或分发任何二进制。运行时包含新 WoW64、MSync、FreeType、GnuTLS、GMP、Nettle 与 SDL2 winebus 手柄桥接,不包含 D3DMetal。Release URL、体积和 SHA-256 固定在 `CommunityIndieWineBootstrapper` 中,安装前逐项验证。 仓库补丁实现两项原本由产品集成层完成的功能:移除专有 `cxcompatdb.so` 加载入口;让开源 Wine 的加载器原生读取 `WINEDLLPATH_PREPEND`,从而在内置 Wine DLL 之前选择用户本机导入的 D3DMetal Wine Bridge。Steam WebHelper 的 CEF 参数兼容由仓库内可重编译的小型 wrapper 完成。上述实现不复制 CodeWeavers 专有模块。 @@ -36,3 +36,7 @@ DXMT、DXVK 和 VKD3D 以独立 Overlay 存放,不能修改已安装 Runtime ## 签名与公证 取得 Developer ID 后,`scripts/build-app.sh` 使用 `INDIE_CODESIGN_IDENTITY` 签名。正式流水线必须启用 Hardened Runtime、执行 `notarytool submit --wait`、`stapler staple`、`spctl --assess`,再生成 DMG。主应用不申请 JIT 或关闭 Library Validation;若 Wine 运行时确需例外,只对 Wine 可执行文件使用经测试的最小 entitlement。 + +## 实验空间音频构建 + +空间音频补丁来源、适配与验证要求见 [SPATIAL_AUDIO.md](SPATIAL_AUDIO.md)。构建脚本按 source.lock.json 的顺序和 SHA-256 校验应用补丁,并将完整补丁集打包进运行时。新构建版本为 11.0.3-spatial.2;应用默认下载仍使用现有 11.0.2 制品,不能以旧哈希代表新构建。 diff --git a/docs/SPATIAL_AUDIO.md b/docs/SPATIAL_AUDIO.md new file mode 100644 index 0000000..92c9b7e --- /dev/null +++ b/docs/SPATIAL_AUDIO.md @@ -0,0 +1,223 @@ +# Windows spatial audio port (experimental) + +This patch set adds Windows Spatial Audio object rendering to the existing +CrossOver FOSS Wine build. Games must actually use `ISpatialAudioClient` and +`ISpatialAudioObjectRenderStream` to supply dynamic objects. Ordinary stereo +mixes do not acquire object metadata through this change. There is no Dolby +Atmos bitstream output or head-tracking capability claim. + +## Provenance and scope + +- Destination repository baseline: `enginefuture/mac-gaming-uncle@1c65c3c527a43cb9ea3c0763acf2d4d8aa9e3a6c`. +- Wine source: the CrossOver 26.3.0 FOSS archive locked in + `runtime/indie-wine11/source.lock.json`, after existing patches 0001–0003. +- Donor: [Switchyard Wine](https://github.com/jungwuk-ryu/switchyard-wine/tree/codex/macos-fex-pro-review-20261005), + exact revision `ba57a08921dfe8f3a4281692b040cd2fa5acd94e`. +- Spatial implementation commits: + `4694d9dff307277abc5f27e68a80941898d0347d`, + `33905f4e445eb90abc1615714e9cfbeda2bb4dbf`, + `9806392a89eb5176a51f8d2fac68423d3634e322`, + `71fd097e6119c1076b67b2b7462edfa4441f2980`, + `db0f01e161e4abda59d574ad8ff5a991b0e4b075`. +- Required upstream spatial prerequisites: object format decoupling + `e237972495de7a70aef6587f332236292d69fa22` (Giovanni Mascellani) and + stream Reset `d39f7c2e8958c0735d10074985ac81698b8dd023` (Paul Gofman). +- Original implementation author: jungwuk-ryu. The port retains Wine's + LGPL-2.1-or-later notices. No FEX, native-gate SDK, ARM64EC translation, + Switchyard application code or proprietary CrossOver payload is included. + +The donor documentation and its measurements are references, not test results +for this port. The build packages the exact patch files and this provenance +notice alongside `source.lock.json`. + +## Patch layout + +| Patch | Content | +| --- | --- | +| 0004-spatial-audio-com.patch | COM contracts, static/dynamic object lifecycle, capacity/invalidation, audio-client helpers, shared Unix transport and non-CoreAudio ABI adapters | +| 0005-spatial-audio-coreaudio.patch | Spatial Mixer bed/point-source graph, physical output mapping, device timing/capability validation, synchronized PCM/metadata, real-time event relay and teardown | +| 0006-spatial-audio-tests.patch | Object/activation/reset/lifetime/invalidation tests and actual engine-period assertion | + +Apply all patches in the locked order. The shared Unix ABI changes require the +client, CoreAudio and other driver call tables to be rebuilt together; do not +replace just `spatialaudio.c` or install just one rebuilt DLL. + +ALSA, OSS and PulseAudio do not gain spatial rendering. Their private transport +rejection, pointer conversions and function tables are updated to match the +shared ABI, including new WoW64 calls. + +## CrossOver adaptations + +CrossOver 26.3.0 creates its audio timer through a PE `CreateThread` plus the +existing Unix `timer_loop` entry. The donor uses `PsCreateSystemThread`, which +this baseline does not export. This port keeps the PE-owned lifecycle: + +1. Create the graph and its preallocated coalescing Mach semaphore. +2. Before publishing spatial activation, create the PE timer thread in + `stream_init`; it runs the existing Unix call with the stream handle. +3. Spatial timer calls wait on the semaphore and relay endpoint-loss/audio + events; normal timer calls retain the existing periodic behavior. +4. Events before relay startup remain pending in the semaphore. Initialization + failures release the unpublished stream and join any created relay. +5. Teardown detaches/drains device listeners, signals and joins the PE relay, + stops/drains audio callbacks, then disposes units/buffers/handles. + +The object format stays mono float at 48 kHz rather than being replaced by +a physical endpoint's closest channel format. CoreAudio performs the output +conversion. + +CrossOver's HALOutput path and AppKit/AVFoundation links are preserved. The +Spatial Mixer needs `-fblocks` for device property listeners. This port does +not import Switchyard's unrelated default-device migration code. Spatial +streams remain tied to the activated endpoint; callers must reacquire and +reactivate after invalidation. + +## Native physical output layouts + +The renderer queries CoreAudio's preferred output layout and expands tags or +bitmaps through AudioFormat into channel descriptions. It preserves labels, +flags, coordinates and physical channel order, including LeftTopMiddle and +RightTopMiddle. The Spatial Mixer output and HALOutput input both receive this +native layout. Windows masks remain input-bed representations and are not used +to encode the mixer's physical output. PCM/position frame synchronization and +the shared Unix ABI remain unchanged. + +The reader checks description sizes, finite coordinates, a maximum of 64 output +channels, and agreement with actual output StreamConfiguration. Unknown, unused +or discrete channel labels cannot supply speaker directions. Mono/stereo may +fall back to an unambiguous existing mix format, but that fallback must still +match the actual output channel count; multichannel layouts are never guessed. +Non-spatial dry objects locate front-left/right or center in native channel +order. Devices without those named front channels are currently rejected. + +Capability generations hash the complete normalized layout. Preferred-layout +changes are listened for when the property exists; failure to subscribe to an +existing property rejects dynamic capacity. Active streams are invalidated +rather than retargeted silently. Aggregate/virtual devices must expose their +intended speaker layout; aggregation alone cannot infer physical placement or +correct clock drift and inter-device delay. + +The native helper test compiles the actual patched source helpers with mocked +device properties and Apple's real tag/bitmap expansion: + +```sh +python3 scripts/test-coreaudio-layout.py /path/to/patched/wine/source +``` + +It exercises 5.1.2 top-middle labels, reordered front channels, coordinates and +layout identity, malformed sizes, channel-count mismatch, unknown/discrete +labels, tag/bitmap expansion, and verified stereo fallback. + +## Build and test + +The full runtime build uses seven hash-locked patches and emits +`11.0.9-services.1`, including the rendering-capacity fix and audio services, +to distinguish it from the shipped `11.0.2` runtime: + +```sh +scripts/build-indie-wine11.sh +``` + +The package records the actual toolchain in `build-info.json` independently of +the reference versions in `source.lock.json`. A packaging audit checks required +files, native/PE architectures, bundled dependency resolution and patch hashes +before the archive is emitted. Use a whitespace-free `INDIE_WINE_BUILD_ROOT` +when overriding the default temporary build directory. The output directory +may contain spaces. See `docs/TESTING.md` for extracted-artifact and product +importer integration checks. + +The default download URL/hash in the application is unchanged: no experimental +runtime has been released. Import a locally built runtime to evaluate it. + +To replay patches on a clean, hash-verified extraction: + +```sh +python3 scripts/apply-wine11-patches.py /path/to/sources/wine +``` + +After configuring a new WoW64 build using the project's toolchain, build both +PE architectures and the Unix backend: + +```sh +make -j8 dlls/mmdevapi/all dlls/winecoreaudio.drv/all \ + dlls/mmdevapi/tests/x86_64-windows/mmdevapi_test.exe \ + dlls/mmdevapi/tests/i386-windows/mmdevapi_test.exe +``` + +Run each focused test in a dedicated disposable prefix with the newly built +client and backend, never a user's game prefix. For a complete Wine build: + +```sh +WINEPREFIX=/absolute/path/to/test-prefix ./wine \ + dlls/mmdevapi/tests/x86_64-windows/mmdevapi_test.exe spatialaudio +WINEPREFIX=/absolute/path/to/test-prefix ./wine \ + dlls/mmdevapi/tests/i386-windows/mmdevapi_test.exe spatialaudio +``` + +A run that skips for no audio endpoint or zero dynamic capacity is not evidence +of dynamic rendering. Record check/failure/skip counts, device layout/rate, +object capacity, runtime identities and output logs. Also run `render`, +`capture`, `mmdevenum` and `propstore` to check normal audio. + +`SWITCHYARD_SPATIAL_AUDIO_PROFILE=1 WINEDEBUG=+mmdevapi,+coreaudio` enables the +inherited bounded profiler. Its reported callback-allocation count is a source +path property, not an allocation-profiler measurement. The inherited +`SWITCHYARD_SPATIAL_AUDIO_FAULT_INVALIDATE_ON_START=1` and +`SWITCHYARD_SPATIAL_AUDIO_FAULT_INVALIDATE_BEFORE_START=1` hooks are for isolated +invalidation tests only; leave them unset for games. + +## Release gate + +Build/test outcomes for this checkout are recorded in +`docs/SPATIAL_AUDIO_VALIDATION.md`. Do not infer application compatibility from +module compilation or upstream tests. Before promoting the runtime, perform a +one-hour soak, real device changes/sleep-wake, stereo/headphone/multichannel +channel checks, confirmed object-audio game runs, D3DMetal launch and SDL/XInput +regressions. Keep the default release metadata at the existing validated +runtime until a new artifact has its own hash, signature and hardware results. + +## Spatial stream services (2026-10-10) + +Patch 0007 supplies `IAudioClock`, `IAudioClock2`, and `IAudioStreamVolume` from +`ISpatialAudioObjectRenderStreamBase::GetService`. Embedded service interfaces +hold stream references, retain the endpoint/render lifetime, and check sticky +spatial invalidation before accessing the underlying client. Clock/Clock2 share +IUnknown identity and can query each other; unsupported services return +E_NOINTERFACE and clear the output pointer. Null required outputs return +E_POINTER. + +The stream clock reuses the existing client position/frequency pair: both are +byte-based in shared mode, so position/frequency yields elapsed seconds. Reset +clears the stream position. Clock2 obtains the activated CoreAudio endpoint's +raw device frame timeline; it does not reinterpret private PCM bytes as device +frames. A stopped stream returns AUDCLNT_S_POSITION_STALLED with its last +observed device position. CoreAudio host timestamps are mapped to Wine QPC's +continuous epoch, including the difference between sleep-excluding host time +and continuous time. Queries run on the calling thread; realtime render +callbacks do not gain blocking calls, logging, or allocations. + +Volume channels follow this port's renderer input transport order: ordered +static channels, the dry channel, then dynamic-object slots. GetChannelCount +reports that stream's actual channel count, not the endpoint speaker count. +Controls reuse the existing per-input atomic gain path and combine with object +volume/session gain. All setters reject nonfinite values and values outside +[0,1]; batch validation completes before any channel is modified. This mapping +is the implementation's transport model; exact Windows channel mapping still +needs a Windows reference-machine conformance capture. + +IsSpatialAudioStreamAvailable now checks the base object stream against the +activated endpoint capability, and returns STREAM_NOT_AVAILABLE for unsupported +stream interfaces. HRTF/metadata stream implementations remain separate work. + +Validation: both i386 and x86_64 spatial suites execute 3090 checks, zero failures +and skips, with two pre-existing todo results. Added tests cover service +identity/reference lifetime, pointer/range errors, atomic rejection of invalid +volume batches, round trips, clocks during playback/stop/reset, and fault-driven +endpoint loss. The independent prefix uses WINEARCH=wow64; default-prefix setup +previously omitted syswow64 builtins, which explained the earlier x86 loader +failure. See work/full-runtime/spatial-services for logs and package audit. + +References: [GetService](https://learn.microsoft.com/en-us/windows/win32/api/spatialaudioclient/nf-spatialaudioclient-ispatialaudioobjectrenderstreambase-getservice), +[clock units](https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclock-getfrequency), +[device position](https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclock2-getdeviceposition), +and [batch volume validation](https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiostreamvolume-setallvolumes). diff --git a/docs/SPATIAL_AUDIO_VALIDATION.md b/docs/SPATIAL_AUDIO_VALIDATION.md new file mode 100644 index 0000000..653362d --- /dev/null +++ b/docs/SPATIAL_AUDIO_VALIDATION.md @@ -0,0 +1,122 @@ +# 空间音频移植验证记录 + +日期:2026-10-09(Asia/Shanghai)。这是本地移植的结果,不引用上游成绩作为本项目成绩。 + +## 最新结果:完整实验制品与产品导入 + +包含 FreeType、GMP、Nettle、GnuTLS、libinotify-kqueue、SDL2 的完整 `11.0.3-spatial.2` 已构建并打包。最终压缩包为 `indie-wine-11.0.3-spatial.2-macos-x86_64.tar.xz`,47,004,056 字节,SHA-256 `b2a970c8484884130325e967f8bd230708374910add5fdc5ee52585d1d640474`。开发应用包 `Mac-Gaming-Uncle-spatial-test.zip` 的 SHA-256 为 `56bf9f2cecdd7c2ed93d6611dcedf729d0e6334e3b935b6b639a3904957961b2`,ad-hoc 签名校验通过,未公证或发布。 + +实际环境仍为 Xcode/SDK 27 与 MinGW GCC 16.1,不是参考工具链复现。制品内 `build-info.json` 保存实际环境及构建脚本哈希,`package-audit.json` 保存打包检查。从最终压缩包重新解压后的 38 个原生模块、双架构关键 PE、补丁哈希及可重定位依赖检查均通过。 + +本轮修复两项构建问题:上游 Autoconf 不支持含空白的构建目录,入口现提前拒绝;旧 zsh 动态库路径拆分将多条依赖合并,导致 GnuTLS/Nettle 引用构建目录,现逐行正确改写。另设置 `ac_cv_func_pipe2=no`,使用已有 pipe/fcntl 路径,避免 SDK 27 将仅 macOS 27 可用的 pipe2 引入最低目标为 macOS 15 的 ntdll;最终 ntdll 不导入该符号。旧 macOS 真机兼容仍未验证。 + +界面通用 Wine 导入器现在识别本项目源码锁定标记,转交完整构建导入器,保留游戏引擎身份及 `11.0.3-spatial.2` 版本。真实制品通过该路径安装到中文、空格路径,再由产品 WineRuntimeProvider 初始化独立容器并执行 cmd,集成测试通过。新增逐游戏空间音频诊断日志开关,默认关闭;开启后诊断环境经游戏 LaunchPlan 传递到 Steam 启动链路,保留 D3DMetal 库路径。 + +| 最终解压制品检查 | 结果 | +| --- | --- | +| wineboot / x64、x86 cmd | 通过 | +| x64、x86 窗口自动退出探针 | 通过;不等同于中文字体视觉验收 | +| 内置 WineD3D D3D11 | 120 帧提交通过 | +| GPTK 4.0b2 D3DMetal D3D11 / D3D12 | 产品导入、Bridge 与 LaunchPlan 链路通过;各提交 120 帧,dyld 日志确认导入的 libd3dshared 与 D3DMetal.framework 已加载 | +| x86_64 spatialaudio | 2998 检查,0 失败,0 跳过,2 todo | +| i386 spatialaudio | 2998 检查,0 失败,0 跳过,2 todo | +| x86_64 render | 4440 检查,0 失败,2 跳过,177 todo | +| x86_64 mmdevenum / propstore | 72 / 241 检查,0 失败;propstore 保留 14 todo | +| XInput | 未连接实体手柄,不能作为实体输入通过 | + +默认输出查询仍为虚拟 `Dolby_5.1.2`,8 声道及顶中坐标保留。测试使用新的临时容器,未改变 macOS 默认输出;临时容器禁用附加组件的设置不进入产品游戏默认配置。mmdevapi 测试程序由本次完整源码树重新编译。最终 Swift 检查为 98 项测试、0 失败、4 跳过(两项需要真实包/GPTK 的集成测试已独立实跑通过);补丁测试 7 项、Release 构建及五个 Windows 探针编译通过。 + +结构化证据见 [spatial-runtime-20261009.json](validation/spatial-runtime-20261009.json),原始运行日志保留在工作区 `work/full-runtime`。后续 D3DMetal 实跑测试在独立容器完成;日志含 Vulkan 未编译和 Apple Neural Engine Code 26 提示,但两个探针均成功完成,不能据此推导复杂游戏兼容。用户本机已安装实验引擎和 GPTK 4.0b2,Steam 已更新到官方登录界面。下一步测试《双影奇境》及当前默认设备,按 [游戏验收指南](SPLIT_FICTION_VALIDATION.md)记录。真实游戏、实体扬声器方向、一小时压力和设备事件仍未完成;默认下载仍为 11.0.2。 + +## 最新结果:CoreAudio 原生设备布局适配 + +本轮修改修复了下面历史记录中的默认 8 声道限制。补丁 `0005` 和锁定哈希已更新;构建版本为 `11.0.3-spatial.2`。本轮未重新运行无改动的 Swift 应用测试。 + +原生查询得到默认端点 `Dolby_5.1.2`(设备 ID 145,transport `virt`),8 个描述按设备顺序为:Left、Right、Center、LFE、LeftSurround、RightSurround、LeftTopMiddle、RightTopMiddle。顶部标签为 49/51,设备提供球面坐标 [-90,45,1] / [90,45,1]。保留这些原生描述,不再要求物理输出可表示为 Windows speaker mask。 + +| 本轮测试 | 检查数 | 失败 | 跳过 | todo | +| --- | ---: | ---: | ---: | ---: | +| x86_64 spatialaudio,Dolby_5.1.2 | 2998 | 0 | 0 | 2 | +| i386 spatialaudio,Dolby_5.1.2 | 2998 | 0 | 0 | 2 | +| x86_64 spatialaudio,内建立体声 | 2998 | 0 | 0 | 2 | +| i386 spatialaudio,内建立体声 | 2998 | 0 | 0 | 2 | +| x86_64 render,默认 8 声道设备 | 4440 | 0 | 2 | 177 | +| x86_64 mmdevenum | 72 | 0 | 0 | 0 | +| x86_64 propstore | 241 | 0 | 0 | 14 | + +诊断 trace 确认:Spatial Mixer 使用 2 声道输入床、31 个 PointSources、8 个输出声道,输出类型 3、算法 7。最终 profile 66 个样本,p50=379541 ns、p95=484417 ns、p99=527333 ns,underrun/overrun/reentrant reject 均为 0。callback allocations=0 是源码路径属性,未运行分配探测器。 + +六个最终补丁在原始归档文件上重新应用成功(零 fuzz、零 offset),音频源码与实际编译文件逐字节一致。补丁管理测试 7 项通过,CoreAudio Clang 静态分析无报告,源码及仓库 diff 检查通过。编译无新增警告。原生布局辅助测试直接编译本次 Wine 的布局函数,设备属性用夹具,AudioFormat 展开用 Apple 真实框架;验证顶中标签、声道重排后的 dry 路由、坐标保留与变化身份、非法尺寸、实际声道数不符、未知/离散标签拒绝、tag/bitmap 展开,以及严格核对实际通道的双声道回退。 + +发现并修复了回归:内建设备提供含无效标签的首选布局。单/双声道允许原有格式回退并核对 StreamConfiguration;多声道仍拒绝猜测。最终两种设备、双架构测试均通过。仅临时 prefix 的 DefaultOutput 用于双声道回归,测试后已删除;macOS 默认设备未修改。 + +布局身份包含全部标签、flags、坐标和顺序;添加 PreferredChannelLayout 属性监听,布局改变时旧流失效。未主动改变系统设备布局以测试真实硬件事件。没有进行声学方向确认、多个物理设备间时钟/延迟测试、真实游戏或完整签名发行包验证。`Dolby_5.1.2` 端点暴露的虚拟布局已验证,不能等同于全部实体扬声器已验证。 + +## 源码与构建 + +- Mac Gaming Uncle 基线:`1c65c3c527a43cb9ea3c0763acf2d4d8aa9e3a6c`。 +- 来源分支固定为 `ba57a08921dfe8f3a4281692b040cd2fa5acd94e`,提交清单与前置修复见 `source.lock.json`。 +- CrossOver 26.3.0 归档 SHA-256:`ac99c8ca4b3848f3e81784135f023df266b61c2345726ea55a50b3e030dd6872`,已校验。 +- 全部六个补丁在重新提取的原始文件上按锁定顺序应用成功,`--fuzz=0`;没有偏移或模糊匹配。11 个音频文件与实际编译源码逐字节一致。 +- COM、CoreAudio 与空间音频测试程序的 i386/x86_64 PE 编译通过;CoreAudio Unix 模块为 x86_64。 +- 诊断 Wine 的全部运行时目标构建通过,`wine --version` 返回 `wine-11.0`。 + +测试机:Apple M4、macOS 27.0.1 (26A434)。实际工具链为 Xcode 27.0、Apple Clang 21.0.0、SDK 27.0、MinGW GCC 16.1.0。 + +本机工具链与锁定文件声明的 Xcode 26.6/GCC 15.1 不同,不能当作那套工具链的复现。诊断构建采用 new WoW64、i386/x86_64,原生模块最低部署目标 15.0;为了聚焦音频,未启用 FreeType、GnuTLS、SDL、Vulkan 等可选依赖。未执行完整依赖打包、签名或发布,因此它不是供游戏使用的完整运行时制品。 + +基线 ntdll 在 SDK 27 下存在 `pipe2` 最低系统版本警告;本次没有修改这些无关代码。 + +## 自动化与静态分析 + +- `python3 scripts/test-wine11-patches.py`:7 项通过。覆盖真实补丁应用、重复应用拒绝、清单顺序、未知补丁、重复条目、路径穿越和哈希不匹配。 +- `swift test --jobs 4`:96 项、0 失败,2 项跳过(选择性网络/Apple 签名集成与本机 Steam 缓存读取)。 +- `zsh -n`:构建脚本与检查脚本通过。 +- `git diff --check`:通过。 +- Clang 静态分析:CoreAudio 与最终 `spatialaudio.c` 没有报告;通用 `client.c` 的 QueryInterface 路径报告一个空指针警告,未修改的 CrossOver 基线也报告同一问题。未声称整个基线没有问题。 + +## 首次移植的本机运行时测试(历史记录) + +采用独立临时 prefix,未使用游戏容器。首次默认初始化在 180 秒时超时;诊断容器设置 `WINEDLLOVERRIDES=mscoree,mshtml,winemenubuilder.exe=d` 后完成初始化。这只用于隔离无关附加组件,不进入产品默认配置。 + +| 测试与设备 | 检查数 | 失败 | 跳过 | todo | 结果 | +| --- | ---: | ---: | ---: | ---: | --- | +| x86_64 spatialaudio,内建立体声 | 2998 | 0 | 0 | 2 | 通过 | +| i386 spatialaudio,内建立体声 | 2998 | 0 | 0 | 2 | 通过 | +| x86_64 render,系统默认设备 | 4440 | 0 | 2 | 177 | 通过,带已标注限制 | +| x86_64 mmdevenum | 72 | 0 | 0 | 0 | 通过 | +| x86_64 propstore | 241 | 0 | 0 | 14 | 通过,带已标注 todo | +| x86_64/i386 spatialaudio,系统默认 8 声道设备 | 各 86 | 各 9 | 0 | 各 1 | 布局不受支持;不能作为通过 | + +默认设备的布局包含 `LeftTopMiddle` / `RightTopMiddle`(49/51),首次移植的映射无法在 WAVE mask 中准确表达。能力查询返回 `AUDCLNT_E_UNSUPPORTED_FORMAT`,测试由此报告失败。保留失败记录,未通过猜测映射或关闭检查来让测试变绿。 + +为验证对象实现,仅在临时 Wine prefix 的 `HKCU\Software\Wine\Drivers\winecoreaudio.drv` 设置 `DefaultOutput` 为内建立体声端点;没有修改 macOS 的默认音频设备。之后双架构的完整聚焦测试均通过,包括动态对象耗尽/复用、位置、音量、结束、Reset、最大对象持续提交、预 Start 失效、后端失效转发和回调重入释放。实际听感与真实多声道仍未验证。 + +`render` 的两项跳过与已有 todo 保留,未将它描述为无条件完整 WASAPI 兼容。未运行可能要求麦克风权限的 capture 测试。 + +## 短时性能记录 + +内建立体声端点使用 48 kHz、512 帧周期(10.6667 ms),实际报告 31 个动态对象。带诊断开关的 x86_64 聚焦测试再次通过 2998 项、0 失败、0 跳过、2 todo。 + +最大 31 对象路径采样 66 次:回调 p50 338166 ns、p95 434125 ns、p99 454125 ns;该短窗口内 underrun/overrun/重入拒绝均为 0。接口报告的流延迟为 167292 个 100 ns 单位(16.7292 ms),不是声学端到端实测延迟。回调分配计数是代码路径声明,未由 Allocations 验证。 + +短时数据仅用于证明本机渲染路径确实工作,不能推导一小时稳定性或所有硬件性能。 + +## 真实游戏回归发现 + +《双影奇境》在新 11.0.3-spatial.2 下严重卡顿并卡住,关闭 MetalFX、Metal 4 和音频诊断后仍复现。切回既有 11.0.2、保持基础配置,用户确认完全正常。实验包已暂时移出活动运行时目录。该结果阻止实验运行时推广;探针通过不代表真实游戏验收通过。回归可能来自空间音频补丁、构建工具链或其他运行时差异,需同源码/工具链的无补丁对照进一步定位。 + +## 尚未验收 + +- Xcode 26.6/GCC 15.1 参考工具链复现;完整依赖打包已在本轮实际工具链下完成。 +- 真实游戏是否提交空间对象以及听感/坐标准确性。 +- 物理 USB/HDMI 多声道输出、耳机、蓝牙、拔插、睡眠与采样率切换。 +- 一小时压力测试、内存和线程 sanitizer、实测端到端声学延迟。 +- D3DMetal 真实游戏与实体手柄的本机回归;D3D11/12 探针已通过,完整实验包已包含 SDL2,XInput 探针未检出连接的实体手柄。 +- 应用默认发布制品更新;其下载地址和哈希仍对应既有 11.0.2。 + +源码移植与编译通过,不等于以上硬件、游戏或发布要求全部通过。 + +2026-10-10 用户调整默认输出为 7.1.4 后重新读取 CoreAudio:设备仍名 Dolby_5.1.2,实际输出已为 12 声道/48 kHz,具备前/中/低频/侧/后与四个顶部方向标签,顺序按原生布局保留。服务版 11.0.9-services.1 在此输出上执行 x64 空间套件 3090 项、0 失败、0 跳过、2 既有 todo。确认 7.1.4 端点渲染路径通过,不将其等同于实体扬声器方向听感验收。证据:work/full-runtime/spatial-services/output-layout-7.1.4.txt 和 spatial-7.1.4-x64.log。 + +2026-10-10 用户确认 11.0.9-services.1 在 7.1.4(12 声道、48 kHz)输出下,同一场景“画面流畅、操作和声音正常”。本轮真实游戏短测验收通过,新增时钟/音量服务未在该场景引入已观察到的回归。此结论不替代实体扬声器方向、设备拔插/睡眠恢复及长时压力验收,也不证明游戏已调用每一个新增服务接口。 diff --git a/docs/SPLIT_FICTION_VALIDATION.md b/docs/SPLIT_FICTION_VALIDATION.md new file mode 100644 index 0000000..e61924c --- /dev/null +++ b/docs/SPLIT_FICTION_VALIDATION.md @@ -0,0 +1,94 @@ +# 《双影奇境》空间音频实验验收 + +测试由用户执行,输出设备使用 macOS 当前默认设备。尚未确认游戏是否调用 Windows Spatial Audio API,也未宣称游戏兼容或实际空间效果已通过。 + +## 实验包安装 + +1. 使用本轮构建的 `dist/Mac Gaming Uncle.app`。 +2. 解压 `dist/runtime/indie-wine-11.0.3-spatial.2-macos-x86_64.tar.xz`,在应用“运行时 → 导入本地 Wine”选择 `wine-runtime` 文件夹。仓库已有解压目录 `dist/runtime/extracted/wine-runtime`。 +3. 在运行时列表确认 **11.0.3-spatial.2** 已导入。导入器保留游戏引擎身份和实验版本,游戏流程会选择已安装的较新游戏引擎。 +4. 完全退出游戏及应用托管的 Windows Steam,再重开应用和 Steam,使旧 Wine 进程退出并重新加载新引擎。保留原有图形配置;若应用要求 D3DMetal,请先完成 GPTK 导入。 + +如果首次启动还未完成环境设置,也可以先用仓库 CLI 导入: + +```sh +.build/release/macgamingunclectl wine local-install dist/runtime/extracted/wine-runtime +``` + +原有运行时目录和游戏数据保留;需要回退时,退出游戏和 Windows Steam,将实验版本移出运行时目录并重开应用。应用默认下载制品仍为 11.0.2。 + +## 两次游戏测试 + +2026-10-09 本机已完成实验运行时安装及 GPTK 4.0b2 导入,应用托管的 Windows Steam 已更新并到达官方登录界面。用户可直接在该窗口登录,随后在应用同步的游戏库中安装或启动《双影奇境》。登录成功及真实游戏运行结果仍待记录。 + +先关闭“游戏设置 → 音频诊断 → 记录空间音频诊断日志”,验证游戏进入实际场景、普通声音、画面与输入,运行至少 5 分钟。记录游戏 BuildID、音频设置、图形后端、运行时版本和异常退出。 + +随后退出游戏,打开该诊断开关并保存,完全退出托管的 Windows Steam 后重新启动游戏。在同一场景短时测试 1–3 分钟,移动人物和转动视角;如游戏提供空间音频相关设置,记录具体选项与选择,不猜测选项名称。正常退出以便收集流销毁时的回调 profile。测试后关闭诊断并再次重启游戏/Steam。 + +日志位于 `~/Library/Application Support/Indie/Logs`,每次启动保留 LaunchPlan 与 Wine 输出。提交此次运行对应的日志及下方观察记录。 + +## 判定与记录 + +截至 2026-10-09 本轮构建测试开始时,默认设备为 **Dolby_5.1.2**,transport 为 `virt`,8 声道顺序为 L、R、C、LFE、Ls、Rs、LeftTopMiddle、RightTopMiddle。这是设备暴露的虚拟布局;用户测试时按实际默认设备记录,设备 ID 不作为稳定身份。 + +| 项目 | 用户测试记录 | +| --- | --- | +| 游戏版本 / Steam BuildID | 待填 | +| macOS / 运行时 / 图形后端 | 待填 | +| 默认输出设备 / 游戏音频设置 | 待填 | +| 实际场景进入 / 画面 / 输入 / 普通声音 | 待填 | +| 左右、前后、上下听感及对白清晰度 | 待填 | +| 卡顿、破音、无声或异常退出 | 待填 | +| 本次 LaunchPlan 与 Wine 日志文件 | 待填 | + +动态对象结论需结合流激活、动态对象创建、缓冲更新和位置调用。仅查询对象容量、出现 Spatial Mixer 初始化信息或存在环绕听感,都不足以证明游戏提交了动态对象。若游戏未调用该 API,应记录为普通音频路径,并单独判断普通音频是否正常。 + +实体扬声器方向、拔插/睡眠恢复与一小时压力仍另行验收;本次游戏短测不替代这些项目。 + +## 首次真实游戏反馈(2026-10-09) + +用户报告进入游戏后严重卡顿,随后完全卡住。Steam 记录 20:59:28 启动、21:02:31 退出,退出码 1。D3DMetal 日志出现 Apple Neural Engine Code 26,因果关系尚未确认。反馈后设置界面显示 MetalFX、Metal 4 和空间音频诊断均开启;该界面状态不独立证明首次进程继承的全部环境。已关闭并保存这三个选项,发起基础配置复测,结果待确认。真实游戏验收当前记为失败,探针通过不能替代此结果。 + +基础配置复测仍卡住。已采集 5 秒线程采样,物理内存占用约 2.2 GB;Wine/Rosetta 调用栈在 syscall dispatcher 中反复展开,不能据此断言死锁位置。当前暂时将实验运行时保存在 `~/Library/Application Support/Indie/DisabledRuntimes/org.indie.wine11/11.0.3-spatial.2`,重启应用并切回已安装的 11.0.2 做同配置引擎对照,结果待用户确认。 + +## 引擎对照结果 + +用户确认切回 11.0.2 后“很正常完全没有任何问题”。保持 MetalFX、Metal 4、空间音频诊断关闭的基础配置,新实验 11.0.3-spatial.2 卡住,既有 11.0.2 正常;当前问题范围收敛到实验运行时或其构建差异,尚不能单独归因于空间音频补丁。日常使用保持 11.0.2,实验包继续存放于 DisabledRuntimes。下一步应优先用同一源码与工具链构建不含空间音频补丁的对照运行时,定位回归;修复后再进行空间音频验收。 + +## 同工具链无空间补丁对照包 + +诊断制品为 `dist/runtime/control/wine-runtime`,版本 `11.0.3-control.1`。以完整实验包为基底,在原构建树中撤去 0004/0005/0006 后,仅重新编译 mmdevapi 与 winecoreaudio 模块;依赖、编译参数和其余运行时二进制保持一致。共校验 1600 个 lib/wine 文件,实际变化仅为 x86_64 Unix winecoreaudio.so 和 i386/x86_64 mmdevapi.dll。源文件已恢复补丁版本并更新时间戳,后续重建会重新编译;原实验制品未改变。 + +审计、构建命令、模块哈希及启动验证证据位于 `work/full-runtime/spatial-control`。旧 `build-info.json` 的构建记录保留为基底记录,通过新增 controlVariant 字段明确本次重编译与移除补丁,sourceLockSHA256 已按对照清单更新。本包仅用于隔离回归,不是 11.0.2 的重新发布或空间音频实现的验收。 + +用户要求关闭游戏后,游戏已结束;对照包不自动安装到日常活动运行时。下一次真实游戏对照保持同一游戏设置。若本包正常,可进一步分别替换 CoreAudio 和 mmdevapi,以定位音频层回归;若仍卡住,再检查新工具链及其他构建差异。 + +对照包已通过 38 个 Mach-O 模块审计、产品导入/容器初始化及 D3DMetal D3D11/12 实跑集成测试(2 项、0 失败),基础冒烟 7 项均返回 0。XInput 探针此时成功,不单独证明物理手柄全流程。游戏关闭状态已核实;真实游戏结果仍待下一次测试。 + +用户随后明确要求使用对照包测试。已通过产品 CLI 导入 11.0.3-control.1,重启应用,核对 MetalFX、Metal 4、空间音频诊断均关闭,并发起启动;实际 wineserver 路径已确认为 control.1。真实游戏结果待用户观察。 + +用户确认 11.0.3-control.1“没有问题非常流畅”。再次比较本机安装的 control.1 与停用的 spatial.2:lib/wine 1600 个文件中仅 CoreAudio Unix 模块及双架构 mmdevapi.dll 不同,wine/wineserver 二进制一致。图形模块和外部 GPTK/D3DMetal 未改变,因此回归范围进一步隔离到空间音频补丁组(包括普通 CoreAudio 端点/声道行为改动);尚未定位到某个函数或证明游戏调用了空间音频 API。下一步可分别对照 CoreAudio 和 mmdevapi,而无需改动图形层。 + +## 第一步:阻断空间音频客户端激活 + +诊断版本 11.0.4-probeoff.1 以原 spatial.2 为基底,只改变双架构 mmdevapi.dll,在 SpatialAudioClient_Create 返回 E_NOINTERFACE(输出指针为 NULL),并写入固定 MGU_DIAGNOSTIC 标记。其余新音频实现、CoreAudio、图形层与原实验包一致。32/64 位独立探针验证 HRESULT=0x80004002,普通混音查询仍为 8 声道/48 kHz,设备周期 106667 个 100 ns 单位。已导入并发起真实游戏测试,游戏结果和是否实际请求该接口待观察。该诊断版本不用于发布。证据位于 work/full-runtime/spatial-probe-gate。 + +诊断启动已确认加载 11.0.4-probeoff.1;游戏启动日志 242AECA5-6F26-4902-9EDC-D5C73DFACC4E-steam-d3dmetal.log 出现 SpatialAudioClient 激活阻断标记。已请求用户在同一场景报告画面及声音。能力探测确有发生,但是否导致卡顿仍需此次结果。 + +用户确认 probeoff.1“画面流畅,声音正常”。此版本保留新 CoreAudio 与普通音频代码,仅拒绝空间客户端激活,因此回归范围进一步收敛到空间客户端成功激活或后续空间 API 路径;不再以普通音频周期变化作为首要方向。正在准备恢复支持并加有限 COM 层标记的 trace 诊断版本。 + +## 第二步:恢复支持并观察调用顺序 + +11.0.5-trace.1 恢复原 spatial.2 语义,只在 COM 层添加最多 256 条带进程/线程 ID 的进入、HRESULT 返回及能力/初始化参数标记,不在 CoreAudio 实时回调中打印。双架构空间测试各 2998 项、0 失败、0 跳过、2 todo。已安装并发起游戏复现,定位能力查询、流初始化或开始更新的具体路径;证据保存在 work/full-runtime/spatial-trace。 + +用户确认 trace.1 恢复空间支持后又卡顿/卡死。trace2.1 在双架构 2998 项测试各 0 失败后加入缺失接口 GUID 追踪及独立更新失败日志,真实进程加载版本已核实。公共标记记录大量重复建流,尚未出现缺失接口调用标记。更新成功仅前四条为设计限流,不能认定后续不更新。微软文档与实现缺口对照见 WINDOWS_SPATIAL_AUDIO_COMPARISON.md。 + +11.0.7-native-trace.1 增加 CoreAudio 错误阶段及设备 selector 标记,实时回调不打印,保留原始语义;已通过 48 个 Mach-O 审计,导入并发起复现。证据位于 work/full-runtime/spatial-native-trace,游戏结果待底层日志。 + +原生追踪运行约 3 分钟,未出现设备 selector 或回调失效错误,公共 COM 标记仍记录重复建流。按微软 BeginUpdatingAudioObjects 的“本轮可渲染数量”定义制作 11.0.8-capacity.1,单独改变 Begin 动态数量返回值从分配余额为流容量;修订测试中的满分配预期。真实游戏日志显示 allocated=31、capacity=31,持续更新且目前仅一次建流。用户同场景画面/声音结果待确认,不能仅由日志替代实跑验收。 + +2026-10-10 用户确认容量单点对照在同一场景“画面流畅、操作和声音正常”。结合保留空间支持、只改变 Begin 动态数量语义、重复建流消失,可将本次卡顿/卡死归因于渲染容量被错误返回为未分配槽位数量。正式 0004 COM 补丁和 0006 测试已修订,source.lock.json 哈希更新,完整空间补丁组零 fuzz 重应用通过。其他缺失服务接口仍是实现后续工作,不是此次已验证原因。32 位独立测试 prefix 问题另行修复,当前只确认容量版 64 位完整测试通过。本结果不替代空间听感、设备拔插及长时压力验收。 + +2026-10-10 服务版 11.0.9-services.1 已在 7.1.4 默认输出(12 声道、48 kHz)下启动《双影奇境》,实际 wineserver 路径与游戏进程已核实。启动日志为 14CF7E0D-24AF-4874-B9D9-B73EB39C8260-steam-d3dmetal.log。已请用户在此前卡住的同一场景检查画面、操作和声音,结果待反馈。日志仍出现此前观察过的 Apple Neural Engine Code 26,不据此判定本轮失败或音频因果。 + +2026-10-10 用户确认 11.0.9-services.1 在 7.1.4(12 声道、48 kHz)输出下,同一场景“画面流畅、操作和声音正常”。本轮真实游戏短测验收通过,新增时钟/音量服务未在该场景引入已观察到的回归。此结论不替代实体扬声器方向、设备拔插/睡眠恢复及长时压力验收,也不证明游戏已调用每一个新增服务接口。 diff --git a/docs/TESTING.md b/docs/TESTING.md index c2f4e05..d029b99 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -6,7 +6,7 @@ scripts/check.sh ``` -该命令运行 Swift 单元测试、Release 构建以及四个 Windows 测试程序的交叉编译。当前测试覆盖: +该命令运行 Wine 补丁校验测试、Swift 单元测试、Release 构建以及五个 Windows 测试程序的交叉编译。当前测试覆盖: - 模型 JSON 往返、SemVer、SQLite 持久化; - Ed25519 Manifest 验签、渲染器优先级、内核反作弊阻断; @@ -32,3 +32,67 @@ scripts/check.sh 必须验证:损坏哈希/签名、非 Apple GPTK、双层 DMG 中断、错误 DLL Overlay、磁盘不足、中文/空格路径、外置盘、Bottle 并发锁、Wine 非零退出、快照回退和离线启动。 正式发布不能要求 `sudo`、关闭 SIP/Gatekeeper,或对用户目录执行递归 quarantine 清除。 + +## 实验空间音频 + +补丁回放、双架构编译和空间对象/设备失效测试见 [SPATIAL_AUDIO.md](SPATIAL_AUDIO.md)。本机结果单独记录在 [SPATIAL_AUDIO_VALIDATION.md](SPATIAL_AUDIO_VALIDATION.md)。普通音频、D3DMetal、手柄和物理多声道仍分别验收。 + +### 完整运行时打包检查 + +`scripts/build-indie-wine11.sh` 在打包前生成 `build-info.json`(实际 macOS、SDK、编译器和构建脚本哈希)与 `package-audit.json`(必需文件、双架构 PE、x86_64 Mach-O、可重定位依赖与补丁哈希检查)。实际环境记录不替代 `source.lock.json` 的参考工具链,也不构成该工具链的复现声明。上游 Autoconf 要求构建目录不含空白;默认临时目录符合此要求,输出目录可含空格。 + +Wine 配置显式设置 `ac_cv_func_pipe2=no`,使用已有 `pipe`/`fcntl` 路径。SDK 27 提供的 `pipe2` 仅在 macOS 27 可用,不能仅凭新系统上的 configure 探测将其引入最低目标为 macOS 15 的制品。打包检查同时拒绝 ntdll 对 `_pipe2` 的导入;这不替代旧 macOS 真机测试。 + +解压后再次验证,确保验证的是最终制品: + +```sh +python3 scripts/verify-wine-runtime.py /path/to/wine-runtime +INDIE_TEST_WINE_RUNTIME=/path/to/wine-runtime \ + swift test --jobs 4 --filter PackagedWineIntegrationTests +``` + +集成测试通过产品本地导入器安装到隔离目录,再通过 `WineRuntimeProvider` 初始化独立容器并执行命令。路径同时包含中文和空格;测试结束关闭对应 wineserver 并清理目录。未提供环境变量时明确跳过,不记为真实运行时通过。 + +已导入 GPTK 时,可额外验证产品 D3DMetal 启动链路: + +```sh +INDIE_TEST_WINE_RUNTIME=/path/to/wine-runtime \ +INDIE_TEST_D3DMETAL_ROOT=/path/to/imported/renderer \ +INDIE_TEST_D3DMETAL_LOGS=/path/to/logs \ + swift test --jobs 4 --filter testPackagedRuntimeWithImportedD3DMetal +``` + +先编译下方 Windows 探针。测试使用独立容器,将探针复制到 C: 盘,再通过产品 Bridge 安装与 LaunchPlan 分别运行 D3D11、D3D12 的 120 帧测试,并核对实际加载导入的 `libd3dshared.dylib`。不修改 Steam 或游戏容器。 + +```sh +scripts/build-windows-fixtures.sh +python3 scripts/smoke-wine-runtime.py /path/to/wine-runtime \ + --output dist/runtime-smoke \ + --mmdevapi-tests /path/to/wine-build/dlls/mmdevapi/tests +``` + +冒烟脚本使用全新的临时 prefix,记录 32/64 位命令、窗口、内置 WineD3D D3D11、XInput 和可选双架构空间音频/普通音频测试。窗口测试会短暂显示窗口;`--smoke` 模式的 D3D11/12 探针须成功提交 120 帧,提前关闭不记为通过。XInput 返回“未连接手柄”单独记录,不能据此宣称实体手柄通过。脚本仅在该临时容器禁用附加组件,游戏默认配置不变。没有 D3DMetal 导入时不执行 D3D12,也不宣称 D3DMetal 通过。 + +## Wine 版本管理 + +在“高级设置 → 运行环境 → Wine 运行环境”核对“当前使用”和“正在运行”:前者为下次启动选择,后者根据该运行时目录内的真实进程检测,每两秒刷新。未手动选择时使用已安装的最新 Mac Gaming Uncle Wine;显式选择保留到下次打开应用,导入更高版本不会覆盖选择。普通本地 Wine 可以删除,但不作为 Mac Gaming Uncle 游戏引擎候选。 + +切换前退出游戏及 Windows Steam;有 Wine 进程时拒绝切换。删除需确认,当前选择或仍在运行的版本无法删除。删除仅将应用管理的运行时目录移到废纸篓,保留容器、游戏及原始导入来源。自动化检查覆盖显式选择、失效选择回退、外部目录/符号链接保护和运行中版本拒绝删除。 + +可使用 `MAC_GAMING_UNCLE_APP_DESTINATION=/absolute/path/Preview.app scripts/build-app.sh` 在独立目录构建开发应用,避免替换正在打开的应用包。 + +## Steam 获取与界面状态 + +商店输入停顿 350 ms 自动搜索,回车/按钮仍可立即搜索;每次改词或清空输入均使旧请求失效并取消请求。加载、短关键词、无匹配、连接失败分开显示。游戏库筛选无结果可一键恢复全部;首页不会用 Steam 会话状态推断云存档同步,也不默认宣称游戏兼容性优秀。 + +SteamLibraryReader actor 将本地文件解析移出主线程:下载清单最多每秒读取一次,账户/成就/库位置每五秒更新,手动刷新可强制更新。元数据缓存每个应用进程只加载一次,写入在后台执行;资料补全保留八个请求的并发上限,结束/取消时清理任务引用。失败按 10、20、40…秒重试,上限五分钟;手动刷新重置重试间隔。单个资料请求超时为 15 秒。 + +SteamRefreshPolicyTests 验证旧搜索响应与清空后的响应不能覆盖界面、无结果和错误分离、重试间隔与重置、扫描频率/强制刷新/根目录变化,以及下载完成在下一秒生效而无需等待完整账户扫描。网络及真实账户信息仍通过可选本机检查验证,不以合成数据测试替代 Steam 服务连通性。 + +## 展示检查 + +商店与游戏库工具栏在空间不足时拆成两行;游戏标题保留两行并可悬停查看完整名称。主页和商店横向列表提供按当前可见卡片数量翻页的左右按钮,到首尾禁用;触控板滚动和滚动条仍可使用。商店列表按游戏 ID 去重并展示全部条目,不再只展示前 20 项。检查宽窗口、最小窗口、长游戏名、翻页后继续滚动,以及过滤/切换分类后的翻页状态。 + +## macOS 窗口快捷键 + +关闭窗口使用系统文件菜单的 ⌘W;最小化 ⌘M,最大化/恢复 ⌃⌘M,全屏切换 ⌃⌘F。窗口菜单显示对应操作,使用 AppKit 响应链作用于活动窗口。检查文本框聚焦时按键仍生效,最大化与全屏均可恢复;关闭最后一个窗口会按原有退出流程关闭托管 Steam。 diff --git a/docs/WINDOWS_SPATIAL_AUDIO_COMPARISON.md b/docs/WINDOWS_SPATIAL_AUDIO_COMPARISON.md new file mode 100644 index 0000000..5e0fd8d --- /dev/null +++ b/docs/WINDOWS_SPATIAL_AUDIO_COMPARISON.md @@ -0,0 +1,56 @@ +# Windows 空间音频与 Wine 对照:Split Fiction 卡顿定位 + +2026-10-09。结论分为已复现事实、实现缺口和待验证原因,避免把 API 尚未完成等同于本次根因。 + +## Windows 的生成与输出流程 + +游戏引擎为声音对象提供单声道 PCM 和位置/音量;静态对象对应固定扬声器方向,动态对象可以移动。ISpatialAudioClient 查询格式与对象容量,激活带 EventHandle 的空间流。Start 后系统以事件请求下一批数据;游戏在 BeginUpdatingAudioObjects / EndUpdatingAudioObjects 之间写各对象缓冲与位置。空间渲染器将这些对象混合/渲染为当前输出设备支持的声音。游戏提供空间内容,平台完成输出渲染;仅成功查询容量不代表实际提交了对象。 + +微软示例建议等待事件设置合理超时,例如 100 ms,并在端点/渲染类型改变后尝试 Reset。这说明持续事件、资源失效及重建行为同样是接口契约的一部分。 + +## 实现对照 + +| 环节 | Windows 文档约定 | 当前 Wine | 本次证据 | +| --- | --- | --- | --- | +| 客户端、格式、容量 | 查询当前端点空间能力 | 返回支持,最大动态对象 31 | 游戏查询成功 | +| 流激活与对象 | 静态通道及动态对象,带事件 | COM 对象、PCM/元数据传输已实现 | 游戏请求 mask 0x1ffe、最多 31 动态对象;内部 44 通道 | +| 更新与渲染 | 事件唤醒,Begin → GetBuffer/位置 → End | CoreAudio Spatial Mixer、环形缓冲与事件转发 | 首批 Begin/End 成功;尚需原生错误证据 | +| 时钟与音量服务 | GetService 支持 IAudioClock、IAudioClock2、IAudioStreamVolume | 一律 E_NOTIMPL | 有实现缺口,但已捕获日志未显示游戏调用 | +| 特定流可用性 | IsSpatialAudioStreamAvailable 查询指定流 | E_NOTIMPL | 有实现缺口,已捕获日志未显示游戏调用 | +| 扩展对象流 | HRTF/Metadata 等各有独立接口与要求 | 尚未实现这些流接口 | 未证明游戏请求这些接口 | +| 端点变化与失效 | 事件/通知、停止/复位/重建 | 原生监听、失效事件、动态容量丢失通知 | 游戏大量重复激活;需要区分真实设备改变与渲染故障 | + +## 已隔离范围 + +同工具链对照 control.1 流畅;与空间版比较,1600 个 Wine 模块仅 CoreAudio Unix 模块与双架构 mmdevapi.dll 不同,图形模块及 wine/wineserver 相同。probeoff.1 保留新 CoreAudio,只拒绝空间客户端激活,用户确认画面流畅且声音正常;恢复支持的 trace.1 又卡顿/卡死。因此空间 API 成功激活后的路径是必要排查范围,已有证据不支持先改图形层。 + +trace2.1 的 256 条公共标记中,记录 16 次客户端创建、16 次空间流激活入口、15 次启动入口,均集中在同一游戏线程。未记录 GetService、QueryInterface、IsSpatialAudioStreamAvailable 或独立更新失败标记。更新成功只记录最初四条,是诊断版主动限流,不能据此断言后续停止更新。公共日志已耗尽,不能排除限额后的接口请求。 + +这种重复建流异常优先指向失效/重建循环或事件驱动的持续运行问题;目前还不是经过验证的根因。新增 native-trace.1 仅加入原生诊断,实时回调写原子错误值,事件线程输出错误/阶段,设备监听回调输出 selector,保留原始空间语义。 + +## 文档与源码 + +- [Microsoft:渲染空间音频对象与完整更新示例](https://learn.microsoft.com/en-us/windows/win32/coreaudio/render-spatial-sound-using-spatial-audio-objects) +- [Microsoft:GetService 必须提供的服务](https://learn.microsoft.com/en-us/windows/win32/api/spatialaudioclient/nf-spatialaudioclient-ispatialaudioobjectrenderstreambase-getservice) +- [Microsoft:BeginUpdatingAudioObjects](https://learn.microsoft.com/en-us/windows/win32/api/spatialaudioclient/nf-spatialaudioclient-ispatialaudioobjectrenderstreambase-beginupdatingaudioobjects) +- [Microsoft:IsSpatialAudioStreamAvailable](https://learn.microsoft.com/en-us/windows/win32/api/spatialaudioclient/nf-spatialaudioclient-ispatialaudioclient-isspatialaudiostreamavailable) + +源码构建树 dlls/mmdevapi/spatialaudio.c:GetService、IsSpatialAudioStreamAvailable、Start/Begin/End、失效通知。dlls/winecoreaudio.drv/coreaudio.c:schedule_spatial_positions、ca_spatial_render_cb、设备监听、unix_timer_loop。诊断补丁和游戏证据位于 work/full-runtime/spatial-trace2、spatial-native-trace。构建源文件在诊断构建后恢复,原实验包不变。 + +## 单点候选:Begin 返回了剩余槽位而非渲染容量 + +微软 BeginUpdatingAudioObjects 文档将 availableDynamicObjectCount 定义为本轮可渲染的动态对象数量。当前代码返回 max_dynamic_objects - allocated_dynamic_objects,游戏分配满 31 个对象后该值变为 0。此前测试也把满分配后的 0 固化为预期,不能独立证明 Windows 契约正确。 + +11.0.8-capacity.1 仅将 Begin 的动态数量改为 max_dynamic_objects;GetAvailableDynamicObjectCount 的分配余额及对象分配上限均不变,保留 trace2/native 诊断。修订对应测试断言为满分配时仍有渲染容量,不改变其余检查。 + +游戏日志确认 allocated=31、capacity=31、frames=512,32 条独立限流标记显示持续更新。目前该启动仅创建一个空间流,之前的重复建流现象消失;未记录原生失效/设备变化。这为容量语义导致重建循环提供强支持,但画面卡顿是否完全恢复仍待用户同场景确认,尚不宣布最终修复。 + +容量版 x64 空间测试执行 2998 项、0 失败、0 跳过、2 todo,48 个 Mach-O 包装审计通过。x86 测试在进入测试之前失败:新建独立测试 prefix 缺少 syswow64/kernel32.dll(c0000135),不能记为通过或解释为容量实现回归;需先修复测试 prefix 再补跑。 + +2026-10-10 用户确认容量单点对照在同一场景“画面流畅、操作和声音正常”。结合保留空间支持、只改变 Begin 动态数量语义、重复建流消失,可将本次卡顿/卡死归因于渲染容量被错误返回为未分配槽位数量。正式 0004 COM 补丁和 0006 测试已修订,source.lock.json 哈希更新,完整空间补丁组零 fuzz 重应用通过。其他缺失服务接口仍是实现后续工作,不是此次已验证原因。32 位独立测试 prefix 问题另行修复,当前只确认容量版 64 位完整测试通过。本结果不替代空间听感、设备拔插及长时压力验收。 + +## 服务补齐(2026-10-10) + +新增正式 0007 补丁:空间流 GetService 提供音频时钟、设备时钟和流音量,并保留空间流及失效状态;CoreAudio 设备位置查询实现端点帧时间线/QPC 关联。补上基础流可用性查询,未支持的流类型返回不可用。音量按渲染输入 transport 声道控制,实际 Windows 的空间流服务声道映射仍待参考机核对。HRTF/Metadata 流仍未实现,不由本次服务补齐推断其支持。 + +11.0.9-services.1 包含此前动态容量修复及本次服务实现,不含诊断日志插桩。双架构各 3090 项、0 失败、0 跳过、2 既有 todo;48 个 Mach-O 审计通过,更新后的补丁零 fuzz 应用且源码与实测构建源完全一致。原先 x86 测试环境问题已用显式 WoW64 独立 prefix 修复。随后用户确认服务版在 7.1.4(12 声道、48 kHz)输出的同一游戏场景中“画面流畅、操作和声音正常”;真实游戏短测通过,实体方向听感、设备拔插/睡眠恢复和长时压力仍待验收。 diff --git a/docs/validation/spatial-runtime-20261009.json b/docs/validation/spatial-runtime-20261009.json new file mode 100644 index 0000000..7df67b6 --- /dev/null +++ b/docs/validation/spatial-runtime-20261009.json @@ -0,0 +1,530 @@ +{ + "date": "2026-10-09", + "runtimeVersion": "11.0.3-spatial.2", + "runtimeArtifact": { + "name": "indie-wine-11.0.3-spatial.2-macos-x86_64.tar.xz", + "sha256": "b2a970c8484884130325e967f8bd230708374910add5fdc5ee52585d1d640474", + "size": 47004056 + }, + "applicationArtifact": { + "name": "Mac-Gaming-Uncle-spatial-test.zip", + "sha256": "56bf9f2cecdd7c2ed93d6611dcedf729d0e6334e3b935b6b639a3904957961b2" + }, + "packageAudit": { + "runtimeVersion": "11.0.3-spatial.2", + "machOCount": 38, + "dependencies": [ + "/System/Library/Frameworks/AVFoundation.framework/Versions/A/AVFoundation", + "/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit", + "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices", + "/System/Library/Frameworks/AudioToolbox.framework/Versions/A/AudioToolbox", + "/System/Library/Frameworks/AudioUnit.framework/Versions/A/AudioUnit", + "/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon", + "/System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa", + "/System/Library/Frameworks/CoreAudio.framework/Versions/A/CoreAudio", + "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation", + "/System/Library/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics", + "/System/Library/Frameworks/CoreHaptics.framework/Versions/A/CoreHaptics", + "/System/Library/Frameworks/CoreMIDI.framework/Versions/A/CoreMIDI", + "/System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices", + "/System/Library/Frameworks/CoreText.framework/Versions/A/CoreText", + "/System/Library/Frameworks/CoreVideo.framework/Versions/A/CoreVideo", + "/System/Library/Frameworks/DiskArbitration.framework/Versions/A/DiskArbitration", + "/System/Library/Frameworks/ForceFeedback.framework/Versions/A/ForceFeedback", + "/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation", + "/System/Library/Frameworks/GameController.framework/Versions/A/GameController", + "/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit", + "/System/Library/Frameworks/Metal.framework/Versions/A/Metal", + "/System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL", + "/System/Library/Frameworks/PCSC.framework/Versions/A/PCSC", + "/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore", + "/System/Library/Frameworks/Security.framework/Versions/A/Security", + "/System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration", + "/usr/lib/libSystem.B.dylib", + "/usr/lib/libobjc.A.dylib", + "/usr/lib/libresolv.9.dylib", + "/usr/lib/libz.1.dylib", + "@rpath/libgmp.10.dylib", + "@rpath/libhogweed.6.dylib", + "@rpath/libinotify.0.dylib", + "@rpath/libnettle.8.dylib", + "@rpath/ntdll.so", + "@rpath/win32u.so" + ], + "errors": [], + "passed": true + }, + "productImporterIntegration": "passed; isolated Chinese and whitespace paths; WineRuntimeProvider initialization and cmd verified", + "defaultOutput": "Device: Dolby_5.1.2 (id 145)\nTransport: virt\nTag 0; bitmap 0; descriptions 8\nChannel 0 label 1 flags 0x2 xyz [-30,0,1]\nChannel 1 label 2 flags 0x2 xyz [30,0,1]\nChannel 2 label 3 flags 0x2 xyz [0,0,1]\nChannel 3 label 4 flags 0 xyz [0,0,0]\nChannel 4 label 5 flags 0x2 xyz [-110,0,1]\nChannel 5 label 6 flags 0x2 xyz [110,0,1]\nChannel 6 label 49 flags 0x2 xyz [-90,45,1]\nChannel 7 label 51 flags 0x2 xyz [90,45,1]\nBuffers 1\nBuffer 0 channels 8\n", + "smokeResults": [ + { + "name": "wineboot", + "exit": 0, + "status": "passed", + "seconds": 16.89, + "summaries": [] + }, + { + "name": "cmd-x64", + "exit": 0, + "status": "passed", + "seconds": 4.65, + "summaries": [] + }, + { + "name": "cmd-x86", + "exit": 0, + "status": "passed", + "seconds": 4.61, + "summaries": [] + }, + { + "name": "indie-smoke-x64", + "exit": 0, + "status": "passed", + "seconds": 7.78, + "summaries": [] + }, + { + "name": "indie-smoke-x86", + "exit": 0, + "status": "passed", + "seconds": 7.77, + "summaries": [] + }, + { + "name": "indie-d3d11-fixture", + "exit": 0, + "status": "passed", + "seconds": 9.22, + "summaries": [] + }, + { + "name": "xinput", + "exit": 2, + "status": "no-controller-connected", + "seconds": 5.54, + "summaries": [] + }, + { + "name": "x86_64-spatialaudio", + "exit": 0, + "status": "passed", + "seconds": 7.18, + "summaries": [ + "0020:spatialaudio: 2998 tests executed (2 marked as todo, 0 as flaky, 0 failures), 0 skipped.\r" + ] + }, + { + "name": "x86_64-render", + "exit": 0, + "status": "passed", + "seconds": 56.39, + "summaries": [ + "0020:render: 4440 tests executed (177 marked as todo, 0 as flaky, 0 failures), 2 skipped.\r" + ] + }, + { + "name": "x86_64-mmdevenum", + "exit": 0, + "status": "passed", + "seconds": 4.92, + "summaries": [ + "0020:mmdevenum: 72 tests executed (0 marked as todo, 0 as flaky, 0 failures), 0 skipped.\r" + ] + }, + { + "name": "x86_64-propstore", + "exit": 0, + "status": "passed", + "seconds": 4.68, + "summaries": [ + "0020:propstore: 241 tests executed (14 marked as todo, 0 as flaky, 0 failures), 0 skipped.\r" + ] + }, + { + "name": "i386-spatialaudio", + "exit": 0, + "status": "passed", + "seconds": 6.73, + "summaries": [ + "00d0:spatialaudio: 2998 tests executed (2 marked as todo, 0 as flaky, 0 failures), 0 skipped.\r" + ] + } + ], + "pending": [ + "isolate and fix 11.0.3-spatial.2 Split Fiction freeze before re-enabling experimental runtime", + "real-game spatial audio validation after runtime regression is fixed", + "physical controller input", + "physical speaker direction", + "device change and sleep/wake", + "one-hour soak", + "reference toolchain reproduction", + "old macOS hardware validation", + "release signing and default metadata promotion" + ], + "d3dMetalIntegration": { + "status": "passed", + "version": "4.0b2", + "runtime": "11.0.3-spatial.2", + "durationSeconds": 27.018, + "fixtures": { + "d3d11": { + "exit": 0, + "frames": 120 + }, + "d3d12": { + "exit": 0, + "frames": 120 + } + }, + "loadedLibraries": [ + "imported renderer/external/libd3dshared.dylib", + "imported renderer/external/D3DMetal.framework/Versions/A/D3DMetal" + ], + "logs": "work/full-runtime/d3dmetal", + "warnings": [ + "Vulkan support was not built into this runtime", + "Apple Neural Engine Code 26; fixtures completed successfully" + ] + }, + "localSetup": { + "runtimeInstalled": true, + "gptkInstalled": "4.0b2", + "steam": "updated; official login required from user", + "gameRun": "Split Fiction normal with 11.0.2; failed with 11.0.3-spatial.2", + "activeRuntime": "11.0.3-control.1 (temporary diagnostic test)", + "experimentalRuntime": "preserved outside active runtimes" + }, + "swiftTests": { + "total": 98, + "failures": 0, + "skipped": 4, + "realRuntimeIntegration": "passed separately", + "d3dMetalIntegration": "passed separately" + }, + "splitFictionFirstRun": { + "status": "failed", + "userObservation": "severe low frame rate followed by freeze", + "steamStart": "2026-10-09 20:59:28", + "steamEnd": "2026-10-09 21:02:31", + "exitCode": 1, + "renderer": "d3dmetal", + "logWarning": "Apple Neural Engine Code 26; causality unconfirmed", + "settingsShownAfterRun": { + "metalFX": "on", + "metal4": "on", + "spatialAudioDiagnostics": true + }, + "baselineRetest": { + "metalFX": "off", + "metal4": "off", + "spatialAudioDiagnostics": false, + "result": "failed; user reports continued freeze" + } + }, + "splitFictionRuntimeComparison": { + "status": "baseline passed; experimental runtime regression", + "baselineRuntime": "11.0.2", + "experimentalRuntimeParked": "~/Library/Application Support/Indie/DisabledRuntimes/org.indie.wine11/11.0.3-spatial.2", + "settings": "MetalFX, Metal 4, spatial diagnostics off", + "sample": "work/full-runtime/split-fiction-first-run/game-hang-sample.txt", + "sampleInterpretation": "Wine/Rosetta syscall dispatch frames limit unwind; root cause unconfirmed", + "physicalFootprintGB": 2.2, + "userObservation": "11.0.2 runs normally without any reported issue", + "conclusion": "Failure isolated to experimental runtime/build differences; spatial audio patch causality not established" + }, + "spatialControlBuild": { + "runtimeVersion": "11.0.3-control.1", + "artifact": "dist/runtime/indie-wine-11.0.3-control.1-macos-x86_64.tar.xz", + "sha256": "2e76a52c24eea28b59257a8e4f224f8aa2eba6fded0a69955bb548f357cd385d", + "size": 52515392, + "packageAudit": { + "runtimeVersion": "11.0.3-control.1", + "machOCount": 38, + "dependencies": [ + "/System/Library/Frameworks/AVFoundation.framework/Versions/A/AVFoundation", + "/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit", + "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices", + "/System/Library/Frameworks/AudioToolbox.framework/Versions/A/AudioToolbox", + "/System/Library/Frameworks/AudioUnit.framework/Versions/A/AudioUnit", + "/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon", + "/System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa", + "/System/Library/Frameworks/CoreAudio.framework/Versions/A/CoreAudio", + "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation", + "/System/Library/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics", + "/System/Library/Frameworks/CoreHaptics.framework/Versions/A/CoreHaptics", + "/System/Library/Frameworks/CoreMIDI.framework/Versions/A/CoreMIDI", + "/System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices", + "/System/Library/Frameworks/CoreText.framework/Versions/A/CoreText", + "/System/Library/Frameworks/CoreVideo.framework/Versions/A/CoreVideo", + "/System/Library/Frameworks/DiskArbitration.framework/Versions/A/DiskArbitration", + "/System/Library/Frameworks/ForceFeedback.framework/Versions/A/ForceFeedback", + "/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation", + "/System/Library/Frameworks/GameController.framework/Versions/A/GameController", + "/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit", + "/System/Library/Frameworks/Metal.framework/Versions/A/Metal", + "/System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL", + "/System/Library/Frameworks/PCSC.framework/Versions/A/PCSC", + "/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore", + "/System/Library/Frameworks/Security.framework/Versions/A/Security", + "/System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration", + "/usr/lib/libSystem.B.dylib", + "/usr/lib/libobjc.A.dylib", + "/usr/lib/libresolv.9.dylib", + "/usr/lib/libz.1.dylib", + "@rpath/libgmp.10.dylib", + "@rpath/libhogweed.6.dylib", + "@rpath/libinotify.0.dylib", + "@rpath/libnettle.8.dylib", + "@rpath/ntdll.so", + "@rpath/win32u.so" + ], + "errors": [], + "passed": true + }, + "binaryDifferences": { + "checkedFiles": 1600, + "changed": [ + "lib/wine/x86_64-unix/winecoreaudio.so", + "lib/wine/i386-windows/mmdevapi.dll", + "lib/wine/x86_64-windows/mmdevapi.dll" + ] + }, + "integrationTests": { + "executed": 2, + "failures": 0 + }, + "smokeResults": [ + { + "name": "wineboot", + "exit": 0, + "status": "passed", + "seconds": 24.91, + "summaries": [] + }, + { + "name": "cmd-x64", + "exit": 0, + "status": "passed", + "seconds": 4.63, + "summaries": [] + }, + { + "name": "cmd-x86", + "exit": 0, + "status": "passed", + "seconds": 4.72, + "summaries": [] + }, + { + "name": "indie-smoke-x64", + "exit": 0, + "status": "passed", + "seconds": 7.83, + "summaries": [] + }, + { + "name": "indie-smoke-x86", + "exit": 0, + "status": "passed", + "seconds": 7.8, + "summaries": [] + }, + { + "name": "indie-d3d11-fixture", + "exit": 0, + "status": "passed", + "seconds": 8.97, + "summaries": [] + }, + { + "name": "xinput", + "exit": 0, + "status": "passed", + "seconds": 5.5, + "summaries": [] + } + ], + "gameStatus": "passed; user reports no problem and very smooth gameplay", + "installedToActiveRuntimes": true, + "gameLog": "4B858AB7-EB39-44E1-9749-71B32686F9B7-steam-d3dmetal.log", + "gameComparisonConclusion": "Same-build control removing spatial patches is smooth; regression isolated to audio patch group, individual cause still pending", + "installedBinaryVerification": { + "filesChecked": 1600, + "changed": [ + "lib/wine/x86_64-unix/winecoreaudio.so", + "lib/wine/i386-windows/mmdevapi.dll", + "lib/wine/x86_64-windows/mmdevapi.dll" + ], + "wineAndWineserverIdentical": true + } + }, + "spatialProbeGate": { + "version": "11.0.4-probeoff.1", + "baseline": "11.0.3-spatial.2", + "change": "SpatialAudioClient_Create returns E_NOINTERFACE and writes diagnostic marker; all other spatial implementation retained", + "binaryDifferences": [ + "lib/wine/i386-windows/mmdevapi.dll", + "lib/wine/x86_64-windows/mmdevapi.dll" + ], + "activationProbes": [ + { + "name": "wineboot", + "exit": 0 + }, + { + "name": "activation-x64", + "exit": 0 + }, + { + "name": "activation-x86", + "exit": 0 + } + ], + "ordinaryMixQuery": { + "channels": 8, + "rate": 48000, + "period100ns": 106667 + }, + "gameResult": "passed; user reports smooth picture and normal sound", + "notForRelease": true, + "gameLog": "242AECA5-6F26-4902-9EDC-D5C73DFACC4E-steam-d3dmetal.log", + "runtimeProcessConfirmed": true, + "activationMarkerObserved": true, + "conclusion": "Regression requires successful spatial activation or subsequent spatial API path; new ordinary audio implementation retained and normal in this test" + }, + "spatialTraceDiagnostic": { + "version": "11.0.5-trace.1", + "base": "11.0.3-spatial.2", + "change": "COM-only bounded markers (256 per process), spatial semantics retained", + "tests": [ + { + "name": "wineboot", + "exit": 0, + "summaries": [] + }, + { + "name": "spatial-x64", + "exit": 0, + "summaries": [ + "0020:spatialaudio: 2998 tests executed (2 marked as todo, 0 as flaky, 0 failures), 0 skipped.\r" + ] + }, + { + "name": "spatial-x86", + "exit": 0, + "summaries": [ + "00d8:spatialaudio: 2998 tests executed (2 marked as todo, 0 as flaky, 0 failures), 0 skipped.\r" + ] + } + ], + "gameResult": "failed; user reports renewed stutter/freeze", + "notForRelease": true, + "observations": { + "dynamicCapacity": 31, + "periodFrames": 512, + "rate": 48000, + "staticMask": "0x1ffe", + "requestedDynamic": "0..31", + "streamChannels": 44, + "clientActivation": "success", + "streamInitialization": "success", + "startAndInitialUpdates": "success", + "unimplementedInterfaceCause": "not established" + } + }, + "windowsComparisonDiagnostic": { + "document": "docs/WINDOWS_SPATIAL_AUDIO_COMPARISON.md", + "trace2RepeatedActivations": 16, + "nativeTraceErrorsObserved": 0, + "capacityVariant": "11.0.8-capacity.1", + "singleBehaviorChange": "BeginUpdatingAudioObjects returns render capacity instead of unallocated slots", + "gameLog": "6E5CDE03-00C5-4FA9-B1B2-DACD24E37509-steam-d3dmetal.log", + "capacityGameObserved": { + "allocated": 31, + "reportedCapacity": 31, + "frames": 512, + "streamCreations": 1 + }, + "gameplayConfirmation": "User confirmed same scene: smooth picture, controls and sound normal", + "x64Tests": { + "executed": 2998, + "failures": 0, + "skipped": 0, + "todo": 2 + }, + "x86Tests": { + "status": "blocked-by-test-prefix", + "reason": "Fresh test prefix missing syswow64/kernel32.dll; test exits c0000135 before execution; no implementation conclusion" + }, + "conclusion": "Begin render-capacity semantics causes repeated spatial stream recreation and observed stutter/freeze; single-value A/B restores normal gameplay", + "formalPatchStack": "Updated 0004 COM and 0006 tests; SHA256 refreshed; zero-fuzz reapply verified" + }, + "spatialServices": { + "date": "2026-10-10", + "runtime": "11.0.9-services.1", + "patch": "0007-spatial-audio-services.patch", + "services": [ + "IAudioClock", + "IAudioClock2", + "IAudioStreamVolume" + ], + "streamAvailability": "base object stream capability query; unsupported streams rejected", + "tests": [ + { + "name": "spatial-x64", + "exit": 0, + "summaries": [ + "0020:spatialaudio: 3090 tests executed (2 marked as todo, 0 as flaky, 0 failures), 0 skipped." + ] + }, + { + "name": "spatial-x86", + "exit": 0, + "summaries": [ + "011c:spatialaudio: 3090 tests executed (2 marked as todo, 0 as flaky, 0 failures), 0 skipped." + ] + } + ], + "packageAudit": { + "passed": true, + "machOCount": 48 + }, + "patchAppliedWithZeroFuzz": true, + "diagnosticInstrumentation": false, + "gameplayValidation": { + "date": "2026-10-10", + "game": "Split Fiction", + "runtime": "11.0.9-services.1", + "defaultOutputChannels": 12, + "defaultOutputRate": 48000, + "gamePID": 51291, + "wineServerPID": 51155, + "outputLog": "14CF7E0D-24AF-4874-B9D9-B73EB39C8260-steam-d3dmetal.log", + "status": "passed-user-confirmed-same-scene", + "note": "Existing Apple Neural Engine Code 26 observed; not independently causal for audio regression", + "userFeedback": "画面流畅、操作和声音正常", + "limitations": "Short same-scene gameplay acceptance; speaker direction listening, sleep/wake, device hotplug and long-duration soak remain unverified" + }, + "remainingConformance": "Windows reference device/volume mapping; non-default sample rates and physical device lifecycle", + "output714Validation": { + "date": "2026-10-10", + "deviceName": "Dolby_5.1.2", + "channels": 12, + "sampleRate": 48000, + "layout": "front L/R/C/LFE, side L/R, top rear L/R, rear L/R, top front L/R; preserved native order", + "runtime": "11.0.9-services.1", + "architecture": "x86_64", + "tests": 3090, + "failures": 0, + "skipped": 0, + "todo": 2, + "evidence": [ + "work/full-runtime/spatial-services/output-layout-7.1.4.txt", + "work/full-runtime/spatial-services/spatial-7.1.4-x64.log" + ], + "limitations": "API/renderer test pass; directional listening and physical downstream speaker routing not independently verified" + } + } +} diff --git a/patches/wine11/0004-spatial-audio-com.patch b/patches/wine11/0004-spatial-audio-com.patch new file mode 100644 index 0000000..990ed16 --- /dev/null +++ b/patches/wine11/0004-spatial-audio-com.patch @@ -0,0 +1,2483 @@ +From: jungwuk-ryu +Subject: [MGU] spatial audio com +Origin: https://github.com/jungwuk-ryu/switchyard-wine +Source-revision: ba57a08921dfe8f3a4281692b040cd2fa5acd94e +License: LGPL-2.1-or-later + +Backported to CodeWeavers CrossOver 26.3.0 FOSS sources. +Port adaptations retain CrossOver HALOutput and PE-owned timer threads. +Apply the complete ordered patch set; shared Unix ABI and all audio tables +must be updated together. See docs/SPATIAL_AUDIO.md for provenance. + +diff --git a/dlls/mmdevapi/client.c b/dlls/mmdevapi/client.c +index 4538eca..d29eb88 100644 +--- a/dlls/mmdevapi/client.c ++++ b/dlls/mmdevapi/client.c +@@ -110,7 +110,6 @@ static inline struct audio_client *impl_from_IAudioStreamVolume(IAudioStreamVolu + static HRESULT get_periods(struct audio_client *client, + REFERENCE_TIME *def_period, REFERENCE_TIME *min_period) + { +- static const REFERENCE_TIME min_def_period = 100000; /* 10 ms */ + struct get_device_period_params params; + + params.device = client->device_name; +@@ -120,8 +119,6 @@ static HRESULT get_periods(struct audio_client *client, + + wine_unix_call(get_device_period, ¶ms); + +- if (def_period) *def_period = max(*def_period, min_def_period); +- + return params.result; + } + +@@ -486,7 +483,12 @@ static HRESULT validate_wfx(const WAVEFORMATEX *fmt, AUDCLNT_SHAREMODE share_mod + static HRESULT stream_init(struct audio_client *client, const BOOLEAN force_def_period, + const AUDCLNT_SHAREMODE mode, const DWORD flags, + REFERENCE_TIME duration, REFERENCE_TIME period, +- const WAVEFORMATEX *fmt, const GUID *sessionguid) ++ const WAVEFORMATEX *fmt, const GUID *sessionguid, ++ BOOL spatial, UINT32 spatial_static_mask, ++ UINT32 spatial_dynamic_objects, ++ UINT32 spatial_endpoint_generation, ++ HANDLE spatial_invalidation_event, ++ BOOL spatial_fault_invalidate_on_start) + { + struct create_stream_params params; + UINT32 i, channel_count; +@@ -579,6 +581,13 @@ static HRESULT stream_init(struct audio_client *client, const BOOLEAN force_def_ + params.flow = client->dataflow; + params.share = mode; + params.flags = flags; ++ params.spatial = spatial; ++ params.spatial_static_mask = spatial_static_mask; ++ params.spatial_dynamic_objects = spatial_dynamic_objects; ++ params.spatial_endpoint_generation = spatial_endpoint_generation; ++ params.spatial_invalidation_event = spatial_invalidation_event; ++ params.spatial_fault_invalidate_on_start = ++ spatial_fault_invalidate_on_start; + params.duration = duration; + params.period = period; + params.fmt = fmt; +@@ -602,11 +611,28 @@ static HRESULT stream_init(struct audio_client *client, const BOOLEAN force_def_ + for (i = 0; i < channel_count; i++) + client->vols[i] = 1.f; + ++ /* CrossOver 26.3 uses a PE-owned timer thread rather than the newer ++ * PsCreateSystemThread helper. Start the spatial semaphore relay before ++ * publishing activation, including before the first client Start. Any ++ * callback before this point leaves a coalesced semaphore wake pending. */ ++ if (spatial) ++ { ++ client->stream = stream; ++ if (!(client->timer_thread = CreateThread(NULL, 0, timer_loop_func, client, 0, NULL))) ++ { ++ params.result = HRESULT_FROM_WIN32(GetLastError()); ++ goto exit; ++ } ++ SetThreadPriority(client->timer_thread, THREAD_PRIORITY_TIME_CRITICAL); ++ } ++ + params.result = get_audio_session(sessionguid, client->parent, channel_count, &client->session); + + exit: + if (FAILED(params.result)) { +- stream_release(stream, NULL); ++ stream_release(stream, client->timer_thread); ++ client->timer_thread = NULL; ++ client->stream = 0; + free(client->vols); + client->vols = NULL; + } else { +@@ -813,7 +839,8 @@ static HRESULT WINAPI client_Initialize(IAudioClient3 *iface, AUDCLNT_SHAREMODE + wine_dbgstr_longlong(period), fmt, + debugstr_guid(sessionguid)); + +- return stream_init(This, TRUE, mode, flags, duration, period, fmt, sessionguid); ++ return stream_init(This, TRUE, mode, flags, duration, period, fmt, sessionguid, ++ FALSE, 0, 0, 0, NULL, FALSE); + } + + static HRESULT WINAPI client_GetBufferSize(IAudioClient3 *iface, UINT32 *out) +@@ -1249,7 +1276,78 @@ static HRESULT WINAPI client_InitializeSharedAudioStream(IAudioClient3 *iface, D + + period = period_frames * (REFERENCE_TIME)10000000 / format->nSamplesPerSec; + +- return stream_init(This, FALSE, AUDCLNT_SHAREMODE_SHARED, flags, 0, period, format, session_guid); ++ return stream_init(This, FALSE, AUDCLNT_SHAREMODE_SHARED, flags, 0, period, format, ++ session_guid, FALSE, 0, 0, 0, NULL, FALSE); ++} ++ ++HRESULT audio_client_initialize_spatial(IAudioClient *iface, DWORD flags, ++ REFERENCE_TIME duration, REFERENCE_TIME period, const WAVEFORMATEX *format, ++ const GUID *session_guid, AudioObjectType static_object_mask, ++ UINT32 dynamic_object_count, UINT32 endpoint_generation, ++ HANDLE invalidation_event, BOOL fault_invalidate_on_start) ++{ ++ struct audio_client *client = impl_from_IAudioClient3((IAudioClient3 *)iface); ++ ++ if (client->dataflow != eRender) ++ return E_INVALIDARG; ++ ++ return stream_init(client, TRUE, AUDCLNT_SHAREMODE_SHARED, flags, duration, period, ++ format, session_guid, TRUE, static_object_mask, dynamic_object_count, ++ endpoint_generation, invalidation_event, ++ fault_invalidate_on_start); ++} ++ ++HRESULT audio_client_get_spatial_audio_capabilities(IMMDevice *iface, ++ struct spatial_audio_capabilities *capabilities) ++{ ++ struct get_spatial_audio_capabilities_params params; ++ MMDevice *device; ++ EDataFlow flow; ++ char *name; ++ ++ if (!iface || !capabilities) ++ return E_POINTER; ++ ++ memset(capabilities, 0, sizeof(*capabilities)); ++ device = CONTAINING_RECORD(iface, MMDevice, IMMDevice_iface); ++ if (!get_device_name_from_guid(&device->devguid, &name, &flow)) ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ if (flow != eRender) ++ { ++ free(name); ++ return AUDCLNT_E_WRONG_ENDPOINT_TYPE; ++ } ++ ++ params.device = name; ++ params.result = E_NOTIMPL; ++ memset(¶ms.capabilities, 0, sizeof(params.capabilities)); ++ wine_unix_call(get_spatial_audio_capabilities, ¶ms); ++ if (params.result == E_NOTIMPL) ++ { ++ struct get_device_period_params period_params; ++ REFERENCE_TIME period = 0; ++ ++ period_params.device = name; ++ period_params.flow = flow; ++ period_params.def_period = . ++ period_params.min_period = NULL; ++ period_params.result = E_NOTIMPL; ++ wine_unix_call(get_device_period, &period_params); ++ if (SUCCEEDED(period_params.result) && period > 0) ++ { ++ params.capabilities.sample_rate = 48000; ++ params.capabilities.period_frames = MulDiv(period, 48000, ++ 10000000); ++ params.result = params.capabilities.period_frames ? S_OK : E_FAIL; ++ } ++ else ++ params.result = period_params.result; ++ } ++ free(name); ++ ++ if (SUCCEEDED(params.result)) ++ *capabilities = params.capabilities; ++ return params.result; + } + + const IAudioClient3Vtbl AudioClient3_Vtbl = +@@ -1549,12 +1647,35 @@ static HRESULT WINAPI render_ReleaseBuffer(IAudioRenderClient *iface, UINT32 wri + params.stream = This->stream; + params.written_frames = written_frames; + params.flags = flags; ++ params.spatial_objects = NULL; ++ params.spatial_object_count = 0; + + wine_unix_call(release_render_buffer, ¶ms); + + return params.result; + } + ++HRESULT audio_client_release_spatial_buffer(IAudioClient *iface, ++ UINT32 written_frames, DWORD flags, ++ const struct spatial_audio_object_state *objects, UINT32 object_count) ++{ ++ struct audio_client *client = impl_from_IAudioClient3((IAudioClient3 *)iface); ++ struct release_render_buffer_params params; ++ ++ if (!client->stream) ++ return AUDCLNT_E_NOT_INITIALIZED; ++ if (object_count && !objects) ++ return E_POINTER; ++ ++ params.stream = client->stream; ++ params.written_frames = written_frames; ++ params.flags = flags; ++ params.spatial_objects = objects; ++ params.spatial_object_count = object_count; ++ wine_unix_call(release_render_buffer, ¶ms); ++ return params.result; ++} ++ + const IAudioRenderClientVtbl AudioRenderClient_Vtbl = { + render_QueryInterface, + render_AddRef, +diff --git a/dlls/mmdevapi/mmdevapi_private.h b/dlls/mmdevapi/mmdevapi_private.h +index 672d901..0b163cf 100644 +--- a/dlls/mmdevapi/mmdevapi_private.h ++++ b/dlls/mmdevapi/mmdevapi_private.h +@@ -121,6 +121,16 @@ static inline void wine_unix_call(const unsigned int code, void *args) + } + + extern HRESULT AudioClient_Create(GUID *guid, IMMDevice *device, IAudioClient **out); ++extern HRESULT audio_client_initialize_spatial(IAudioClient *client, DWORD flags, ++ REFERENCE_TIME duration, REFERENCE_TIME period, const WAVEFORMATEX *format, ++ const GUID *session_guid, AudioObjectType static_object_mask, ++ UINT32 dynamic_object_count, UINT32 endpoint_generation, ++ HANDLE invalidation_event, BOOL fault_invalidate_on_start); ++extern HRESULT audio_client_get_spatial_audio_capabilities(IMMDevice *device, ++ struct spatial_audio_capabilities *capabilities); ++extern HRESULT audio_client_release_spatial_buffer(IAudioClient *client, ++ UINT32 written_frames, DWORD flags, ++ const struct spatial_audio_object_state *objects, UINT32 object_count); + extern HRESULT AudioEndpointVolume_Create(MMDevice *parent, IAudioEndpointVolumeEx **ppv); + extern HRESULT AudioSessionManager_Create(IMMDevice *device, IAudioSessionManager2 **ppv); + extern HRESULT SpatialAudioClient_Create(IMMDevice *device, ISpatialAudioClient **out); +diff --git a/dlls/mmdevapi/spatialaudio.c b/dlls/mmdevapi/spatialaudio.c +index 8ae37cb..edb4d62 100644 +--- a/dlls/mmdevapi/spatialaudio.c ++++ b/dlls/mmdevapi/spatialaudio.c +@@ -18,6 +18,9 @@ + + #define COBJMACROS + ++#include ++#include ++#include + #include + + #include "windef.h" +@@ -39,6 +42,44 @@ + + WINE_DEFAULT_DEBUG_CHANNEL(mmdevapi); + ++#define NATIVE_STATIC_OBJECT_MASK SPATIAL_AUDIO_STATIC_OBJECT_MASK ++ ++struct static_object_desc ++{ ++ AudioObjectType type; ++ DWORD speaker; ++ float x, y, z; ++}; ++ ++/* Positions use the listener-relative, right-handed coordinate system documented ++ * by ISpatialAudioClient. The exact distance is renderer-defined; keep every ++ * directional speaker on a one-metre sphere and the non-directional LFE at the ++ * listener origin. */ ++static const struct static_object_desc static_objects[] = ++{ ++ {AudioObjectType_FrontLeft, SPEAKER_FRONT_LEFT, -0.5f, 0.0f, -0.8660254f}, ++ {AudioObjectType_FrontRight, SPEAKER_FRONT_RIGHT, 0.5f, 0.0f, -0.8660254f}, ++ {AudioObjectType_FrontCenter, SPEAKER_FRONT_CENTER, 0.0f, 0.0f, -1.0f}, ++ {AudioObjectType_LowFrequency, SPEAKER_LOW_FREQUENCY, 0.0f, 0.0f, 0.0f}, ++ {AudioObjectType_SideLeft, SPEAKER_SIDE_LEFT, -1.0f, 0.0f, 0.0f}, ++ {AudioObjectType_SideRight, SPEAKER_SIDE_RIGHT, 1.0f, 0.0f, 0.0f}, ++ {AudioObjectType_BackLeft, SPEAKER_BACK_LEFT, -0.5f, 0.0f, 0.8660254f}, ++ {AudioObjectType_BackRight, SPEAKER_BACK_RIGHT, 0.5f, 0.0f, 0.8660254f}, ++ {AudioObjectType_TopFrontLeft, SPEAKER_TOP_FRONT_LEFT, -0.3535534f, 0.7071068f, -0.6123724f}, ++ {AudioObjectType_TopFrontRight, SPEAKER_TOP_FRONT_RIGHT, 0.3535534f, 0.7071068f, -0.6123724f}, ++ {AudioObjectType_TopBackLeft, SPEAKER_TOP_BACK_LEFT, -0.3535534f, 0.7071068f, 0.6123724f}, ++ {AudioObjectType_TopBackRight, SPEAKER_TOP_BACK_RIGHT, 0.3535534f, 0.7071068f, 0.6123724f}, ++ {AudioObjectType_BottomFrontLeft, SPATIAL_AUDIO_BOTTOM_FRONT_LEFT_SPEAKER, ++ -0.3535534f, -0.7071068f, -0.6123724f}, ++ {AudioObjectType_BottomFrontRight, SPATIAL_AUDIO_BOTTOM_FRONT_RIGHT_SPEAKER, ++ 0.3535534f, -0.7071068f, -0.6123724f}, ++ {AudioObjectType_BottomBackLeft, SPATIAL_AUDIO_BOTTOM_BACK_LEFT_SPEAKER, ++ -0.3535534f, -0.7071068f, 0.6123724f}, ++ {AudioObjectType_BottomBackRight, SPATIAL_AUDIO_BOTTOM_BACK_RIGHT_SPEAKER, ++ 0.3535534f, -0.7071068f, 0.6123724f}, ++ {AudioObjectType_BackCenter, SPEAKER_BACK_CENTER, 0.0f, 0.0f, 1.0f}, ++}; ++ + static UINT32 AudioObjectType_to_index(AudioObjectType type) + { + UINT32 o = 0; +@@ -79,6 +120,32 @@ static BOOL formats_equal(const WAVEFORMATEX *fmt1, const WAVEFORMATEX *fmt2) + return !memcmp(fmt1, fmt2, sizeof(*fmt1)) && !memcmp(fmt1 + 1, fmt2 + 1, fmt1->cbSize); + } + ++static HRESULT spatial_period_for_format(const struct spatial_audio_capabilities *capabilities, ++ DWORD sample_rate, REFERENCE_TIME *period, UINT32 *frames) ++{ ++ UINT64 period_value, frame_value; ++ ++ if (!capabilities->sample_rate || !capabilities->period_frames || !sample_rate) ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ ++ period_value = (UINT64)capabilities->period_frames * 10000000; ++ period_value = (period_value + capabilities->sample_rate / 2) / ++ capabilities->sample_rate; ++ if (!period_value || period_value > INT_MAX || ++ period_value > (~(UINT64)0 - 5000000) / sample_rate) ++ return E_INVALIDARG; ++ ++ frame_value = (period_value * sample_rate + 5000000) / 10000000; ++ if (!frame_value || frame_value > ~0u) ++ return E_INVALIDARG; ++ ++ if (period) ++ *period = period_value; ++ if (frames) ++ *frames = frame_value; ++ return S_OK; ++} ++ + typedef struct SpatialAudioImpl SpatialAudioImpl; + typedef struct SpatialAudioStreamImpl SpatialAudioStreamImpl; + typedef struct SpatialAudioObjectImpl SpatialAudioObjectImpl; +@@ -89,9 +156,17 @@ struct SpatialAudioObjectImpl { + + SpatialAudioStreamImpl *sa_stream; + AudioObjectType type; +- UINT32 static_idx; + + float *buf; ++ float x, y, z; ++ float volume; ++ UINT32 dynamic_slot; ++ UINT32 end_of_stream_frames; ++ BOOL active; ++ BOOL started; ++ BOOL got_buffer; ++ BOOL end_of_stream; ++ BOOL released; + + struct list entry; + }; +@@ -108,11 +183,30 @@ struct SpatialAudioStreamImpl { + IAudioRenderClient *render; + + UINT32 period_frames, update_frames; ++ UINT32 max_dynamic_objects; ++ UINT32 allocated_dynamic_objects; ++ HRESULT invalidation_hr; ++ BOOL invalidation_notified; ++ BOOL invalidation_armed; ++ HANDLE invalidation_event; ++ HANDLE invalidation_ready_event; ++ HANDLE invalidation_start_event; ++ HANDLE invalidation_thread; ++ DWORD invalidation_thread_id; ++ LONG invalidation_thread_quit; ++ BOOL fault_invalidate_on_start; ++ BOOL fault_invalidate_before_start; ++ HRESULT invalidation_thread_hr; ++ struct spatial_audio_capabilities capabilities; + WAVEFORMATEXTENSIBLE stream_fmtex; + + float *buf; + ++ UINT32 dry_channel; ++ UINT32 dynamic_channel_base; + UINT32 static_object_map[17]; ++ SpatialAudioObjectImpl **dynamic_slots; ++ struct spatial_audio_object_state *dynamic_states; + + struct list objects; + }; +@@ -145,6 +239,140 @@ static inline SpatialAudioImpl *impl_from_IAudioFormatEnumerator(IAudioFormatEnu + return CONTAINING_RECORD(iface, SpatialAudioImpl, IAudioFormatEnumerator_iface); + } + ++static BOOL is_endpoint_resource_loss(HRESULT hr) ++{ ++ return hr == AUDCLNT_E_DEVICE_INVALIDATED || ++ hr == AUDCLNT_E_RESOURCES_INVALIDATED || ++ hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED; ++} ++ ++/* Caller holds stream->lock. Object interfaces stay allocated until their ++ * owners release them, but no object may remain renderable after the endpoint ++ * or one of its graph resources disappears. */ ++static BOOL revoke_stream_objects_locked(SpatialAudioStreamImpl *stream, ++ HRESULT hr, BOOL allow_notify) ++{ ++ SpatialAudioObjectImpl *object; ++ BOOL notify = FALSE; ++ ++ if (is_endpoint_resource_loss(hr) && SUCCEEDED(stream->invalidation_hr)) ++ { ++ /* The transport may report an AUDCLNT_* endpoint error, but object ++ * methods expose the spatial-audio contract after revocation. */ ++ stream->invalidation_hr = SPTLAUDCLNT_E_RESOURCES_INVALIDATED; ++ } ++ if (allow_notify && stream->invalidation_armed && ++ FAILED(stream->invalidation_hr) && ++ stream->max_dynamic_objects && stream->params.NotifyObject && ++ !stream->invalidation_notified) ++ { ++ stream->invalidation_notified = TRUE; ++ notify = TRUE; ++ } ++ ++ LIST_FOR_EACH_ENTRY(object, &stream->objects, SpatialAudioObjectImpl, entry) ++ { ++ object->active = FALSE; ++ object->got_buffer = FALSE; ++ object->end_of_stream = FALSE; ++ } ++ if (stream->max_dynamic_objects) ++ memset(stream->dynamic_states, 0, stream->max_dynamic_objects * ++ sizeof(*stream->dynamic_states)); ++ return notify; ++} ++ ++static void notify_dynamic_capacity_lost(SpatialAudioStreamImpl *stream) ++{ ++ ISpatialAudioObjectRenderStreamNotify *notify = stream->params.NotifyObject; ++ HRESULT hr; ++ ++ /* Endpoint loss is immediate. Invoke application code without the stream ++ * lock so a callback may query the stream without deadlocking. Hold local ++ * references because callback code is allowed to release its stream and ++ * notification references reentrantly. */ ++ ISpatialAudioObjectRenderStream_AddRef(&stream->ISpatialAudioObjectRenderStream_iface); ++ ISpatialAudioObjectRenderStreamNotify_AddRef(notify); ++ hr = ISpatialAudioObjectRenderStreamNotify_OnAvailableDynamicObjectCountChange( ++ notify, ++ (ISpatialAudioObjectRenderStreamBase *)&stream->ISpatialAudioObjectRenderStream_iface, ++ 0, 0); ++ if (FAILED(hr)) ++ WARN("Dynamic-capacity notification failed: %08lx.\n", hr); ++ ISpatialAudioObjectRenderStreamNotify_Release(notify); ++ ISpatialAudioObjectRenderStream_Release(&stream->ISpatialAudioObjectRenderStream_iface); ++} ++ ++static void revoke_stream_objects(SpatialAudioStreamImpl *stream, HRESULT hr) ++{ ++ BOOL notify; ++ ++ if (!is_endpoint_resource_loss(hr)) ++ return; ++ ++ EnterCriticalSection(&stream->lock); ++ notify = revoke_stream_objects_locked(stream, hr, TRUE); ++ LeaveCriticalSection(&stream->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(stream); ++} ++ ++/* Caller holds stream->lock. The auto-reset event is the authoritative bridge ++ * for endpoint loss before the notification worker is armed. Public methods ++ * consume it so stale capacity and objects are never observable; application ++ * callbacks remain suppressed until Start publishes invalidation_armed. */ ++static BOOL poll_stream_invalidation_locked(SpatialAudioStreamImpl *stream) ++{ ++ if (SUCCEEDED(stream->invalidation_hr) && stream->invalidation_event && ++ WaitForSingleObject(stream->invalidation_event, 0) == WAIT_OBJECT_0) ++ return revoke_stream_objects_locked(stream, ++ SPTLAUDCLNT_E_RESOURCES_INVALIDATED, ++ stream->invalidation_armed); ++ return FALSE; ++} ++ ++static BOOL spatial_stream_try_addref(SpatialAudioStreamImpl *stream) ++{ ++ LONG ref = InterlockedCompareExchange(&stream->ref, 0, 0); ++ ++ while (ref > 0 && ref < LONG_MAX) ++ { ++ LONG previous = InterlockedCompareExchange(&stream->ref, ref + 1, ref); ++ ++ if (previous == ref) ++ return TRUE; ++ ref = previous; ++ } ++ return FALSE; ++} ++ ++static DWORD WINAPI spatial_invalidation_thread(void *arg) ++{ ++ SpatialAudioStreamImpl *stream = arg; ++ HRESULT hr; ++ ++ hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); ++ stream->invalidation_thread_hr = hr; ++ SetEvent(stream->invalidation_ready_event); ++ if (FAILED(hr)) ++ { ++ WARN("Failed to initialize the spatial invalidation MTA: %08lx.\n", hr); ++ return 0; ++ } ++ if (WaitForSingleObject(stream->invalidation_start_event, INFINITE) == WAIT_OBJECT_0 && ++ !InterlockedCompareExchange(&stream->invalidation_thread_quit, 0, 0) && ++ WaitForSingleObject(stream->invalidation_event, INFINITE) == WAIT_OBJECT_0 && ++ !InterlockedCompareExchange(&stream->invalidation_thread_quit, 0, 0) && ++ spatial_stream_try_addref(stream)) ++ { ++ revoke_stream_objects(stream, SPTLAUDCLNT_E_RESOURCES_INVALIDATED); ++ ISpatialAudioObjectRenderStream_Release( ++ &stream->ISpatialAudioObjectRenderStream_iface); ++ } ++ CoUninitialize(); ++ return 0; ++} ++ + static HRESULT WINAPI SAO_QueryInterface(ISpatialAudioObject *iface, + REFIID riid, void **ppv) + { +@@ -181,16 +409,42 @@ static ULONG WINAPI SAO_AddRef(ISpatialAudioObject *iface) + static ULONG WINAPI SAO_Release(ISpatialAudioObject *iface) + { + SpatialAudioObjectImpl *This = impl_from_ISpatialAudioObject(iface); ++ SpatialAudioStreamImpl *stream = This->sa_stream; + ULONG ref = InterlockedDecrement(&This->ref); ++ BOOL deferred = FALSE; ++ + TRACE("(%p) new ref %lu\n", This, ref); +- if(!ref){ +- EnterCriticalSection(&This->sa_stream->lock); +- list_remove(&This->entry); +- LeaveCriticalSection(&This->sa_stream->lock); ++ if (!ref) ++ { ++ EnterCriticalSection(&stream->lock); ++ if (stream->update_frames != ~0u) ++ { ++ /* Keep the object's final buffer alive until EndUpdatingAudioObjects(). ++ * The object no longer owns its stream reference; a stream destroyed ++ * before that call will discard the pending object itself. */ ++ This->released = TRUE; ++ deferred = TRUE; ++ } ++ else ++ { ++ list_remove(&This->entry); ++ if (This->type == AudioObjectType_Dynamic) ++ { ++ assert(This->dynamic_slot < stream->max_dynamic_objects); ++ assert(stream->dynamic_slots[This->dynamic_slot] == This); ++ stream->dynamic_slots[This->dynamic_slot] = NULL; ++ assert(stream->allocated_dynamic_objects); ++ --stream->allocated_dynamic_objects; ++ } ++ } ++ LeaveCriticalSection(&stream->lock); + +- ISpatialAudioObjectRenderStream_Release(&This->sa_stream->ISpatialAudioObjectRenderStream_iface); +- free(This->buf); +- free(This); ++ if (!deferred) ++ { ++ free(This->buf); ++ free(This); ++ } ++ ISpatialAudioObjectRenderStream_Release(&stream->ISpatialAudioObjectRenderStream_iface); + } + return ref; + } +@@ -199,37 +453,91 @@ static HRESULT WINAPI SAO_GetBuffer(ISpatialAudioObject *iface, + BYTE **buffer, UINT32 *bytes) + { + SpatialAudioObjectImpl *This = impl_from_ISpatialAudioObject(iface); ++ BOOL notify; ++ HRESULT hr = S_OK; + + TRACE("(%p)->(%p, %p)\n", This, buffer, bytes); + ++ if (!buffer || !bytes) ++ return E_POINTER; ++ + EnterCriticalSection(&This->sa_stream->lock); + +- if(This->sa_stream->update_frames == ~0){ +- LeaveCriticalSection(&This->sa_stream->lock); +- return SPTLAUDCLNT_E_OUT_OF_ORDER; ++ notify = poll_stream_invalidation_locked(This->sa_stream); ++ if (FAILED(This->sa_stream->invalidation_hr)) ++ hr = This->sa_stream->invalidation_hr; ++ else if (This->sa_stream->update_frames == ~0) ++ hr = SPTLAUDCLNT_E_OUT_OF_ORDER; ++ else if (!This->active) ++ hr = SPTLAUDCLNT_E_RESOURCES_INVALIDATED; ++ else ++ { ++ *buffer = (BYTE *)This->buf; ++ *bytes = This->sa_stream->update_frames * ++ This->sa_stream->sa_client->object_fmtex.Format.nBlockAlign; ++ This->got_buffer = TRUE; ++ This->started = TRUE; + } + +- *buffer = (BYTE *)This->buf; +- *bytes = This->sa_stream->update_frames * +- This->sa_stream->sa_client->object_fmtex.Format.nBlockAlign; +- + LeaveCriticalSection(&This->sa_stream->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This->sa_stream); + +- return S_OK; ++ return hr; + } + + static HRESULT WINAPI SAO_SetEndOfStream(ISpatialAudioObject *iface, UINT32 frames) + { + SpatialAudioObjectImpl *This = impl_from_ISpatialAudioObject(iface); +- FIXME("(%p)->(%u)\n", This, frames); +- return E_NOTIMPL; ++ BOOL notify; ++ HRESULT hr = S_OK; ++ ++ TRACE("(%p)->(%u)\n", This, frames); ++ ++ EnterCriticalSection(&This->sa_stream->lock); ++ ++ notify = poll_stream_invalidation_locked(This->sa_stream); ++ if (FAILED(This->sa_stream->invalidation_hr)) ++ hr = This->sa_stream->invalidation_hr; ++ else if (This->sa_stream->update_frames == ~0) ++ hr = SPTLAUDCLNT_E_OUT_OF_ORDER; ++ else if (!This->active) ++ hr = SPTLAUDCLNT_E_RESOURCES_INVALIDATED; ++ else if (frames > This->sa_stream->update_frames) ++ hr = E_INVALIDARG; ++ else ++ { ++ This->got_buffer = TRUE; ++ This->started = TRUE; ++ This->end_of_stream = TRUE; ++ This->end_of_stream_frames = frames; ++ This->active = FALSE; ++ } ++ ++ LeaveCriticalSection(&This->sa_stream->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This->sa_stream); ++ return hr; + } + + static HRESULT WINAPI SAO_IsActive(ISpatialAudioObject *iface, BOOL *active) + { + SpatialAudioObjectImpl *This = impl_from_ISpatialAudioObject(iface); +- FIXME("(%p)->(%p)\n", This, active); +- return E_NOTIMPL; ++ BOOL notify; ++ ++ TRACE("(%p)->(%p)\n", This, active); ++ ++ if (!active) ++ return E_POINTER; ++ ++ EnterCriticalSection(&This->sa_stream->lock); ++ notify = poll_stream_invalidation_locked(This->sa_stream); ++ *active = This->active; ++ LeaveCriticalSection(&This->sa_stream->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This->sa_stream); ++ ++ return S_OK; + } + + static HRESULT WINAPI SAO_GetAudioObjectType(ISpatialAudioObject *iface, +@@ -239,6 +547,9 @@ static HRESULT WINAPI SAO_GetAudioObjectType(ISpatialAudioObject *iface, + + TRACE("(%p)->(%p)\n", This, type); + ++ if (!type) ++ return E_POINTER; ++ + *type = This->type; + + return S_OK; +@@ -248,15 +559,61 @@ static HRESULT WINAPI SAO_SetPosition(ISpatialAudioObject *iface, float x, + float y, float z) + { + SpatialAudioObjectImpl *This = impl_from_ISpatialAudioObject(iface); +- FIXME("(%p)->(%f, %f, %f)\n", This, x, y, z); +- return E_NOTIMPL; ++ BOOL notify; ++ HRESULT hr = S_OK; ++ ++ TRACE("(%p)->(%f, %f, %f)\n", This, x, y, z); ++ ++ EnterCriticalSection(&This->sa_stream->lock); ++ notify = poll_stream_invalidation_locked(This->sa_stream); ++ if (FAILED(This->sa_stream->invalidation_hr)) ++ hr = This->sa_stream->invalidation_hr; ++ else if (This->sa_stream->update_frames == ~0) ++ hr = SPTLAUDCLNT_E_OUT_OF_ORDER; ++ else if (!This->active) ++ hr = SPTLAUDCLNT_E_RESOURCES_INVALIDATED; ++ else if (This->type != AudioObjectType_Dynamic) ++ hr = SPTLAUDCLNT_E_PROPERTY_NOT_SUPPORTED; ++ else if (!isfinite(x) || !isfinite(y) || !isfinite(z)) ++ hr = E_INVALIDARG; ++ else ++ { ++ This->x = x; ++ This->y = y; ++ This->z = z; ++ } ++ LeaveCriticalSection(&This->sa_stream->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This->sa_stream); ++ ++ return hr; + } + + static HRESULT WINAPI SAO_SetVolume(ISpatialAudioObject *iface, float vol) + { + SpatialAudioObjectImpl *This = impl_from_ISpatialAudioObject(iface); +- FIXME("(%p)->(%f)\n", This, vol); +- return E_NOTIMPL; ++ BOOL notify; ++ HRESULT hr = S_OK; ++ ++ TRACE("(%p)->(%f)\n", This, vol); ++ ++ EnterCriticalSection(&This->sa_stream->lock); ++ notify = poll_stream_invalidation_locked(This->sa_stream); ++ if (FAILED(This->sa_stream->invalidation_hr)) ++ hr = This->sa_stream->invalidation_hr; ++ else if (This->sa_stream->update_frames == ~0) ++ hr = SPTLAUDCLNT_E_OUT_OF_ORDER; ++ else if (!This->active) ++ hr = SPTLAUDCLNT_E_RESOURCES_INVALIDATED; ++ else if (!(vol >= 0.0f && vol <= 1.0f)) ++ hr = E_INVALIDARG; ++ else ++ This->volume = vol; ++ LeaveCriticalSection(&This->sa_stream->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This->sa_stream); ++ ++ return hr; + } + + static ISpatialAudioObjectVtbl ISpatialAudioObject_vtbl = { +@@ -307,17 +664,54 @@ static ULONG WINAPI SAORS_AddRef(ISpatialAudioObjectRenderStream *iface) + static ULONG WINAPI SAORS_Release(ISpatialAudioObjectRenderStream *iface) + { + SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); ++ SpatialAudioObjectImpl *object, *object2; + ULONG ref = InterlockedDecrement(&This->ref); ++ + TRACE("(%p) new ref %lu\n", This, ref); +- if(!ref){ ++ if (!ref) ++ { ++ if (This->invalidation_thread) ++ { ++ InterlockedExchange(&This->invalidation_thread_quit, 1); ++ SetEvent(This->invalidation_start_event); ++ SetEvent(This->invalidation_event); ++ if (GetCurrentThreadId() != This->invalidation_thread_id) ++ WaitForSingleObject(This->invalidation_thread, INFINITE); ++ CloseHandle(This->invalidation_thread); ++ } + IAudioClient_Stop(This->client); +- if(This->update_frames != ~0 && This->update_frames > 0) +- IAudioRenderClient_ReleaseBuffer(This->render, This->update_frames, 0); ++ if (This->update_frames != ~0u && This->update_frames > 0) ++ { ++ if (This->max_dynamic_objects) ++ audio_client_release_spatial_buffer(This->client, This->update_frames, 0, ++ This->dynamic_states, This->max_dynamic_objects); ++ else ++ IAudioRenderClient_ReleaseBuffer(This->render, This->update_frames, 0); ++ } + IAudioRenderClient_Release(This->render); + IAudioClient_Release(This->client); +- if(This->params.NotifyObject) ++ if (This->invalidation_event) ++ CloseHandle(This->invalidation_event); ++ if (This->invalidation_ready_event) ++ CloseHandle(This->invalidation_ready_event); ++ if (This->invalidation_start_event) ++ CloseHandle(This->invalidation_start_event); ++ if (This->params.NotifyObject) + ISpatialAudioObjectRenderStreamNotify_Release(This->params.NotifyObject); +- free((void*)This->params.ObjectFormat); ++ ++ LIST_FOR_EACH_ENTRY_SAFE(object, object2, &This->objects, SpatialAudioObjectImpl, entry) ++ { ++ /* Live objects hold a stream reference, so only objects whose final ++ * Release happened during an update can remain here. */ ++ assert(object->released); ++ list_remove(&object->entry); ++ free(object->buf); ++ free(object); ++ } ++ ++ free(This->dynamic_states); ++ free(This->dynamic_slots); ++ free((void *)This->params.ObjectFormat); + CloseHandle(This->params.EventHandle); + DeleteCriticalSection(&This->lock); + ISpatialAudioClient_Release(&This->sa_client->ISpatialAudioClient_iface); +@@ -330,9 +724,29 @@ static HRESULT WINAPI SAORS_GetAvailableDynamicObjectCount( + ISpatialAudioObjectRenderStream *iface, UINT32 *count) + { + SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); +- FIXME("(%p)->(%p)\n", This, count); ++ BOOL notify; ++ HRESULT hr; + +- *count = 0; ++ TRACE("(%p)->(%p)\n", This, count); ++ ++ if (!count) ++ return E_POINTER; ++ ++ EnterCriticalSection(&This->lock); ++ notify = poll_stream_invalidation_locked(This); ++ if (FAILED(This->invalidation_hr)) ++ { ++ hr = This->invalidation_hr; ++ ++ *count = 0; ++ LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ return hr; ++ } ++ assert(This->allocated_dynamic_objects <= This->max_dynamic_objects); ++ *count = This->max_dynamic_objects - This->allocated_dynamic_objects; ++ LeaveCriticalSection(&This->lock); + return S_OK; + } + +@@ -341,35 +755,123 @@ static HRESULT WINAPI SAORS_GetService(ISpatialAudioObjectRenderStream *iface, + { + SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); + FIXME("(%p)->(%s, %p)\n", This, debugstr_guid(riid), service); ++ ++ if (!service) ++ return E_POINTER; ++ ++ *service = NULL; + return E_NOTIMPL; + } + + static HRESULT WINAPI SAORS_Start(ISpatialAudioObjectRenderStream *iface) + { + SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); ++ BOOL notify; + HRESULT hr; + + TRACE("(%p)->()\n", This); + ++ SAORS_AddRef(iface); ++ EnterCriticalSection(&This->lock); ++ notify = poll_stream_invalidation_locked(This); ++ hr = This->invalidation_hr; ++ if (FAILED(hr)) ++ { ++ /* A Start attempt is the publication boundary for endpoint loss that ++ * was recorded before playback could begin. */ ++ This->invalidation_armed = TRUE; ++ notify |= revoke_stream_objects_locked(This, hr, TRUE); ++ } ++ LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ if (FAILED(hr)) ++ { ++ SAORS_Release(iface); ++ return hr; ++ } ++ + hr = IAudioClient_Start(This->client); ++ if (hr == AUDCLNT_E_NOT_STOPPED) ++ { ++ SAORS_Release(iface); ++ return SPTLAUDCLNT_E_STREAM_NOT_STOPPED; ++ } + if(FAILED(hr)){ + WARN("IAudioClient::Start failed: %08lx\n", hr); ++ if (is_endpoint_resource_loss(hr)) ++ { ++ /* A backend can observe the sticky loss before its event relay ++ * runs. Treat that resource failure as the same Start boundary ++ * as a pre-polled event, while leaving unrelated Start failures ++ * unarmed. */ ++ EnterCriticalSection(&This->lock); ++ This->invalidation_armed = TRUE; ++ notify = revoke_stream_objects_locked(This, hr, TRUE); ++ LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ } ++ SAORS_Release(iface); ++ return hr; ++ } ++ ++ /* Do not expose callbacks while IAudioClient::Start is in progress. A ++ * concurrent public call may record the event, but only this successful ++ * Start publishes the armed state and turns that record into a callback. */ ++ EnterCriticalSection(&This->lock); ++ notify = poll_stream_invalidation_locked(This); ++ This->invalidation_armed = TRUE; ++ hr = This->invalidation_hr; ++ if (FAILED(hr)) ++ notify |= revoke_stream_objects_locked(This, hr, TRUE); ++ LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ if (FAILED(hr)) ++ { ++ IAudioClient_Stop(This->client); ++ SAORS_Release(iface); ++ return hr; ++ } ++ ++ /* Keep application callbacks impossible until activation has returned a ++ * fully published interface. The listener may have already signaled the ++ * auto-reset event; arming here preserves that pending endpoint loss. */ ++ if (This->invalidation_start_event && !SetEvent(This->invalidation_start_event)) ++ { ++ hr = HRESULT_FROM_WIN32(GetLastError()); ++ IAudioClient_Stop(This->client); ++ revoke_stream_objects(This, SPTLAUDCLNT_E_RESOURCES_INVALIDATED); ++ SAORS_Release(iface); + return hr; + } + ++ SAORS_Release(iface); + return S_OK; + } + + static HRESULT WINAPI SAORS_Stop(ISpatialAudioObjectRenderStream *iface) + { + SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); ++ BOOL notify; + HRESULT hr; + + TRACE("(%p)->()\n", This); + ++ EnterCriticalSection(&This->lock); ++ notify = poll_stream_invalidation_locked(This); ++ hr = This->invalidation_hr; ++ LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ if (FAILED(hr)) ++ return hr; ++ + hr = IAudioClient_Stop(This->client); + if(FAILED(hr)){ + WARN("IAudioClient::Stop failed: %08lx\n", hr); ++ revoke_stream_objects(This, hr); + return hr; + } + +@@ -379,8 +881,32 @@ static HRESULT WINAPI SAORS_Stop(ISpatialAudioObjectRenderStream *iface) + static HRESULT WINAPI SAORS_Reset(ISpatialAudioObjectRenderStream *iface) + { + SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); +- FIXME("(%p)->()\n", This); +- return E_NOTIMPL; ++ BOOL notify = FALSE; ++ HRESULT hr; ++ ++ TRACE("(%p)->()\n", This); ++ ++ EnterCriticalSection(&This->lock); ++ notify = poll_stream_invalidation_locked(This); ++ hr = This->invalidation_hr; ++ LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ if (FAILED(hr)) ++ return hr; ++ ++ hr = IAudioClient_Reset(This->client); ++ if (hr == AUDCLNT_E_NOT_STOPPED) ++ return SPTLAUDCLNT_E_STREAM_NOT_STOPPED; ++ if (SUCCEEDED(hr) || is_endpoint_resource_loss(hr)) ++ { ++ EnterCriticalSection(&This->lock); ++ notify = revoke_stream_objects_locked(This, hr, TRUE); ++ LeaveCriticalSection(&This->lock); ++ } ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ return hr; + } + + static HRESULT WINAPI SAORS_BeginUpdatingAudioObjects(ISpatialAudioObjectRenderStream *iface, +@@ -389,16 +915,34 @@ static HRESULT WINAPI SAORS_BeginUpdatingAudioObjects(ISpatialAudioObjectRenderS + static BOOL fixme_once = FALSE; + SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); + SpatialAudioObjectImpl *object; ++ BOOL notify = FALSE; + HRESULT hr; + + TRACE("(%p)->(%p, %p)\n", This, dyn_count, frames); + ++ if (!dyn_count || !frames) ++ return E_POINTER; ++ + EnterCriticalSection(&This->lock); + ++ notify = poll_stream_invalidation_locked(This); ++ + if(This->update_frames != ~0){ + LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); + return SPTLAUDCLNT_E_OUT_OF_ORDER; + } ++ if (FAILED(This->invalidation_hr)) ++ { ++ hr = This->invalidation_hr; ++ *dyn_count = 0; ++ *frames = 0; ++ LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ return hr; ++ } + + This->update_frames = This->period_frames; + +@@ -407,19 +951,37 @@ static HRESULT WINAPI SAORS_BeginUpdatingAudioObjects(ISpatialAudioObjectRenderS + if(FAILED(hr)){ + WARN("GetBuffer failed: %08lx\n", hr); + This->update_frames = ~0; ++ if (is_endpoint_resource_loss(hr)) ++ notify = revoke_stream_objects_locked(This, hr, TRUE); + LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); + return hr; + } + +- LIST_FOR_EACH_ENTRY(object, &This->objects, SpatialAudioObjectImpl, entry){ +- memset(object->buf, 0, This->update_frames * This->sa_client->object_fmtex.Format.nBlockAlign); ++ /* GetBuffer does not promise cleared storage. Every update is a fresh ++ * mix, so initialize the complete interleaved transport bed before ++ * accumulating individual object buffers into it. */ ++ memset(This->buf, 0, (size_t)This->update_frames * ++ This->stream_fmtex.Format.nBlockAlign); ++ if (This->max_dynamic_objects) ++ memset(This->dynamic_states, 0, This->max_dynamic_objects * sizeof(*This->dynamic_states)); ++ ++ LIST_FOR_EACH_ENTRY(object, &This->objects, SpatialAudioObjectImpl, entry) ++ { ++ object->got_buffer = FALSE; ++ object->end_of_stream = FALSE; ++ if (object->active) ++ memset(object->buf, 0, (size_t)This->update_frames * ++ This->sa_client->object_fmtex.Format.nBlockAlign); + } + }else if (!fixme_once){ + fixme_once = TRUE; + FIXME("Zero frame update.\n"); + } + +- *dyn_count = 0; ++ assert(This->allocated_dynamic_objects <= This->max_dynamic_objects); ++ *dyn_count = This->max_dynamic_objects; + *frames = This->update_frames; + + LeaveCriticalSection(&This->lock); +@@ -427,95 +989,267 @@ static HRESULT WINAPI SAORS_BeginUpdatingAudioObjects(ISpatialAudioObjectRenderS + return S_OK; + } + +-static void mix_static_object(SpatialAudioStreamImpl *stream, SpatialAudioObjectImpl *object) ++static void mix_object(SpatialAudioStreamImpl *stream, SpatialAudioObjectImpl *object, ++ UINT32 frames) + { +- float *in = object->buf, *out; +- UINT32 i; +- if(object->static_idx == ~0 || +- stream->static_object_map[object->static_idx] == ~0){ +- WARN("Got unmapped static object?! Not mixing. Type: 0x%x\n", object->type); ++ unsigned int object_idx, frame; ++ ++ if (object->type == AudioObjectType_Dynamic) ++ { ++ struct spatial_audio_object_state *state; ++ float *out; ++ ++ assert(object->dynamic_slot < stream->max_dynamic_objects); ++ state = &stream->dynamic_states[object->dynamic_slot]; ++ state->x = object->x; ++ state->y = object->y; ++ state->z = object->z; ++ state->active_frames = frames; ++ ++ out = stream->buf + stream->dynamic_channel_base + object->dynamic_slot; ++ for (frame = 0; frame < frames; ++frame) ++ { ++ *out += object->buf[frame] * object->volume; ++ out += stream->stream_fmtex.Format.nChannels; ++ } ++ return; ++ } ++ ++ if (object->type == AudioObjectType_None) ++ { ++ float *out = stream->buf + stream->dry_channel; ++ ++ /* Keep non-spatialized objects on a private transport channel. The ++ * backend mixes it into the physical front pair only after rendering ++ * the spatial bed, so HRTF, distance, and room processing cannot color ++ * dialogue or other listener-locked content. */ ++ assert(stream->stream_fmtex.dwChannelMask & SPATIAL_AUDIO_DRY_SPEAKER); ++ for (frame = 0; frame < frames; ++frame) ++ { ++ *out += object->buf[frame] * object->volume; ++ out += stream->stream_fmtex.Format.nChannels; ++ } + return; + } +- out = stream->buf + stream->static_object_map[object->static_idx]; +- for(i = 0; i < stream->update_frames; ++i){ +- *out += *in; +- ++in; +- out += stream->stream_fmtex.Format.nChannels; ++ ++ for (object_idx = 0; object_idx < ARRAY_SIZE(static_objects); ++object_idx) ++ { ++ float *out; ++ UINT32 channel; ++ ++ if (!(object->type & static_objects[object_idx].type)) ++ continue; ++ ++ channel = stream->static_object_map[AudioObjectType_to_index(static_objects[object_idx].type)]; ++ if (channel == ~0u) ++ { ++ WARN("Got unmapped static object type 0x%x.\n", static_objects[object_idx].type); ++ continue; ++ } ++ ++ out = stream->buf + channel; ++ for (frame = 0; frame < frames; ++frame) ++ { ++ *out += object->buf[frame] * object->volume; ++ out += stream->stream_fmtex.Format.nChannels; ++ } + } + } + + static HRESULT WINAPI SAORS_EndUpdatingAudioObjects(ISpatialAudioObjectRenderStream *iface) + { + SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); +- SpatialAudioObjectImpl *object; +- HRESULT hr; ++ SpatialAudioObjectImpl *object, *object2; ++ struct list released_objects = LIST_INIT(released_objects); ++ BOOL notify = FALSE; ++ HRESULT hr = S_OK; + + TRACE("(%p)->()\n", This); + + EnterCriticalSection(&This->lock); + ++ notify = poll_stream_invalidation_locked(This); ++ + if(This->update_frames == ~0){ + LeaveCriticalSection(&This->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(This); + return SPTLAUDCLNT_E_OUT_OF_ORDER; + } + +- if(This->update_frames > 0){ +- LIST_FOR_EACH_ENTRY(object, &This->objects, SpatialAudioObjectImpl, entry){ +- if(object->type != AudioObjectType_Dynamic) +- mix_static_object(This, object); +- else +- WARN("Don't know how to mix dynamic object yet. %p\n", object); ++ if (This->update_frames > 0) ++ { ++ LIST_FOR_EACH_ENTRY_SAFE(object, object2, &This->objects, SpatialAudioObjectImpl, entry) ++ { ++ if (object->end_of_stream) ++ { ++ mix_object(This, object, object->end_of_stream_frames); ++ object->end_of_stream = FALSE; ++ } ++ else if (object->active && object->got_buffer) ++ { ++ mix_object(This, object, This->update_frames); ++ } ++ else if (object->active && object->started) ++ { ++ TRACE("Implicitly ending object %p because it was not updated.\n", object); ++ object->active = FALSE; ++ } ++ ++ if (object->released) ++ { ++ list_remove(&object->entry); ++ if (object->type == AudioObjectType_Dynamic) ++ { ++ assert(object->dynamic_slot < This->max_dynamic_objects); ++ assert(This->dynamic_slots[object->dynamic_slot] == object); ++ This->dynamic_slots[object->dynamic_slot] = NULL; ++ assert(This->allocated_dynamic_objects); ++ --This->allocated_dynamic_objects; ++ } ++ list_add_tail(&released_objects, &object->entry); ++ } + } + +- hr = IAudioRenderClient_ReleaseBuffer(This->render, This->update_frames, 0); +- if(FAILED(hr)) ++ if (This->max_dynamic_objects) ++ hr = audio_client_release_spatial_buffer(This->client, This->update_frames, 0, ++ This->dynamic_states, This->max_dynamic_objects); ++ else ++ hr = IAudioRenderClient_ReleaseBuffer(This->render, This->update_frames, 0); ++ if (FAILED(hr)) ++ { + WARN("ReleaseBuffer failed: %08lx\n", hr); ++ if (is_endpoint_resource_loss(hr)) ++ notify |= revoke_stream_objects_locked(This, hr, TRUE); ++ } ++ } ++ else ++ { ++ LIST_FOR_EACH_ENTRY_SAFE(object, object2, &This->objects, SpatialAudioObjectImpl, entry) ++ { ++ if (object->released) ++ { ++ list_remove(&object->entry); ++ if (object->type == AudioObjectType_Dynamic) ++ { ++ assert(object->dynamic_slot < This->max_dynamic_objects); ++ assert(This->dynamic_slots[object->dynamic_slot] == object); ++ This->dynamic_slots[object->dynamic_slot] = NULL; ++ assert(This->allocated_dynamic_objects); ++ --This->allocated_dynamic_objects; ++ } ++ list_add_tail(&released_objects, &object->entry); ++ } ++ } + } + ++ if (SUCCEEDED(hr) && FAILED(This->invalidation_hr)) ++ hr = This->invalidation_hr; + This->update_frames = ~0; + + LeaveCriticalSection(&This->lock); + +- return S_OK; ++ LIST_FOR_EACH_ENTRY_SAFE(object, object2, &released_objects, SpatialAudioObjectImpl, entry) ++ { ++ list_remove(&object->entry); ++ free(object->buf); ++ free(object); ++ } ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ ++ return hr; + } + + static HRESULT WINAPI SAORS_ActivateSpatialAudioObject(ISpatialAudioObjectRenderStream *iface, + AudioObjectType type, ISpatialAudioObject **object) + { + SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); +- SpatialAudioObjectImpl *obj; ++ SpatialAudioObjectImpl *obj, *existing; ++ BOOL notify; ++ UINT32 slot; + + TRACE("(%p)->(0x%x, %p)\n", This, type, object); + +- if(type == AudioObjectType_Dynamic) +- return SPTLAUDCLNT_E_NO_MORE_OBJECTS; ++ if (!object) ++ return E_POINTER; ++ *object = NULL; + +- if(type & ~This->params.StaticObjectTypeMask) ++ if (type != AudioObjectType_None && type != AudioObjectType_Dynamic && ++ (type & ~NATIVE_STATIC_OBJECT_MASK)) ++ return E_INVALIDARG; ++ if (type != AudioObjectType_Dynamic && (type & ~This->params.StaticObjectTypeMask)) + return SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE; + +- LIST_FOR_EACH_ENTRY(obj, &This->objects, SpatialAudioObjectImpl, entry){ +- if(obj->static_idx == AudioObjectType_to_index(type)) +- return SPTLAUDCLNT_E_OBJECT_ALREADY_ACTIVE; +- } +- + obj = calloc(1, sizeof(*obj)); ++ if (!obj) ++ return E_OUTOFMEMORY; ++ + obj->ISpatialAudioObject_iface.lpVtbl = &ISpatialAudioObject_vtbl; + obj->ref = 1; + obj->type = type; +- if(type == AudioObjectType_None){ +- FIXME("AudioObjectType_None not implemented yet!\n"); +- obj->static_idx = ~0; +- }else{ +- obj->static_idx = AudioObjectType_to_index(type); +- } ++ obj->dynamic_slot = ~0u; ++ obj->volume = 1.0f; ++ obj->active = TRUE; + + obj->sa_stream = This; +- SAORS_AddRef(&This->ISpatialAudioObjectRenderStream_iface); +- + obj->buf = calloc(This->period_frames, This->sa_client->object_fmtex.Format.nBlockAlign); ++ if (!obj->buf) ++ { ++ free(obj); ++ return E_OUTOFMEMORY; ++ } + + EnterCriticalSection(&This->lock); + ++ notify = poll_stream_invalidation_locked(This); ++ if (FAILED(This->invalidation_hr)) ++ { ++ HRESULT hr = This->invalidation_hr; ++ ++ LeaveCriticalSection(&This->lock); ++ free(obj->buf); ++ free(obj); ++ if (notify) ++ notify_dynamic_capacity_lost(This); ++ return hr; ++ } ++ ++ /* Complete every operation that can fail before reserving a dynamic slot. ++ * Once the slot is published below, the remaining operations are ++ * infallible, so neither the pointer nor allocated count needs unwind. */ ++ LIST_FOR_EACH_ENTRY(existing, &This->objects, SpatialAudioObjectImpl, entry) ++ { ++ if (type != AudioObjectType_Dynamic && ++ (existing->type == type || (type && (existing->type & type)))) ++ { ++ LeaveCriticalSection(&This->lock); ++ free(obj->buf); ++ free(obj); ++ return SPTLAUDCLNT_E_OBJECT_ALREADY_ACTIVE; ++ } ++ } ++ ++ if (type == AudioObjectType_Dynamic) ++ { ++ if (This->allocated_dynamic_objects == This->max_dynamic_objects) ++ { ++ LeaveCriticalSection(&This->lock); ++ free(obj->buf); ++ free(obj); ++ return SPTLAUDCLNT_E_NO_MORE_OBJECTS; ++ } ++ ++ for (slot = 0; slot < This->max_dynamic_objects; ++slot) ++ if (!This->dynamic_slots[slot]) ++ break; ++ assert(slot < This->max_dynamic_objects); ++ obj->dynamic_slot = slot; ++ This->dynamic_slots[slot] = obj; ++ ++This->allocated_dynamic_objects; ++ } ++ ++ SAORS_AddRef(&This->ISpatialAudioObjectRenderStream_iface); + list_add_tail(&This->objects, &obj->entry); + + LeaveCriticalSection(&This->lock); +@@ -586,26 +1320,59 @@ static HRESULT WINAPI SAC_GetStaticObjectPosition(ISpatialAudioClient *iface, + AudioObjectType type, float *x, float *y, float *z) + { + SpatialAudioImpl *This = impl_from_ISpatialAudioClient(iface); +- FIXME("(%p)->(0x%x, %p, %p, %p)\n", This, type, x, y, z); +- return E_NOTIMPL; ++ unsigned int i; ++ ++ TRACE("(%p)->(0x%x, %p, %p, %p)\n", This, type, x, y, z); ++ ++ if (!x || !y || !z) ++ return E_POINTER; ++ ++ for (i = 0; i < ARRAY_SIZE(static_objects); ++i) ++ { ++ if (static_objects[i].type != type) ++ continue; ++ ++ *x = static_objects[i].x; ++ *y = static_objects[i].y; ++ *z = static_objects[i].z; ++ return S_OK; ++ } ++ ++ return E_INVALIDARG; + } + + static HRESULT WINAPI SAC_GetNativeStaticObjectTypeMask(ISpatialAudioClient *iface, + AudioObjectType *mask) + { + SpatialAudioImpl *This = impl_from_ISpatialAudioClient(iface); +- FIXME("(%p)->(%p)\n", This, mask); +- return E_NOTIMPL; ++ ++ TRACE("(%p)->(%p)\n", This, mask); ++ ++ if (!mask) ++ return E_POINTER; ++ ++ *mask = NATIVE_STATIC_OBJECT_MASK; ++ return S_OK; + } + + static HRESULT WINAPI SAC_GetMaxDynamicObjectCount(ISpatialAudioClient *iface, + UINT32 *value) + { + SpatialAudioImpl *This = impl_from_ISpatialAudioClient(iface); +- FIXME("(%p)->(%p)\n", This, value); ++ struct spatial_audio_capabilities capabilities; ++ HRESULT hr; ++ ++ TRACE("(%p)->(%p)\n", This, value); ++ ++ if (!value) ++ return E_POINTER; + + *value = 0; ++ hr = audio_client_get_spatial_audio_capabilities(This->mmdev, &capabilities); ++ if (FAILED(hr)) ++ return hr; + ++ *value = capabilities.max_dynamic_objects; + return S_OK; + } + +@@ -616,6 +1383,9 @@ static HRESULT WINAPI SAC_GetSupportedAudioObjectFormatEnumerator( + + TRACE("(%p)->(%p)\n", This, enumerator); + ++ if (!enumerator) ++ return E_POINTER; ++ + *enumerator = &This->IAudioFormatEnumerator_iface; + SAC_AddRef(iface); + +@@ -626,15 +1396,22 @@ static HRESULT WINAPI SAC_GetMaxFrameCount(ISpatialAudioClient *iface, + const WAVEFORMATEX *format, UINT32 *count) + { + SpatialAudioImpl *This = impl_from_ISpatialAudioClient(iface); +- +- /* FIXME: should get device period from the device */ +- static const REFERENCE_TIME period = 100000; ++ struct spatial_audio_capabilities capabilities; ++ HRESULT hr; + + TRACE("(%p)->(%p, %p)\n", This, format, count); + +- *count = MulDiv(period, format->nSamplesPerSec, 10000000); ++ if (!format || !count) ++ return E_POINTER; + +- return S_OK; ++ *count = 0; ++ if (!formats_equal(&This->object_fmtex.Format, format)) ++ return E_INVALIDARG; ++ ++ hr = audio_client_get_spatial_audio_capabilities(This->mmdev, &capabilities); ++ if (FAILED(hr)) ++ return hr; ++ return spatial_period_for_format(&capabilities, format->nSamplesPerSec, NULL, count); + } + + static HRESULT WINAPI SAC_IsAudioObjectFormatSupported(ISpatialAudioClient *iface, +@@ -667,49 +1444,86 @@ static HRESULT WINAPI SAC_IsSpatialAudioStreamAvailable(ISpatialAudioClient *ifa + static WAVEFORMATEX *clone_fmtex(const WAVEFORMATEX *src) + { + WAVEFORMATEX *r = malloc(sizeof(WAVEFORMATEX) + src->cbSize); ++ ++ if (!r) ++ return NULL; ++ + memcpy(r, src, sizeof(WAVEFORMATEX) + src->cbSize); + return r; + } + +-static void static_mask_to_channels(AudioObjectType static_mask, WORD *count, DWORD *mask, UINT32 *map) ++static unsigned int count_bits(DWORD value) + { +- UINT32 out_chan = 0, map_idx = 0; ++ unsigned int count = 0; ++ ++ while (value) ++ { ++ value &= value - 1; ++ ++count; ++ } ++ return count; ++} ++ ++static HRESULT static_mask_to_channels(AudioObjectType static_mask, WORD *count, ++ DWORD *mask, UINT32 *dry_channel, UINT32 *map) ++{ ++ unsigned int i; ++ ++ if (static_mask & ~NATIVE_STATIC_OBJECT_MASK) ++ return E_INVALIDARG; ++ + *count = 0; + *mask = 0; +-#define CONVERT_MASK(f, t) \ +- if(static_mask & f){ \ +- *count += 1; \ +- *mask |= t; \ +- map[map_idx++] = out_chan++; \ +- TRACE("mapping 0x%x to %u\n", f, out_chan - 1); \ +- }else{ \ +- map[map_idx++] = ~0; \ +- } +- CONVERT_MASK(AudioObjectType_FrontLeft, SPEAKER_FRONT_LEFT); +- CONVERT_MASK(AudioObjectType_FrontRight, SPEAKER_FRONT_RIGHT); +- CONVERT_MASK(AudioObjectType_FrontCenter, SPEAKER_FRONT_CENTER); +- CONVERT_MASK(AudioObjectType_LowFrequency, SPEAKER_LOW_FREQUENCY); +- CONVERT_MASK(AudioObjectType_SideLeft, SPEAKER_SIDE_LEFT); +- CONVERT_MASK(AudioObjectType_SideRight, SPEAKER_SIDE_RIGHT); +- CONVERT_MASK(AudioObjectType_BackLeft, SPEAKER_BACK_LEFT); +- CONVERT_MASK(AudioObjectType_BackRight, SPEAKER_BACK_RIGHT); +- CONVERT_MASK(AudioObjectType_TopFrontLeft, SPEAKER_TOP_FRONT_LEFT); +- CONVERT_MASK(AudioObjectType_TopFrontRight, SPEAKER_TOP_FRONT_RIGHT); +- CONVERT_MASK(AudioObjectType_TopBackLeft, SPEAKER_TOP_BACK_LEFT); +- CONVERT_MASK(AudioObjectType_TopBackRight, SPEAKER_TOP_BACK_RIGHT); +- CONVERT_MASK(AudioObjectType_BackCenter, SPEAKER_BACK_CENTER); ++ ++ for (i = 0; i < ARRAY_SIZE(static_objects); ++i) ++ { ++ UINT32 object_idx = AudioObjectType_to_index(static_objects[i].type); ++ ++ map[object_idx] = ~0u; ++ if (!(static_mask & static_objects[i].type)) ++ continue; ++ ++ if (!static_objects[i].speaker) ++ return E_INVALIDARG; ++ ++ *mask |= static_objects[i].speaker; ++ } ++ ++ /* Front left/right keep the bed renderable on stereo endpoints even when ++ * the application did not request those static objects. The private dry ++ * slot carries AudioObjectType_None. The backend removes it from the bed ++ * layout and mixes it into the final front pair after spatial rendering. */ ++ *mask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPATIAL_AUDIO_DRY_SPEAKER; ++ *count = count_bits(*mask); ++ *dry_channel = count_bits(*mask & (SPATIAL_AUDIO_DRY_SPEAKER - 1)); ++ for (i = 0; i < ARRAY_SIZE(static_objects); ++i) ++ { ++ UINT32 object_idx; ++ ++ if (!(static_mask & static_objects[i].type)) ++ continue; ++ ++ object_idx = AudioObjectType_to_index(static_objects[i].type); ++ map[object_idx] = count_bits(*mask & (static_objects[i].speaker - 1)); ++ TRACE("Mapping object type 0x%x to channel %u.\n", ++ static_objects[i].type, map[object_idx]); ++ } ++ ++ return S_OK; + } + + static HRESULT activate_stream(SpatialAudioStreamImpl *stream) + { + WAVEFORMATEXTENSIBLE *object_fmtex = (WAVEFORMATEXTENSIBLE *)stream->params.ObjectFormat; ++ WCHAR profile[2]; ++ UINT64 value; + HRESULT hr; +- REFERENCE_TIME period; ++ REFERENCE_TIME latency, period; + + if(!(object_fmtex->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT || + (object_fmtex->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && + IsEqualGUID(&object_fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)))){ +- FIXME("Only float formats are supported for now\n"); ++ TRACE("Rejecting a non-float spatial object format.\n"); + return E_INVALIDARG; + } + +@@ -720,28 +1534,82 @@ static HRESULT activate_stream(SpatialAudioStreamImpl *stream) + return hr; + } + +- hr = IAudioClient_GetDevicePeriod(stream->client, &period, NULL); +- if(FAILED(hr)){ +- WARN("GetDevicePeriod failed: %08lx\n", hr); ++ if (!stream->capabilities.sample_rate || !stream->capabilities.period_frames) ++ { + IAudioClient_Release(stream->client); ++ stream->client = NULL; ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ } ++ ++ hr = spatial_period_for_format(&stream->capabilities, ++ stream->params.ObjectFormat->nSamplesPerSec, &period, ++ &stream->period_frames); ++ if (FAILED(hr)) ++ { ++ IAudioClient_Release(stream->client); ++ stream->client = NULL; + return hr; + } + + stream->stream_fmtex.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; +- static_mask_to_channels(stream->params.StaticObjectTypeMask, ++ hr = static_mask_to_channels(stream->params.StaticObjectTypeMask, + &stream->stream_fmtex.Format.nChannels, &stream->stream_fmtex.dwChannelMask, +- stream->static_object_map); ++ &stream->dry_channel, stream->static_object_map); ++ if (FAILED(hr)) ++ { ++ IAudioClient_Release(stream->client); ++ stream->client = NULL; ++ return hr; ++ } ++ stream->dynamic_channel_base = stream->stream_fmtex.Format.nChannels; ++ if (stream->max_dynamic_objects > 0xffffu - stream->stream_fmtex.Format.nChannels) ++ { ++ IAudioClient_Release(stream->client); ++ stream->client = NULL; ++ return E_INVALIDARG; ++ } ++ stream->stream_fmtex.Format.nChannels += stream->max_dynamic_objects; + stream->stream_fmtex.Format.nSamplesPerSec = stream->params.ObjectFormat->nSamplesPerSec; + stream->stream_fmtex.Format.wBitsPerSample = stream->params.ObjectFormat->wBitsPerSample; +- stream->stream_fmtex.Format.nBlockAlign = (stream->stream_fmtex.Format.nChannels * stream->stream_fmtex.Format.wBitsPerSample) / 8; ++ value = (UINT64)stream->stream_fmtex.Format.nChannels * ++ stream->stream_fmtex.Format.wBitsPerSample / 8; ++ if (value > 0xffffu) ++ { ++ IAudioClient_Release(stream->client); ++ stream->client = NULL; ++ return E_INVALIDARG; ++ } ++ stream->stream_fmtex.Format.nBlockAlign = value; ++ if (stream->stream_fmtex.Format.nSamplesPerSec > ~0u / ++ stream->stream_fmtex.Format.nBlockAlign) ++ { ++ IAudioClient_Release(stream->client); ++ stream->client = NULL; ++ return E_INVALIDARG; ++ } + stream->stream_fmtex.Format.nAvgBytesPerSec = stream->stream_fmtex.Format.nSamplesPerSec * stream->stream_fmtex.Format.nBlockAlign; + stream->stream_fmtex.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); + stream->stream_fmtex.Samples.wValidBitsPerSample = stream->stream_fmtex.Format.wBitsPerSample; + stream->stream_fmtex.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; + +- hr = IAudioClient_Initialize(stream->client, AUDCLNT_SHAREMODE_SHARED, ++ value = stream->period_frames; ++ if (value > ~(SIZE_T)0 / ++ stream->stream_fmtex.Format.nBlockAlign || value > ~0u / ++ stream->sa_client->object_fmtex.Format.nBlockAlign) ++ { ++ IAudioClient_Release(stream->client); ++ stream->client = NULL; ++ return E_INVALIDARG; ++ } ++ stream->period_frames = value; ++ ++ hr = audio_client_initialize_spatial(stream->client, + AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, +- period, 0, &stream->stream_fmtex.Format, NULL); ++ period, 0, &stream->stream_fmtex.Format, NULL, ++ stream->params.StaticObjectTypeMask, stream->max_dynamic_objects, ++ stream->capabilities.endpoint_generation, ++ stream->invalidation_event, ++ stream->fault_invalidate_on_start); + if(FAILED(hr)){ + WARN("Initialize failed: %08lx\n", hr); + IAudioClient_Release(stream->client); +@@ -762,7 +1630,12 @@ static HRESULT activate_stream(SpatialAudioStreamImpl *stream) + return hr; + } + +- stream->period_frames = MulDiv(period, stream->stream_fmtex.Format.nSamplesPerSec, 10000000); ++ if (GetEnvironmentVariableW(L"SWITCHYARD_SPATIAL_AUDIO_PROFILE", ++ profile, ARRAY_SIZE(profile)) && ++ SUCCEEDED(IAudioClient_GetStreamLatency(stream->client, &latency))) ++ TRACE("Spatial stream latency %s (period %s, %u frames).\n", ++ wine_dbgstr_longlong(latency), wine_dbgstr_longlong(period), ++ stream->period_frames); + + return S_OK; + } +@@ -772,44 +1645,72 @@ static HRESULT WINAPI SAC_ActivateSpatialAudioStream(ISpatialAudioClient *iface, + { + SpatialAudioImpl *This = impl_from_ISpatialAudioClient(iface); + SpatialAudioObjectRenderStreamActivationParams *params; ++ struct spatial_audio_capabilities capabilities; ++ UINT32 dynamic_count; + HRESULT hr; + + TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), stream); + ++ if (!stream) ++ return E_POINTER; ++ *stream = NULL; ++ + if(IsEqualIID(riid, &IID_ISpatialAudioObjectRenderStream)){ + SpatialAudioStreamImpl *obj; + +- if(prop && +- (prop->vt != VT_BLOB || +- prop->blob.cbSize != sizeof(SpatialAudioObjectRenderStreamActivationParams))){ ++ if (!prop || prop->vt != VT_BLOB || ++ prop->blob.cbSize != sizeof(SpatialAudioObjectRenderStreamActivationParams) || ++ !prop->blob.pBlobData) ++ { + WARN("Got invalid params\n"); +- *stream = NULL; + return E_INVALIDARG; + } + + params = (SpatialAudioObjectRenderStreamActivationParams*) prop->blob.pBlobData; + +- if(params->StaticObjectTypeMask & AudioObjectType_Dynamic){ +- *stream = NULL; ++ TRACE("Activation params: format {%s}, static mask %#x, dynamic %u..%u, " ++ "category %u, event %p, notify %p.\n", debugstr_fmtex(params->ObjectFormat), ++ params->StaticObjectTypeMask, params->MinDynamicObjectCount, ++ params->MaxDynamicObjectCount, params->Category, params->EventHandle, ++ params->NotifyObject); ++ ++ if (params->StaticObjectTypeMask & ~NATIVE_STATIC_OBJECT_MASK) ++ { ++ TRACE("Rejecting unavailable static objects.\n"); + return E_INVALIDARG; + } ++ if (params->MinDynamicObjectCount > params->MaxDynamicObjectCount) ++ return E_INVALIDARG; + + if(params->EventHandle == INVALID_HANDLE_VALUE || + params->EventHandle == 0){ +- *stream = NULL; ++ TRACE("Rejecting invalid event handle %p.\n", params->EventHandle); + return E_INVALIDARG; + } + + if(!(params->ObjectFormat && formats_equal(params->ObjectFormat, &This->object_fmtex.Format))) { +- *stream = NULL; ++ TRACE("Rejecting unsupported object format; expected {%s}.\n", ++ debugstr_fmtex(&This->object_fmtex.Format)); + return AUDCLNT_E_UNSUPPORTED_FORMAT; + } + ++ hr = audio_client_get_spatial_audio_capabilities(This->mmdev, &capabilities); ++ if (FAILED(hr)) ++ return hr; ++ if (params->MinDynamicObjectCount > capabilities.max_dynamic_objects) ++ return SPTLAUDCLNT_E_NO_MORE_OBJECTS; ++ dynamic_count = min(params->MaxDynamicObjectCount, capabilities.max_dynamic_objects); ++ + obj = calloc(1, sizeof(SpatialAudioStreamImpl)); ++ if (!obj) ++ return E_OUTOFMEMORY; + + obj->ISpatialAudioObjectRenderStream_iface.lpVtbl = &ISpatialAudioObjectRenderStream_vtbl; + obj->ref = 1; + memcpy(&obj->params, params, sizeof(obj->params)); ++ obj->params.MaxDynamicObjectCount = dynamic_count; ++ obj->max_dynamic_objects = dynamic_count; ++ obj->capabilities = capabilities; + + obj->update_frames = ~0; + +@@ -819,11 +1720,84 @@ static HRESULT WINAPI SAC_ActivateSpatialAudioStream(ISpatialAudioClient *iface, + obj->sa_client = This; + SAC_AddRef(&This->ISpatialAudioClient_iface); + ++ if (dynamic_count) ++ { ++ obj->dynamic_slots = calloc(dynamic_count, sizeof(*obj->dynamic_slots)); ++ obj->dynamic_states = calloc(dynamic_count, sizeof(*obj->dynamic_states)); ++ if (!obj->dynamic_slots || !obj->dynamic_states) ++ { ++ free(obj->dynamic_states); ++ free(obj->dynamic_slots); ++ DeleteCriticalSection(&obj->lock); ++ ISpatialAudioClient_Release(&obj->sa_client->ISpatialAudioClient_iface); ++ free(obj); ++ return E_OUTOFMEMORY; ++ } ++ } ++ + obj->params.ObjectFormat = clone_fmtex(obj->params.ObjectFormat); ++ if (!obj->params.ObjectFormat) ++ { ++ free(obj->dynamic_states); ++ free(obj->dynamic_slots); ++ DeleteCriticalSection(&obj->lock); ++ ISpatialAudioClient_Release(&obj->sa_client->ISpatialAudioClient_iface); ++ free(obj); ++ return E_OUTOFMEMORY; ++ } + +- DuplicateHandle(GetCurrentProcess(), obj->params.EventHandle, ++ if (!DuplicateHandle(GetCurrentProcess(), obj->params.EventHandle, + GetCurrentProcess(), &obj->params.EventHandle, 0, FALSE, +- DUPLICATE_SAME_ACCESS); ++ DUPLICATE_SAME_ACCESS)) ++ { ++ DeleteCriticalSection(&obj->lock); ++ free((void *)obj->params.ObjectFormat); ++ free(obj->dynamic_states); ++ free(obj->dynamic_slots); ++ ISpatialAudioClient_Release(&obj->sa_client->ISpatialAudioClient_iface); ++ free(obj); ++ return HRESULT_FROM_WIN32(GetLastError()); ++ } ++ ++ if (dynamic_count) ++ { ++ WCHAR fault[2]; ++ ++ obj->invalidation_event = CreateEventW(NULL, FALSE, FALSE, NULL); ++ if (obj->params.NotifyObject) ++ { ++ obj->invalidation_ready_event = CreateEventW(NULL, TRUE, FALSE, NULL); ++ obj->invalidation_start_event = CreateEventW(NULL, TRUE, FALSE, NULL); ++ } ++ if (!obj->invalidation_event || (obj->params.NotifyObject && ++ (!obj->invalidation_ready_event || ++ !obj->invalidation_start_event))) ++ { ++ hr = HRESULT_FROM_WIN32(GetLastError()); ++ if (obj->invalidation_start_event) ++ CloseHandle(obj->invalidation_start_event); ++ if (obj->invalidation_ready_event) ++ CloseHandle(obj->invalidation_ready_event); ++ if (obj->invalidation_event) ++ CloseHandle(obj->invalidation_event); ++ DeleteCriticalSection(&obj->lock); ++ free((void *)obj->params.ObjectFormat); ++ free(obj->dynamic_states); ++ free(obj->dynamic_slots); ++ CloseHandle(obj->params.EventHandle); ++ ISpatialAudioClient_Release(&obj->sa_client->ISpatialAudioClient_iface); ++ free(obj); ++ return hr; ++ } ++ if (GetEnvironmentVariableW( ++ L"SWITCHYARD_SPATIAL_AUDIO_FAULT_INVALIDATE_ON_START", ++ fault, ARRAY_SIZE(fault)) == 1 && fault[0] == '1') ++ obj->fault_invalidate_on_start = 1; ++ if (GetEnvironmentVariableW( ++ L"SWITCHYARD_SPATIAL_AUDIO_FAULT_INVALIDATE_BEFORE_START", ++ fault, ARRAY_SIZE(fault)) == 1 && fault[0] == '1') ++ obj->fault_invalidate_before_start = 1; ++ } + + if(obj->params.NotifyObject) + ISpatialAudioObjectRenderStreamNotify_AddRef(obj->params.NotifyObject); +@@ -844,17 +1818,51 @@ static HRESULT WINAPI SAC_ActivateSpatialAudioStream(ISpatialAudioClient *iface, + ISpatialAudioObjectRenderStreamNotify_Release(obj->params.NotifyObject); + DeleteCriticalSection(&obj->lock); + free((void*)obj->params.ObjectFormat); ++ free(obj->dynamic_states); ++ free(obj->dynamic_slots); ++ if (obj->invalidation_event) ++ CloseHandle(obj->invalidation_event); ++ if (obj->invalidation_ready_event) ++ CloseHandle(obj->invalidation_ready_event); ++ if (obj->invalidation_start_event) ++ CloseHandle(obj->invalidation_start_event); + CloseHandle(obj->params.EventHandle); + ISpatialAudioClient_Release(&obj->sa_client->ISpatialAudioClient_iface); + free(obj); +- *stream = NULL; + return hr; + } + ++ if (obj->invalidation_start_event) ++ { ++ obj->invalidation_thread = CreateThread(NULL, 0, ++ spatial_invalidation_thread, obj, 0, ++ &obj->invalidation_thread_id); ++ if (!obj->invalidation_thread) ++ { ++ hr = HRESULT_FROM_WIN32(GetLastError()); ++ SAORS_Release(&obj->ISpatialAudioObjectRenderStream_iface); ++ return hr; ++ } ++ if (WaitForSingleObject(obj->invalidation_ready_event, INFINITE) != ++ WAIT_OBJECT_0 || FAILED(obj->invalidation_thread_hr)) ++ { ++ hr = FAILED(obj->invalidation_thread_hr) ? ++ obj->invalidation_thread_hr : E_UNEXPECTED; ++ SAORS_Release(&obj->ISpatialAudioObjectRenderStream_iface); ++ return hr; ++ } ++ } ++ if (obj->invalidation_event && ++ WaitForSingleObject(obj->invalidation_event, 0) == WAIT_OBJECT_0) ++ { ++ SAORS_Release(&obj->ISpatialAudioObjectRenderStream_iface); ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ } + *stream = &obj->ISpatialAudioObjectRenderStream_iface; ++ if (obj->fault_invalidate_before_start) ++ SetEvent(obj->invalidation_event); + }else{ + FIXME("Unsupported audio stream IID: %s\n", debugstr_guid(riid)); +- *stream = NULL; + return E_NOTIMPL; + } + +@@ -900,8 +1908,10 @@ static HRESULT WINAPI SAOFE_GetCount(IAudioFormatEnumerator *iface, UINT32 *coun + + TRACE("(%p)->(%p)\n", This, count); + +- *count = 1; ++ if (!count) ++ return E_POINTER; + ++ *count = 1; + return S_OK; + } + +@@ -912,6 +1922,10 @@ static HRESULT WINAPI SAOFE_GetFormat(IAudioFormatEnumerator *iface, + + TRACE("(%p)->(%u, %p)\n", This, index, format); + ++ if (!format) ++ return E_POINTER; ++ ++ *format = NULL; + if(index > 0) + return E_INVALIDARG; + +@@ -931,11 +1945,13 @@ static IAudioFormatEnumeratorVtbl IAudioFormatEnumerator_vtbl = { + HRESULT SpatialAudioClient_Create(IMMDevice *mmdev, ISpatialAudioClient **out) + { + SpatialAudioImpl *obj; +- IAudioClient *aclient; +- WAVEFORMATEX *closest; +- HRESULT hr; + +- obj = calloc(1, sizeof(*obj)); ++ if (!out) ++ return E_POINTER; ++ *out = NULL; ++ ++ if (!(obj = calloc(1, sizeof(*obj)))) ++ return E_OUTOFMEMORY; + + obj->ref = 1; + obj->ISpatialAudioClient_iface.lpVtbl = &ISpatialAudioClient_vtbl; +@@ -949,45 +1965,6 @@ HRESULT SpatialAudioClient_Create(IMMDevice *mmdev, ISpatialAudioClient **out) + obj->object_fmtex.Format.nAvgBytesPerSec = obj->object_fmtex.Format.nSamplesPerSec * obj->object_fmtex.Format.nBlockAlign; + obj->object_fmtex.Format.cbSize = 0; + +- hr = IMMDevice_Activate(mmdev, &IID_IAudioClient, +- CLSCTX_INPROC_SERVER, NULL, (void**)&aclient); +- if(FAILED(hr)){ +- WARN("Activate failed: %08lx\n", hr); +- free(obj); +- return hr; +- } +- +- hr = IAudioClient_IsFormatSupported(aclient, AUDCLNT_SHAREMODE_SHARED, &obj->object_fmtex.Format, &closest); +- +- IAudioClient_Release(aclient); +- +- if(hr == S_FALSE){ +- if(sizeof(WAVEFORMATEX) + closest->cbSize > sizeof(obj->object_fmtex)){ +- ERR("Returned format too large: %s\n", debugstr_fmtex(closest)); +- CoTaskMemFree(closest); +- free(obj); +- return AUDCLNT_E_UNSUPPORTED_FORMAT; +- }else if(!((closest->wFormatTag == WAVE_FORMAT_IEEE_FLOAT || +- (closest->wFormatTag == WAVE_FORMAT_EXTENSIBLE && +- IsEqualGUID(&((WAVEFORMATEXTENSIBLE *)closest)->SubFormat, +- &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))) && +- closest->wBitsPerSample == 32)){ +- ERR("Returned format not 32-bit float: %s\n", debugstr_fmtex(closest)); +- CoTaskMemFree(closest); +- free(obj); +- return AUDCLNT_E_UNSUPPORTED_FORMAT; +- } +- WARN("The audio stack doesn't support 48kHz 32bit float. Using the closest match. Audio may be glitchy. %s\n", debugstr_fmtex(closest)); +- memcpy(&obj->object_fmtex, +- closest, +- sizeof(WAVEFORMATEX) + closest->cbSize); +- CoTaskMemFree(closest); +- } else if(hr != S_OK){ +- WARN("Checking supported formats failed: %08lx\n", hr); +- free(obj); +- return hr; +- } +- + obj->mmdev = mmdev; + IMMDevice_AddRef(mmdev); + +diff --git a/dlls/mmdevapi/unixlib.h b/dlls/mmdevapi/unixlib.h +index 3df13e9..087331b 100644 +--- a/dlls/mmdevapi/unixlib.h ++++ b/dlls/mmdevapi/unixlib.h +@@ -19,9 +19,61 @@ + + #include "audioclient.h" + #include "mmdeviceapi.h" ++#include "spatialaudioclient.h" + + typedef UINT64 stream_handle; + ++/* A snapshot of the endpoint properties which determine a spatial stream's ++ * processing quantum and PointSource budget. The generation is opaque to ++ * mmdevapi; the backend rejects activation if the endpoint changes between ++ * capability discovery and stream creation. */ ++struct spatial_audio_capabilities ++{ ++ UINT32 max_dynamic_objects; ++ UINT32 period_frames; ++ UINT32 sample_rate; ++ UINT32 endpoint_generation; ++}; ++ ++/* One entry per PointSource input bus, in bus order. Samples are transported ++ * in the corresponding private mono channel; active_frames limits the valid ++ * prefix for end-of-stream updates. */ ++struct spatial_audio_object_state ++{ ++ float x; ++ float y; ++ float z; ++ UINT32 active_frames; ++}; ++ ++/* ++ * Spatial streams use a WAVEFORMATEXTENSIBLE transport between mmdevapi and ++ * the Unix audio backend. AudioObjectType has four bottom speakers which do ++ * not have WAVE speaker-mask equivalents, so give them otherwise-unused WAVE ++ * slots. These values are private transport identifiers; backends must not ++ * expose their normal WAVE meanings to a device. ++ */ ++#define SPATIAL_AUDIO_BOTTOM_FRONT_LEFT_SPEAKER SPEAKER_FRONT_LEFT_OF_CENTER ++#define SPATIAL_AUDIO_BOTTOM_FRONT_RIGHT_SPEAKER SPEAKER_FRONT_RIGHT_OF_CENTER ++#define SPATIAL_AUDIO_BOTTOM_BACK_LEFT_SPEAKER SPEAKER_TOP_FRONT_CENTER ++#define SPATIAL_AUDIO_BOTTOM_BACK_RIGHT_SPEAKER SPEAKER_TOP_BACK_CENTER ++#define SPATIAL_AUDIO_DRY_SPEAKER SPEAKER_TOP_CENTER ++#define SPATIAL_AUDIO_PRIVATE_BED_SPEAKERS \ ++ (SPATIAL_AUDIO_BOTTOM_FRONT_LEFT_SPEAKER | \ ++ SPATIAL_AUDIO_BOTTOM_FRONT_RIGHT_SPEAKER | \ ++ SPATIAL_AUDIO_BOTTOM_BACK_LEFT_SPEAKER | \ ++ SPATIAL_AUDIO_BOTTOM_BACK_RIGHT_SPEAKER) ++#define SPATIAL_AUDIO_STATIC_OBJECT_MASK \ ++ (AudioObjectType_FrontLeft | AudioObjectType_FrontRight | \ ++ AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | \ ++ AudioObjectType_SideLeft | AudioObjectType_SideRight | \ ++ AudioObjectType_BackLeft | AudioObjectType_BackRight | \ ++ AudioObjectType_TopFrontLeft | AudioObjectType_TopFrontRight | \ ++ AudioObjectType_TopBackLeft | AudioObjectType_TopBackRight | \ ++ AudioObjectType_BottomFrontLeft | AudioObjectType_BottomFrontRight | \ ++ AudioObjectType_BottomBackLeft | AudioObjectType_BottomBackRight | \ ++ AudioObjectType_BackCenter) ++ + enum driver_priority + { + Priority_Unavailable = 0, /* driver won't work */ +@@ -58,6 +110,12 @@ struct create_stream_params + EDataFlow flow; + AUDCLNT_SHAREMODE share; + DWORD flags; ++ BOOL spatial; ++ UINT32 spatial_static_mask; ++ UINT32 spatial_dynamic_objects; ++ UINT32 spatial_endpoint_generation; ++ HANDLE spatial_invalidation_event; ++ BOOL spatial_fault_invalidate_on_start; + REFERENCE_TIME duration; + REFERENCE_TIME period; + const WAVEFORMATEX *fmt; +@@ -109,6 +167,8 @@ struct release_render_buffer_params + stream_handle stream; + UINT32 written_frames; + UINT flags; ++ const struct spatial_audio_object_state *spatial_objects; ++ UINT32 spatial_object_count; + HRESULT result; + }; + +@@ -165,6 +225,13 @@ struct get_device_period_params + REFERENCE_TIME *min_period; + }; + ++struct get_spatial_audio_capabilities_params ++{ ++ const char *device; ++ HRESULT result; ++ struct spatial_audio_capabilities capabilities; ++}; ++ + struct get_buffer_size_params + { + stream_handle stream; +@@ -350,5 +417,6 @@ enum unix_funcs + midi_in_message, + midi_notify_wait, + aux_message, ++ get_spatial_audio_capabilities, + funcs_count + }; +diff --git a/dlls/winealsa.drv/alsa.c b/dlls/winealsa.drv/alsa.c +index aea4ddf..8d6bb7d 100644 +--- a/dlls/winealsa.drv/alsa.c ++++ b/dlls/winealsa.drv/alsa.c +@@ -810,6 +810,18 @@ static NTSTATUS alsa_create_stream(void *args) + + params->result = S_OK; + ++ /* mmdevapi spatial streams use a private dry-object transport channel. ++ * Do not expose that channel as a physical speaker on backends which do ++ * not implement the corresponding bed/dry split. */ ++ if (params->spatial) ++ { ++ WARN("Spatial audio transport with %u dynamic objects at endpoint generation %u " ++ "is not supported by the ALSA backend.\n", ++ params->spatial_dynamic_objects, params->spatial_endpoint_generation); ++ params->result = AUDCLNT_E_UNSUPPORTED_FORMAT; ++ return STATUS_SUCCESS; ++ } ++ + stream = calloc(1, sizeof(*stream)); + if(!stream){ + params->result = E_OUTOFMEMORY; +@@ -1738,6 +1750,11 @@ static NTSTATUS alsa_release_render_buffer(void *args) + UINT32 written_frames = params->written_frames; + BYTE *buffer; + ++ /* ALSA rejects spatial streams at creation, so the optional spatial ++ * object-state payload must never be inspected by this backend. */ ++ (void)params->spatial_objects; ++ (void)params->spatial_object_count; ++ + alsa_lock(stream); + + if(!written_frames){ +@@ -2454,6 +2471,7 @@ const unixlib_entry_t __wine_unix_call_funcs[] = + alsa_midi_in_message, + alsa_midi_notify_wait, + alsa_not_implemented, ++ alsa_not_implemented, + }; + + C_ASSERT(ARRAYSIZE(__wine_unix_call_funcs) == funcs_count); +@@ -2509,6 +2527,12 @@ static NTSTATUS alsa_wow64_create_stream(void *args) + EDataFlow flow; + AUDCLNT_SHAREMODE share; + DWORD flags; ++ BOOL spatial; ++ UINT32 spatial_static_mask; ++ UINT32 spatial_dynamic_objects; ++ UINT32 spatial_endpoint_generation; ++ PTR32 spatial_invalidation_event; ++ BOOL spatial_fault_invalidate_on_start; + REFERENCE_TIME duration; + REFERENCE_TIME period; + PTR32 fmt; +@@ -2523,6 +2547,14 @@ static NTSTATUS alsa_wow64_create_stream(void *args) + .flow = params32->flow, + .share = params32->share, + .flags = params32->flags, ++ .spatial = params32->spatial, ++ .spatial_static_mask = params32->spatial_static_mask, ++ .spatial_dynamic_objects = params32->spatial_dynamic_objects, ++ .spatial_endpoint_generation = params32->spatial_endpoint_generation, ++ .spatial_invalidation_event = ULongToPtr( ++ params32->spatial_invalidation_event), ++ .spatial_fault_invalidate_on_start = ++ params32->spatial_fault_invalidate_on_start, + .duration = params32->duration, + .period = params32->period, + .fmt = ULongToPtr(params32->fmt), +@@ -2574,6 +2606,31 @@ static NTSTATUS alsa_wow64_get_render_buffer(void *args) + return STATUS_SUCCESS; + } + ++static NTSTATUS alsa_wow64_release_render_buffer(void *args) ++{ ++ struct ++ { ++ stream_handle stream; ++ UINT32 written_frames; ++ UINT flags; ++ PTR32 spatial_objects; ++ UINT32 spatial_object_count; ++ HRESULT result; ++ } *params32 = args; ++ struct release_render_buffer_params params = ++ { ++ .stream = params32->stream, ++ .written_frames = params32->written_frames, ++ .flags = params32->flags, ++ .spatial_objects = ULongToPtr(params32->spatial_objects), ++ .spatial_object_count = params32->spatial_object_count, ++ }; ++ ++ alsa_release_render_buffer(¶ms); ++ params32->result = params.result; ++ return STATUS_SUCCESS; ++} ++ + static NTSTATUS alsa_wow64_get_capture_buffer(void *args) + { + struct +@@ -2885,7 +2942,7 @@ const unixlib_entry_t __wine_unix_call_wow64_funcs[] = + alsa_reset, + alsa_timer_loop, + alsa_wow64_get_render_buffer, +- alsa_release_render_buffer, ++ alsa_wow64_release_render_buffer, + alsa_wow64_get_capture_buffer, + alsa_release_capture_buffer, + alsa_wow64_is_format_supported, +@@ -2911,6 +2968,7 @@ const unixlib_entry_t __wine_unix_call_wow64_funcs[] = + alsa_wow64_midi_in_message, + alsa_wow64_midi_notify_wait, + alsa_not_implemented, ++ alsa_not_implemented, + }; + + C_ASSERT(ARRAYSIZE(__wine_unix_call_wow64_funcs) == funcs_count); +diff --git a/dlls/wineoss.drv/oss.c b/dlls/wineoss.drv/oss.c +index bcdcc72..37b7205 100644 +--- a/dlls/wineoss.drv/oss.c ++++ b/dlls/wineoss.drv/oss.c +@@ -549,6 +549,18 @@ static NTSTATUS oss_create_stream(void *args) + + params->result = S_OK; + ++ /* mmdevapi spatial streams use a private dry-object transport channel. ++ * Do not expose that channel as a physical speaker on backends which do ++ * not implement the corresponding bed/dry split. */ ++ if (params->spatial) ++ { ++ WARN("Spatial audio transport with %u dynamic objects at endpoint generation %u " ++ "is not supported by the OSS backend.\n", ++ params->spatial_dynamic_objects, params->spatial_endpoint_generation); ++ params->result = AUDCLNT_E_UNSUPPORTED_FORMAT; ++ return STATUS_SUCCESS; ++ } ++ + stream = calloc(1, sizeof(*stream)); + if(!stream){ + params->result = E_OUTOFMEMORY; +@@ -983,6 +995,11 @@ static NTSTATUS oss_release_render_buffer(void *args) + UINT flags = params->flags; + BYTE *buffer; + ++ /* OSS rejects spatial streams at creation, so the optional spatial ++ * object-state payload must never be inspected by this backend. */ ++ (void)params->spatial_objects; ++ (void)params->spatial_object_count; ++ + oss_lock(stream); + + if(!written_frames){ +@@ -1674,6 +1691,7 @@ const unixlib_entry_t __wine_unix_call_funcs[] = + oss_midi_in_message, + oss_midi_notify_wait, + oss_aux_message, ++ oss_not_implemented, + }; + + C_ASSERT(ARRAYSIZE(__wine_unix_call_funcs) == funcs_count); +@@ -1745,6 +1763,12 @@ static NTSTATUS oss_wow64_create_stream(void *args) + EDataFlow flow; + AUDCLNT_SHAREMODE share; + UINT flags; ++ BOOL spatial; ++ UINT32 spatial_static_mask; ++ UINT32 spatial_dynamic_objects; ++ UINT32 spatial_endpoint_generation; ++ PTR32 spatial_invalidation_event; ++ BOOL spatial_fault_invalidate_on_start; + REFERENCE_TIME duration; + REFERENCE_TIME period; + PTR32 fmt; +@@ -1759,6 +1783,14 @@ static NTSTATUS oss_wow64_create_stream(void *args) + .flow = params32->flow, + .share = params32->share, + .flags = params32->flags, ++ .spatial = params32->spatial, ++ .spatial_static_mask = params32->spatial_static_mask, ++ .spatial_dynamic_objects = params32->spatial_dynamic_objects, ++ .spatial_endpoint_generation = params32->spatial_endpoint_generation, ++ .spatial_invalidation_event = ULongToPtr( ++ params32->spatial_invalidation_event), ++ .spatial_fault_invalidate_on_start = ++ params32->spatial_fault_invalidate_on_start, + .duration = params32->duration, + .period = params32->period, + .fmt = ULongToPtr(params32->fmt), +@@ -1810,6 +1842,31 @@ static NTSTATUS oss_wow64_get_render_buffer(void *args) + return STATUS_SUCCESS; + } + ++static NTSTATUS oss_wow64_release_render_buffer(void *args) ++{ ++ struct ++ { ++ stream_handle stream; ++ UINT32 written_frames; ++ UINT flags; ++ PTR32 spatial_objects; ++ UINT32 spatial_object_count; ++ HRESULT result; ++ } *params32 = args; ++ struct release_render_buffer_params params = ++ { ++ .stream = params32->stream, ++ .written_frames = params32->written_frames, ++ .flags = params32->flags, ++ .spatial_objects = ULongToPtr(params32->spatial_objects), ++ .spatial_object_count = params32->spatial_object_count, ++ }; ++ ++ oss_release_render_buffer(¶ms); ++ params32->result = params.result; ++ return STATUS_SUCCESS; ++} ++ + static NTSTATUS oss_wow64_get_capture_buffer(void *args) + { + struct +@@ -2144,7 +2201,7 @@ const unixlib_entry_t __wine_unix_call_wow64_funcs[] = + oss_reset, + oss_timer_loop, + oss_wow64_get_render_buffer, +- oss_release_render_buffer, ++ oss_wow64_release_render_buffer, + oss_wow64_get_capture_buffer, + oss_release_capture_buffer, + oss_wow64_is_format_supported, +@@ -2170,6 +2227,7 @@ const unixlib_entry_t __wine_unix_call_wow64_funcs[] = + oss_wow64_midi_in_message, + oss_wow64_midi_notify_wait, + oss_wow64_aux_message, ++ oss_not_implemented, + }; + + C_ASSERT(ARRAYSIZE(__wine_unix_call_wow64_funcs) == funcs_count); +diff --git a/dlls/winepulse.drv/pulse.c b/dlls/winepulse.drv/pulse.c +index 7c8d872..0604d3d 100644 +--- a/dlls/winepulse.drv/pulse.c ++++ b/dlls/winepulse.drv/pulse.c +@@ -1137,6 +1137,18 @@ static NTSTATUS pulse_create_stream(void *args) + HRESULT hr; + char *name; + ++ /* mmdevapi spatial streams use a private dry-object transport channel. ++ * Do not expose that channel as a physical speaker on backends which do ++ * not implement the corresponding bed/dry split. */ ++ if (params->spatial) ++ { ++ WARN("Spatial audio transport with %u dynamic objects at endpoint generation %u " ++ "is not supported by the PulseAudio backend.\n", ++ params->spatial_dynamic_objects, params->spatial_endpoint_generation); ++ params->result = AUDCLNT_E_UNSUPPORTED_FORMAT; ++ return STATUS_SUCCESS; ++ } ++ + if (params->share == AUDCLNT_SHAREMODE_EXCLUSIVE) { + params->result = AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED; + return STATUS_SUCCESS; +@@ -1935,6 +1947,11 @@ static NTSTATUS pulse_release_render_buffer(void *args) + UINT32 written_bytes; + BYTE *buffer; + ++ /* PulseAudio rejects spatial streams at creation, so the optional spatial ++ * object-state payload must never be inspected by this backend. */ ++ (void)params->spatial_objects; ++ (void)params->spatial_object_count; ++ + pulse_lock(); + if (!stream->locked || !params->written_frames) + { +@@ -2557,6 +2574,7 @@ const unixlib_entry_t __wine_unix_call_funcs[] = + pulse_not_implemented, + pulse_not_implemented, + pulse_not_implemented, ++ pulse_not_implemented, + }; + + C_ASSERT(ARRAYSIZE(__wine_unix_call_funcs) == funcs_count); +@@ -2612,6 +2630,12 @@ static NTSTATUS pulse_wow64_create_stream(void *args) + EDataFlow flow; + AUDCLNT_SHAREMODE share; + DWORD flags; ++ BOOL spatial; ++ UINT32 spatial_static_mask; ++ UINT32 spatial_dynamic_objects; ++ UINT32 spatial_endpoint_generation; ++ PTR32 spatial_invalidation_event; ++ BOOL spatial_fault_invalidate_on_start; + REFERENCE_TIME duration; + REFERENCE_TIME period; + PTR32 fmt; +@@ -2626,6 +2650,14 @@ static NTSTATUS pulse_wow64_create_stream(void *args) + .flow = params32->flow, + .share = params32->share, + .flags = params32->flags, ++ .spatial = params32->spatial, ++ .spatial_static_mask = params32->spatial_static_mask, ++ .spatial_dynamic_objects = params32->spatial_dynamic_objects, ++ .spatial_endpoint_generation = params32->spatial_endpoint_generation, ++ .spatial_invalidation_event = ULongToPtr( ++ params32->spatial_invalidation_event), ++ .spatial_fault_invalidate_on_start = ++ params32->spatial_fault_invalidate_on_start, + .duration = params32->duration, + .period = params32->period, + .fmt = ULongToPtr(params32->fmt), +@@ -2677,6 +2709,31 @@ static NTSTATUS pulse_wow64_get_render_buffer(void *args) + return STATUS_SUCCESS; + } + ++static NTSTATUS pulse_wow64_release_render_buffer(void *args) ++{ ++ struct ++ { ++ stream_handle stream; ++ UINT32 written_frames; ++ UINT flags; ++ PTR32 spatial_objects; ++ UINT32 spatial_object_count; ++ HRESULT result; ++ } *params32 = args; ++ struct release_render_buffer_params params = ++ { ++ .stream = params32->stream, ++ .written_frames = params32->written_frames, ++ .flags = params32->flags, ++ .spatial_objects = ULongToPtr(params32->spatial_objects), ++ .spatial_object_count = params32->spatial_object_count, ++ }; ++ ++ pulse_release_render_buffer(¶ms); ++ params32->result = params.result; ++ return STATUS_SUCCESS; ++} ++ + static NTSTATUS pulse_wow64_get_capture_buffer(void *args) + { + struct +@@ -3028,7 +3085,7 @@ const unixlib_entry_t __wine_unix_call_wow64_funcs[] = + pulse_reset, + pulse_timer_loop, + pulse_wow64_get_render_buffer, +- pulse_release_render_buffer, ++ pulse_wow64_release_render_buffer, + pulse_wow64_get_capture_buffer, + pulse_release_capture_buffer, + pulse_wow64_is_format_supported, +@@ -3054,6 +3111,7 @@ const unixlib_entry_t __wine_unix_call_wow64_funcs[] = + pulse_not_implemented, + pulse_not_implemented, + pulse_not_implemented, ++ pulse_not_implemented, + }; + + C_ASSERT(ARRAYSIZE(__wine_unix_call_wow64_funcs) == funcs_count); diff --git a/patches/wine11/0005-spatial-audio-coreaudio.patch b/patches/wine11/0005-spatial-audio-coreaudio.patch new file mode 100644 index 0000000..e4a7e2b --- /dev/null +++ b/patches/wine11/0005-spatial-audio-coreaudio.patch @@ -0,0 +1,3392 @@ +From: jungwuk-ryu +Subject: [MGU] spatial audio coreaudio +Origin: https://github.com/jungwuk-ryu/switchyard-wine +Source-revision: ba57a08921dfe8f3a4281692b040cd2fa5acd94e +License: LGPL-2.1-or-later + +Backported to CodeWeavers CrossOver 26.3.0 FOSS sources. +Port adaptations retain CrossOver HALOutput and PE-owned timer threads. +Apply the complete ordered patch set; shared Unix ABI and all audio tables +must be updated together. See docs/SPATIAL_AUDIO.md for provenance. + +Native output adaptation preserves CoreAudio descriptions, coordinates and +channel order, including 5.1.2 top-middle speakers; generation and listeners +track native layout changes. + +diff --git a/dlls/winecoreaudio.drv/Makefile.in b/dlls/winecoreaudio.drv/Makefile.in +index 62f32b1..216586e 100644 +--- a/dlls/winecoreaudio.drv/Makefile.in ++++ b/dlls/winecoreaudio.drv/Makefile.in +@@ -3,6 +3,7 @@ UNIXLIB = winecoreaudio.so + IMPORTS = uuid ole32 user32 advapi32 + DELAYIMPORTS = winmm + UNIX_LIBS = $(COREAUDIO_LIBS) -framework AppKit $(AVFOUNDATION_LIBS) ++UNIX_CFLAGS = -fblocks + + SOURCES = \ + authorization.m \ +diff --git a/dlls/winecoreaudio.drv/coreaudio.c b/dlls/winecoreaudio.drv/coreaudio.c +index 3199887..aaa6fff 100644 +--- a/dlls/winecoreaudio.drv/coreaudio.c ++++ b/dlls/winecoreaudio.drv/coreaudio.c +@@ -33,6 +33,7 @@ + + #include + #include ++#include + #include + #include + #include +@@ -41,6 +42,11 @@ + #include + #include + #include ++#include ++#include ++#include ++#include ++#include + #include + + #include +@@ -65,6 +71,7 @@ + #include "mmdeviceapi.h" + #include "initguid.h" + #include "audioclient.h" ++#include "spatialaudioclient.h" + #include "wine/debug.h" + #include "wine/unixlib.h" + +@@ -78,18 +85,55 @@ + WINE_DEFAULT_DEBUG_CHANNEL(coreaudio); + WINE_DECLARE_DEBUG_CHANNEL(winediag); + ++#define SPATIAL_AUDIO_MAX_DYNAMIC_OBJECTS 64 ++#define SPATIAL_AUDIO_PROFILE_SAMPLES 65536 ++#define SPATIAL_AUDIO_CACHE_LINE_SIZE 64 ++ ++struct coreaudio_stream; ++ ++struct spatial_input_context ++{ ++ struct coreaudio_stream *stream; ++ UINT32 slot; ++}; ++ ++struct coreaudio_spatial_object_state ++{ ++ float azimuth; ++ float elevation; ++ float distance; ++ UINT32 active_frames; ++}; ++ + struct coreaudio_stream + { + os_unfair_lock lock; + AudioComponentInstance unit; ++ AudioComponentInstance spatial_unit; + AudioConverterRef converter; + AudioStreamBasicDescription dev_desc; /* audio unit format, not necessarily the same as fmt */ + AudioDeviceID dev_id; ++ BOOL unit_initialized; ++ BOOL spatial_unit_initialized; ++ BOOL unit_started; ++ BOOL spatial_volumes_are_unity; ++ BOOL spatial_resetting; ++ BOOL spatial; ++ UINT32 spatial_static_mask; ++ UINT32 spatial_dynamic_objects; ++ UINT32 spatial_endpoint_generation; ++ BOOL spatial_native_output; + + EDataFlow flow; + DWORD flags; + AUDCLNT_SHAREMODE share; + HANDLE event; ++ HANDLE spatial_invalidation_event; ++ semaphore_t event_semaphore; ++ BOOL event_semaphore_created; ++ semaphore_t callback_drain_semaphore; ++ BOOL callback_drain_semaphore_created; ++ UINT32 event_pending; + + BOOL playing, please_quit; + REFERENCE_TIME period; +@@ -101,14 +145,83 @@ struct coreaudio_stream + UINT64 written_frames; + INT32 getbuf_last; + WAVEFORMATEX *fmt; ++ UINT32 *spatial_volume_bits; ++ float *spatial_bed_buffer; ++ float *spatial_dry_buffer; ++ float *spatial_dry_delay_buffer; ++ float *spatial_dynamic_buffer; ++ struct spatial_input_context *spatial_input_contexts; ++ AudioUnitParameterEvent *spatial_parameter_events; ++ struct coreaudio_spatial_object_state *spatial_object_states; ++ UINT64 *spatial_metadata_sequences; ++ UINT32 spatial_metadata_capacity; ++ UINT32 spatial_parameter_event_capacity; ++ UINT32 spatial_dynamic_channel; ++ UINT32 spatial_render_frames; ++ UINT64 spatial_read_frames __attribute__((aligned(64))); ++ char spatial_read_frames_padding[SPATIAL_AUDIO_CACHE_LINE_SIZE - ++ sizeof(UINT64)]; ++ UINT64 spatial_write_frames __attribute__((aligned(64))); ++ char spatial_write_frames_padding[SPATIAL_AUDIO_CACHE_LINE_SIZE - ++ sizeof(UINT64)]; ++ UINT32 spatial_callbacks_inflight __attribute__((aligned(64))); ++ UINT32 spatial_callback_active; ++ char spatial_callback_padding[SPATIAL_AUDIO_CACHE_LINE_SIZE - ++ 2 * sizeof(UINT32)]; ++ UINT32 device_callbacks_inflight __attribute__((aligned(64))); ++ char device_callback_padding[SPATIAL_AUDIO_CACHE_LINE_SIZE - ++ sizeof(UINT32)]; ++ BOOL shutting_down; ++ BOOL invalidated; ++ UINT32 device_listener_mask; ++ dispatch_queue_t device_listener_queue; ++ AudioObjectPropertyListenerBlock device_listener; ++ dispatch_block_t device_listener_detach; ++ UINT64 underruns; ++ UINT64 overruns; ++ UINT64 reentrant_callbacks; ++ BOOL profile_callbacks; ++ BOOL fault_invalidate_on_start; ++ UINT32 callback_timing_count; ++ UINT64 *callback_timings; ++ UINT32 spatial_bed_channels; ++ UINT32 spatial_dry_capacity; ++ UINT32 spatial_dry_channel; ++ UINT32 spatial_dry_delay_frames; ++ UINT32 spatial_dry_delay_pos; ++ UINT32 spatial_dry_output[2]; ++ UINT32 spatial_dry_output_count; + BYTE *local_buffer, *cap_buffer, *wrap_buffer, *resamp_buffer, *tmp_buffer; + }; + +-static const REFERENCE_TIME def_period = 100000; +-static const REFERENCE_TIME min_period = 50000; + + static ULONG_PTR zero_bits = 0; + ++static const AudioObjectPropertyAddress spatial_device_properties[] = ++{ ++ {kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, ++ kAudioObjectPropertyElementMain}, ++ {kAudioDevicePropertyDeviceHasChanged, kAudioObjectPropertyScopeGlobal, ++ kAudioObjectPropertyElementMain}, ++ {kAudioDevicePropertyBufferFrameSize, kAudioObjectPropertyScopeGlobal, ++ kAudioObjectPropertyElementMain}, ++ {kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, ++ kAudioObjectPropertyElementMain}, ++ {kAudioDevicePropertyStreamConfiguration, kAudioDevicePropertyScopeOutput, ++ kAudioObjectPropertyElementMain}, ++ {kAudioDevicePropertyIOStoppedAbnormally, kAudioObjectPropertyScopeGlobal, ++ kAudioObjectPropertyElementMain}, ++ {kAudioDevicePropertyPreferredChannelLayout, kAudioDevicePropertyScopeOutput, ++ kAudioObjectPropertyElementMain}, ++}; ++ ++static NTSTATUS unix_get_mix_format(void *args); ++static AudioDeviceID dev_id_from_device(const char *device); ++static UINT ca_channel_layout_to_channel_mask(const AudioChannelLayout *layout); ++static UINT32 count_channel_mask_bits(DWORD mask); ++static void wait_for_spatial_callbacks(struct coreaudio_stream *stream); ++static void wait_for_device_callbacks(struct coreaudio_stream *stream); ++ + static NTSTATUS unix_not_implemented(void *args) + { + return STATUS_SUCCESS; +@@ -427,6 +540,702 @@ static OSStatus ca_render_cb(void *user, AudioUnitRenderActionFlags *flags, + return noErr; + } + ++static float load_spatial_volume(struct coreaudio_stream *stream, UINT32 channel) ++{ ++ UINT32 bits = __atomic_load_n(&stream->spatial_volume_bits[channel], ++ __ATOMIC_RELAXED); ++ float volume; ++ ++ memcpy(&volume, &bits, sizeof(volume)); ++ return volume; ++} ++ ++static void spatial_position_to_parameters( ++ const struct spatial_audio_object_state *source, ++ struct coreaudio_spatial_object_state *target) ++{ ++ double horizontal, radius; ++ ++ horizontal = hypot((double)source->x, (double)source->z); ++ radius = hypot(horizontal, (double)source->y); ++ if (!isfinite(horizontal) || !isfinite(radius)) ++ { ++ target->azimuth = target->elevation = target->distance = 0.0f; ++ target->active_frames = 0; ++ return; ++ } ++ ++ target->azimuth = atan2((double)source->x, -(double)source->z) * ++ (180.0 / M_PI); ++ target->elevation = atan2((double)source->y, horizontal) * ++ (180.0 / M_PI); ++ target->distance = min(radius, 10000.0); ++ target->active_frames = source->active_frames; ++} ++ ++static BOOL append_spatial_parameter_event(struct coreaudio_stream *stream, ++ UINT32 *event_count, UINT32 slot, AudioUnitParameterID parameter, ++ UINT32 offset, float value) ++{ ++ AudioUnitParameterEvent *event; ++ ++ if (*event_count >= stream->spatial_parameter_event_capacity) ++ return FALSE; ++ event = &stream->spatial_parameter_events[(*event_count)++]; ++ event->scope = kAudioUnitScope_Input; ++ event->element = slot + 1; ++ event->parameter = parameter; ++ event->eventType = kParameterEvent_Immediate; ++ event->eventValues.immediate.bufferOffset = offset; ++ event->eventValues.immediate.value = value; ++ return TRUE; ++} ++ ++static OSStatus schedule_spatial_positions(struct coreaudio_stream *stream, ++ UINT64 read_frame, UINT32 frames) ++{ ++ UINT32 event_count = 0, offset = 0; ++ ++ while (offset < frames) ++ { ++ UINT64 absolute = read_frame + offset; ++ UINT64 sequence = absolute / stream->period_frames; ++ UINT32 record = sequence % stream->spatial_metadata_capacity; ++ UINT32 next = min(frames, offset + stream->period_frames - ++ absolute % stream->period_frames); ++ const struct coreaudio_spatial_object_state *states; ++ UINT32 slot; ++ ++ if (__atomic_load_n(&stream->spatial_metadata_sequences[record], ++ __ATOMIC_ACQUIRE) != sequence) ++ return kAudio_ParamError; ++ states = stream->spatial_object_states + ++ (size_t)record * stream->spatial_dynamic_objects; ++ ++ for (slot = 0; slot < stream->spatial_dynamic_objects; ++slot) ++ { ++ const struct coreaudio_spatial_object_state *state = &states[slot]; ++ ++ if (!append_spatial_parameter_event(stream, &event_count, slot, ++ kSpatialMixerParam_Azimuth, offset, state->azimuth) || ++ !append_spatial_parameter_event(stream, &event_count, slot, ++ kSpatialMixerParam_Elevation, offset, state->elevation) || ++ !append_spatial_parameter_event(stream, &event_count, slot, ++ kSpatialMixerParam_Distance, offset, state->distance)) ++ return kAudio_ParamError; ++ } ++ offset = next; ++ } ++ ++ return event_count ? AudioUnitScheduleParameters(stream->spatial_unit, ++ stream->spatial_parameter_events, event_count) : noErr; ++} ++ ++static void signal_spatial_event(struct coreaudio_stream *stream) ++{ ++ UINT32 expected = 0; ++ ++ if (stream->event_semaphore_created && ++ __atomic_compare_exchange_n(&stream->event_pending, &expected, 1, ++ FALSE, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) ++ semaphore_signal(stream->event_semaphore); ++} ++ ++static void invalidate_spatial_stream_rt(struct coreaudio_stream *stream) ++{ ++ __atomic_store_n(&stream->invalidated, TRUE, __ATOMIC_RELEASE); ++ signal_spatial_event(stream); ++} ++ ++static void record_spatial_callback_time(struct coreaudio_stream *stream, ++ UINT64 started) ++{ ++ UINT32 index; ++ ++ if (!started) ++ return; ++ index = __atomic_fetch_add(&stream->callback_timing_count, 1, ++ __ATOMIC_RELAXED); ++ if (index < SPATIAL_AUDIO_PROFILE_SAMPLES) ++ stream->callback_timings[index] = mach_absolute_time() - started; ++} ++ ++static void spatial_device_property_changed(struct coreaudio_stream *stream, ++ UInt32 count, const AudioObjectPropertyAddress addresses[]) ++{ ++ UInt32 i; ++ ++ __atomic_add_fetch(&stream->device_callbacks_inflight, 1, ++ __ATOMIC_ACQUIRE); ++ if (__atomic_load_n(&stream->shutting_down, __ATOMIC_ACQUIRE)) ++ goto done; ++ ++ for (i = 0; i < count; ++i) ++ { ++ __atomic_store_n(&stream->invalidated, TRUE, __ATOMIC_RELEASE); ++ } ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ { ++ if (stream->spatial_invalidation_event) ++ NtSetEvent(stream->spatial_invalidation_event, NULL); ++ signal_spatial_event(stream); ++ } ++done: ++ __atomic_sub_fetch(&stream->device_callbacks_inflight, 1, ++ __ATOMIC_RELEASE); ++} ++ ++static HRESULT register_spatial_device_listeners(struct coreaudio_stream *stream) ++{ ++ __block struct coreaudio_stream *target = stream; ++ AudioObjectPropertyListenerBlock listener; ++ dispatch_block_t detach; ++ BOOL topology_listener = FALSE; ++ UINT32 i; ++ OSStatus sc; ++ ++ if (!(stream->device_listener_queue = dispatch_queue_create( ++ "org.winehq.wine.coreaudio.spatial-device", DISPATCH_QUEUE_SERIAL))) ++ return E_OUTOFMEMORY; ++ listener = Block_copy(^(UInt32 count, ++ const AudioObjectPropertyAddress addresses[]) ++ { ++ struct coreaudio_stream *current = target; ++ ++ if (current) ++ spatial_device_property_changed(current, count, addresses); ++ }); ++ detach = Block_copy(^{ target = NULL; }); ++ if (!listener || !detach) ++ { ++ if (listener) Block_release(listener); ++ if (detach) Block_release(detach); ++ return E_OUTOFMEMORY; ++ } ++ stream->device_listener = listener; ++ stream->device_listener_detach = detach; ++ ++ for (i = 0; i < ARRAY_SIZE(spatial_device_properties); ++i) ++ { ++ /* Mono/stereo devices may omit preferred layout entirely. When ++ * present, changes to labels/order must invalidate the stream even ++ * if the number of channels is unchanged. */ ++ if (i == 6 && !AudioObjectHasProperty(stream->dev_id, &spatial_device_properties[i])) ++ continue; ++ sc = AudioObjectAddPropertyListenerBlock(stream->dev_id, ++ &spatial_device_properties[i], stream->device_listener_queue, ++ stream->device_listener); ++ if (sc == noErr) ++ { ++ stream->device_listener_mask |= 1u << i; ++ if (i == 1 || i == 4) ++ topology_listener = TRUE; ++ } ++ else if (i == 0 || i == 2 || i == 3 || i == 5 || i == 6) ++ { ++ WARN("Failed to register required spatial device listener %u: %x.\n", ++ i, (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ } ++ if (!topology_listener) ++ { ++ WARN("Failed to register a spatial topology-change listener.\n"); ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ } ++ return S_OK; ++} ++ ++static void dispatch_barrier_noop(void *context) ++{ ++ (void)context; ++} ++ ++static void dispatch_invoke_block(void *context) ++{ ++ ((dispatch_block_t)context)(); ++} ++ ++static void unregister_spatial_device_listeners(struct coreaudio_stream *stream) ++{ ++ UINT32 i; ++ OSStatus sc; ++ ++ if (stream->device_listener) ++ for (i = 0; i < ARRAY_SIZE(spatial_device_properties); ++i) ++ if (stream->device_listener_mask & (1u << i)) ++ { ++ sc = AudioObjectRemovePropertyListenerBlock(stream->dev_id, ++ &spatial_device_properties[i], ++ stream->device_listener_queue, ++ stream->device_listener); ++ if (sc != noErr) ++ WARN("Failed to remove spatial device listener %u: %x.\n", ++ i, (int)sc); ++ } ++ stream->device_listener_mask = 0; ++ /* Detach the captured stream on the listener's serial queue. Even if a ++ * dead device refuses listener removal, any callback retained by ++ * CoreAudio after this barrier observes NULL instead of freed storage. */ ++ if (stream->device_listener_queue && stream->device_listener_detach) ++ dispatch_sync_f(stream->device_listener_queue, ++ stream->device_listener_detach, dispatch_invoke_block); ++ else if (stream->device_listener_queue) ++ dispatch_sync_f(stream->device_listener_queue, NULL, ++ dispatch_barrier_noop); ++ wait_for_device_callbacks(stream); ++ if (stream->device_listener) ++ { ++ Block_release(stream->device_listener); ++ stream->device_listener = NULL; ++ } ++ if (stream->device_listener_detach) ++ { ++ Block_release(stream->device_listener_detach); ++ stream->device_listener_detach = NULL; ++ } ++ if (stream->device_listener_queue) ++ { ++ dispatch_release(stream->device_listener_queue); ++ stream->device_listener_queue = NULL; ++ } ++} ++ ++static HRESULT validate_spatial_device_listener_capability(AudioDeviceID dev_id) ++{ ++ struct coreaudio_stream probe = {0}; ++ HRESULT hr; ++ ++ probe.dev_id = dev_id; ++ hr = register_spatial_device_listeners(&probe); ++ unregister_spatial_device_listeners(&probe); ++ return hr; ++} ++ ++/* Split the private interleaved transport exactly once for each output slice. ++ * The output callback is the sole ring consumer, so no callback-side lock is ++ * needed. The producer publishes metadata before the matching write cursor. */ ++static OSStatus ca_prepare_spatial_inputs(struct coreaudio_stream *stream, ++ UInt32 nframes, UINT64 *consumed_read_frame, UINT32 *consumed_frames) ++{ ++ const struct coreaudio_spatial_object_state * const object_states = ++ stream->spatial_object_states; ++ const UINT64 * const metadata_sequences = ++ stream->spatial_metadata_sequences; ++ float * const dynamic_buffer = stream->spatial_dynamic_buffer; ++ const struct coreaudio_spatial_object_state *states = NULL; ++ UINT64 read_frame, write_frame; ++ UINT64 sequence = 0; ++ const UINT32 metadata_capacity = stream->spatial_metadata_capacity; ++ const UINT32 dynamic_objects = stream->spatial_dynamic_objects; ++ UINT32 bed_channel, channel, frame, in_quantum = 0, record; ++ UINT32 source_frame, to_copy_frames; ++ BOOL unity, playing; ++ ++ if (nframes > stream->spatial_dry_capacity) ++ return kAudio_ParamError; ++ if (dynamic_objects && (!metadata_capacity || !metadata_sequences || ++ !object_states || !dynamic_buffer)) ++ return kAudio_ParamError; ++ stream->spatial_render_frames = nframes; ++ ++ read_frame = __atomic_load_n(&stream->spatial_read_frames, ++ __ATOMIC_RELAXED); ++ write_frame = __atomic_load_n(&stream->spatial_write_frames, ++ __ATOMIC_ACQUIRE); ++ playing = __atomic_load_n(&stream->playing, __ATOMIC_ACQUIRE) && ++ !__atomic_load_n(&stream->spatial_resetting, __ATOMIC_ACQUIRE) && ++ !__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE); ++ to_copy_frames = playing && write_frame >= read_frame ? ++ min((UINT64)nframes, write_frame - read_frame) : 0; ++ if (playing && to_copy_frames < nframes) ++ __atomic_add_fetch(&stream->underruns, 1, __ATOMIC_RELAXED); ++ unity = __atomic_load_n(&stream->spatial_volumes_are_unity, ++ __ATOMIC_ACQUIRE); ++ source_frame = read_frame % stream->bufsize_frames; ++ if (dynamic_objects && to_copy_frames) ++ { ++ sequence = read_frame / stream->period_frames; ++ in_quantum = read_frame - sequence * stream->period_frames; ++ record = sequence % metadata_capacity; ++ if (__atomic_load_n(&metadata_sequences[record], ++ __ATOMIC_ACQUIRE) == sequence) ++ states = object_states + ++ (size_t)record * dynamic_objects; ++ } ++ ++ for (frame = 0; frame < to_copy_frames; ++frame) ++ { ++ const float *source; ++ UINT32 slot; ++ ++ source = (const float *)stream->local_buffer + ++ (size_t)source_frame * stream->fmt->nChannels; ++ ++ bed_channel = 0; ++ for (channel = 0; channel < stream->spatial_dynamic_channel; ++channel) ++ { ++ float sample = source[channel]; ++ ++ if (!unity) ++ sample *= load_spatial_volume(stream, channel); ++ if (channel == stream->spatial_dry_channel) ++ stream->spatial_dry_buffer[frame] = sample; ++ else ++ stream->spatial_bed_buffer[frame * ++ stream->spatial_bed_channels + bed_channel++] = sample; ++ } ++ ++ for (slot = 0; slot < dynamic_objects; ++slot) ++ { ++ float sample = source[stream->spatial_dynamic_channel + slot]; ++ ++ if (!states || in_quantum >= states[slot].active_frames) ++ sample = 0.0f; ++ else if (!unity) ++ sample *= load_spatial_volume(stream, ++ stream->spatial_dynamic_channel + slot); ++ dynamic_buffer[(size_t)slot * ++ stream->spatial_dry_capacity + frame] = sample; ++ } ++ ++ if (++source_frame == stream->bufsize_frames) ++ source_frame = 0; ++ if (dynamic_objects && ++in_quantum == stream->period_frames) ++ { ++ in_quantum = 0; ++ ++sequence; ++ record = sequence % metadata_capacity; ++ states = NULL; ++ if (frame + 1 < to_copy_frames && ++ __atomic_load_n( ++ &metadata_sequences[record], ++ __ATOMIC_ACQUIRE) == sequence) ++ states = object_states + ++ (size_t)record * dynamic_objects; ++ } ++ } ++ ++ if (nframes > to_copy_frames) ++ { ++ memset(stream->spatial_bed_buffer + (size_t)to_copy_frames * ++ stream->spatial_bed_channels, 0, (size_t)(nframes - ++ to_copy_frames) * stream->spatial_bed_channels * sizeof(float)); ++ memset(stream->spatial_dry_buffer + to_copy_frames, 0, ++ (nframes - to_copy_frames) * sizeof(float)); ++ for (channel = 0; channel < dynamic_objects; ++channel) ++ memset(dynamic_buffer + (size_t)channel * ++ stream->spatial_dry_capacity + to_copy_frames, 0, ++ (nframes - to_copy_frames) * sizeof(float)); ++ } ++ ++ if (dynamic_objects && to_copy_frames && ++ schedule_spatial_positions(stream, read_frame, to_copy_frames) != noErr) ++ { ++ __atomic_store_n(&stream->invalidated, TRUE, __ATOMIC_RELEASE); ++ signal_spatial_event(stream); ++ return kAudio_ParamError; ++ } ++ *consumed_read_frame = read_frame; ++ *consumed_frames = to_copy_frames; ++ return noErr; ++} ++ ++static void delay_spatial_dry_input(struct coreaudio_stream *stream, ++ UInt32 nframes) ++{ ++ UINT32 frame, pos; ++ ++ if (!stream->spatial_dry_delay_frames) ++ return; ++ pos = stream->spatial_dry_delay_pos; ++ for (frame = 0; frame < nframes; ++frame) ++ { ++ float sample = stream->spatial_dry_buffer[frame]; ++ ++ stream->spatial_dry_buffer[frame] = ++ stream->spatial_dry_delay_buffer[pos]; ++ stream->spatial_dry_delay_buffer[pos] = sample; ++ if (++pos == stream->spatial_dry_delay_frames) ++ pos = 0; ++ } ++ stream->spatial_dry_delay_pos = pos; ++} ++ ++static void commit_spatial_inputs(struct coreaudio_stream *stream, ++ UINT64 read_frame, UINT32 frames) ++{ ++ UINT64 write_frame, queued_frames; ++ ++ if (!frames) ++ return; ++ read_frame += frames; ++ __atomic_store_n(&stream->spatial_read_frames, read_frame, ++ __ATOMIC_RELEASE); ++ ++ /* CoreAudio may request slices smaller than the Windows update quantum, ++ * especially while its output unit is converting sample rates. Wake the ++ * producer only after an entire quantum fits; otherwise BeginUpdating() ++ * would be woken merely to fail GetBuffer(period_frames). */ ++ write_frame = __atomic_load_n(&stream->spatial_write_frames, ++ __ATOMIC_ACQUIRE); ++ queued_frames = write_frame >= read_frame ? write_frame - read_frame : 0; ++ if (stream->bufsize_frames >= stream->period_frames && ++ queued_frames <= stream->bufsize_frames - stream->period_frames) ++ signal_spatial_event(stream); ++} ++ ++static OSStatus ca_spatial_bed_render_cb(void *user, AudioUnitRenderActionFlags *flags, ++ const AudioTimeStamp *ts, UInt32 bus, UInt32 nframes, AudioBufferList *data) ++{ ++ struct coreaudio_stream *stream = user; ++ UInt32 bytes; ++ ++ (void)flags; ++ (void)ts; ++ (void)bus; ++ ++ if (nframes != stream->spatial_render_frames || ++ nframes > stream->spatial_dry_capacity) ++ return kAudio_ParamError; ++ bytes = nframes * stream->spatial_bed_channels * sizeof(float); ++ ++ if (data->mNumberBuffers != 1 || ++ data->mBuffers[0].mNumberChannels != stream->spatial_bed_channels) ++ return kAudio_ParamError; ++ if (!data->mBuffers[0].mData) ++ { ++ data->mBuffers[0].mData = stream->spatial_bed_buffer; ++ data->mBuffers[0].mDataByteSize = bytes; ++ } ++ else if (data->mBuffers[0].mDataByteSize < bytes) ++ return kAudio_ParamError; ++ else ++ memcpy(data->mBuffers[0].mData, stream->spatial_bed_buffer, bytes); ++ return noErr; ++} ++ ++static OSStatus ca_spatial_dynamic_render_cb(void *user, ++ AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts, UInt32 bus, ++ UInt32 nframes, AudioBufferList *data) ++{ ++ struct spatial_input_context *context = user; ++ struct coreaudio_stream *stream = context->stream; ++ float *source; ++ UInt32 bytes; ++ ++ (void)flags; ++ (void)ts; ++ (void)bus; ++ ++ if (context->slot >= stream->spatial_dynamic_objects || ++ nframes != stream->spatial_render_frames || ++ nframes > stream->spatial_dry_capacity || data->mNumberBuffers != 1 || ++ data->mBuffers[0].mNumberChannels != 1) ++ return kAudio_ParamError; ++ ++ bytes = nframes * sizeof(float); ++ source = stream->spatial_dynamic_buffer + ++ (size_t)context->slot * stream->spatial_dry_capacity; ++ if (!data->mBuffers[0].mData) ++ { ++ data->mBuffers[0].mData = source; ++ data->mBuffers[0].mDataByteSize = bytes; ++ } ++ else if (data->mBuffers[0].mDataByteSize < bytes) ++ return kAudio_ParamError; ++ else ++ memcpy(data->mBuffers[0].mData, source, bytes); ++ return noErr; ++} ++ ++static void mix_spatial_dry_planar(struct coreaudio_stream *stream, ++ UInt32 nframes, AudioBufferList *data) ++{ ++ UINT32 channel, frame; ++ ++ for (channel = 0; channel < stream->spatial_dry_output_count; ++channel) ++ { ++ UINT32 index = stream->spatial_dry_output[channel]; ++ float *output = data->mBuffers[index].mData; ++ ++ for (frame = 0; frame < nframes; ++frame) ++ output[frame] += stream->spatial_dry_buffer[frame]; ++ } ++} ++ ++static OSStatus ca_spatial_render_cb(void *user, AudioUnitRenderActionFlags *flags, ++ const AudioTimeStamp *ts, UInt32 bus, UInt32 nframes, AudioBufferList *data) ++{ ++ struct coreaudio_stream *stream = user; ++ UINT64 consumed_read_frame = 0, started = 0; ++ UINT32 consumed_frames = 0; ++ UINT32 expected = 0; ++ unsigned int i; ++ OSStatus result = noErr; ++ ++ (void)bus; ++ ++ __atomic_add_fetch(&stream->spatial_callbacks_inflight, 1, ++ __ATOMIC_ACQUIRE); ++ if (!__atomic_compare_exchange_n(&stream->spatial_callback_active, ++ &expected, 1, FALSE, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) ++ { ++ __atomic_add_fetch(&stream->reentrant_callbacks, 1, __ATOMIC_RELAXED); ++ result = kAudioUnitErr_CannotDoInCurrentContext; ++ goto done_inflight; ++ } ++ if (stream->profile_callbacks) ++ started = mach_absolute_time(); ++ ++ if (nframes > stream->spatial_dry_capacity || ++ __atomic_load_n(&stream->shutting_down, __ATOMIC_ACQUIRE)) ++ { ++ result = kAudio_ParamError; ++ goto done; ++ } ++ ++ if (!__atomic_load_n(&stream->playing, __ATOMIC_ACQUIRE) || ++ __atomic_load_n(&stream->spatial_resetting, __ATOMIC_ACQUIRE) || ++ __atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ { ++ for (i = 0; i < data->mNumberBuffers; ++i) ++ if (data->mBuffers[i].mData) ++ memset(data->mBuffers[i].mData, 0, data->mBuffers[i].mDataByteSize); ++ goto done; ++ } ++ ++ if ((result = ca_prepare_spatial_inputs(stream, nframes, ++ &consumed_read_frame, &consumed_frames)) != noErr) ++ { ++ for (i = 0; i < data->mNumberBuffers; ++i) ++ if (data->mBuffers[i].mData) ++ memset(data->mBuffers[i].mData, 0, data->mBuffers[i].mDataByteSize); ++ goto done; ++ } ++ ++ if ((result = AudioUnitRender(stream->spatial_unit, flags, ts, 0, nframes, ++ data)) != noErr) ++ goto done; ++ ++ if (data->mNumberBuffers < stream->dev_desc.mChannelsPerFrame) ++ { ++ result = kAudio_ParamError; ++ goto done; ++ } ++ for (i = 0; i < stream->dev_desc.mChannelsPerFrame; ++i) ++ if (!data->mBuffers[i].mData || data->mBuffers[i].mNumberChannels != 1 || ++ data->mBuffers[i].mDataByteSize < nframes * sizeof(float)) ++ { ++ result = kAudio_ParamError; ++ goto done; ++ } ++ ++ delay_spatial_dry_input(stream, nframes); ++ mix_spatial_dry_planar(stream, nframes, data); ++ commit_spatial_inputs(stream, consumed_read_frame, consumed_frames); ++ ++done: ++ __atomic_store_n(&stream->spatial_callback_active, 0, __ATOMIC_RELEASE); ++done_inflight: ++ if (result != noErr && result != kAudioUnitErr_CannotDoInCurrentContext && ++ !__atomic_load_n(&stream->shutting_down, __ATOMIC_ACQUIRE) && ++ !__atomic_load_n(&stream->spatial_resetting, __ATOMIC_ACQUIRE)) ++ invalidate_spatial_stream_rt(stream); ++ record_spatial_callback_time(stream, started); ++ if (!__atomic_sub_fetch(&stream->spatial_callbacks_inflight, 1, ++ __ATOMIC_RELEASE) && stream->callback_drain_semaphore_created && ++ (__atomic_load_n(&stream->shutting_down, __ATOMIC_ACQUIRE) || ++ __atomic_load_n(&stream->spatial_resetting, __ATOMIC_ACQUIRE))) ++ semaphore_signal(stream->callback_drain_semaphore); ++ return result; ++} ++ ++static OSStatus ca_native_spatial_render_cb(void *user, AudioUnitRenderActionFlags *flags, ++ const AudioTimeStamp *ts, UInt32 bus, UInt32 nframes, AudioBufferList *data) ++{ ++ struct coreaudio_stream *stream = user; ++ UINT64 consumed_read_frame = 0, started = 0; ++ UINT32 consumed_frames = 0; ++ UINT32 expected = 0; ++ float *output; ++ UINT32 channel, frame; ++ UInt32 bytes; ++ OSStatus result = noErr; ++ ++ (void)flags; ++ (void)ts; ++ (void)bus; ++ ++ __atomic_add_fetch(&stream->spatial_callbacks_inflight, 1, ++ __ATOMIC_ACQUIRE); ++ if (!__atomic_compare_exchange_n(&stream->spatial_callback_active, ++ &expected, 1, FALSE, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) ++ { ++ __atomic_add_fetch(&stream->reentrant_callbacks, 1, __ATOMIC_RELAXED); ++ result = kAudioUnitErr_CannotDoInCurrentContext; ++ goto done_inflight; ++ } ++ if (stream->profile_callbacks) ++ started = mach_absolute_time(); ++ if (nframes > stream->spatial_dry_capacity || ++ __atomic_load_n(&stream->shutting_down, __ATOMIC_ACQUIRE)) ++ { ++ result = kAudio_ParamError; ++ goto done; ++ } ++ bytes = nframes * stream->spatial_bed_channels * sizeof(float); ++ ++ if (data->mNumberBuffers != 1 || ++ data->mBuffers[0].mNumberChannels != stream->spatial_bed_channels) ++ { ++ result = kAudio_ParamError; ++ goto done; ++ } ++ if (!data->mBuffers[0].mData) ++ { ++ data->mBuffers[0].mData = stream->spatial_bed_buffer; ++ data->mBuffers[0].mDataByteSize = bytes; ++ } ++ else if (data->mBuffers[0].mDataByteSize < bytes) ++ { ++ result = kAudio_ParamError; ++ goto done; ++ } ++ ++ output = data->mBuffers[0].mData; ++ if ((result = ca_prepare_spatial_inputs(stream, nframes, ++ &consumed_read_frame, &consumed_frames)) != noErr) ++ goto done; ++ if (output != stream->spatial_bed_buffer) ++ memcpy(output, stream->spatial_bed_buffer, bytes); ++ ++ delay_spatial_dry_input(stream, nframes); ++ for (channel = 0; channel < stream->spatial_dry_output_count; ++channel) ++ { ++ UINT32 index = stream->spatial_dry_output[channel]; ++ ++ for (frame = 0; frame < nframes; ++frame) ++ output[frame * stream->spatial_bed_channels + index] += ++ stream->spatial_dry_buffer[frame]; ++ } ++ commit_spatial_inputs(stream, consumed_read_frame, consumed_frames); ++done: ++ __atomic_store_n(&stream->spatial_callback_active, 0, __ATOMIC_RELEASE); ++done_inflight: ++ if (result != noErr && result != kAudioUnitErr_CannotDoInCurrentContext && ++ !__atomic_load_n(&stream->shutting_down, __ATOMIC_ACQUIRE) && ++ !__atomic_load_n(&stream->spatial_resetting, __ATOMIC_ACQUIRE)) ++ invalidate_spatial_stream_rt(stream); ++ record_spatial_callback_time(stream, started); ++ if (!__atomic_sub_fetch(&stream->spatial_callbacks_inflight, 1, ++ __ATOMIC_RELEASE) && stream->callback_drain_semaphore_created && ++ (__atomic_load_n(&stream->shutting_down, __ATOMIC_ACQUIRE) || ++ __atomic_load_n(&stream->spatial_resetting, __ATOMIC_ACQUIRE))) ++ semaphore_signal(stream->callback_drain_semaphore); ++ return result; ++} ++ + static void ca_wrap_buffer(BYTE *dst, UINT32 dst_offs, UINT32 dst_bytes, + BYTE *src, UINT32 src_bytes) + { +@@ -552,10 +1361,92 @@ static AudioComponentInstance get_audiounit(EDataFlow dataflow, AudioDeviceID ad + AudioComponentInstanceDispose(unit); + return NULL; + } ++ return unit; ++} ++ ++static AudioComponentInstance get_spatial_mixer(void) ++{ ++ AudioComponentDescription desc = {0}; ++ AudioComponentInstance unit; ++ AudioComponent component; ++ OSStatus sc; ++ ++ desc.componentType = kAudioUnitType_Mixer; ++ desc.componentSubType = kAudioUnitSubType_SpatialMixer; ++ desc.componentManufacturer = kAudioUnitManufacturer_Apple; ++ ++ if (!(component = AudioComponentFindNext(NULL, &desc))) ++ { ++ WARN("Spatial mixer AudioComponent is unavailable.\n"); ++ return NULL; ++ } ++ ++ if ((sc = AudioComponentInstanceNew(component, &unit)) != noErr) ++ { ++ WARN("Failed to create spatial mixer: %x.\n", (int)sc); ++ return NULL; ++ } + + return unit; + } + ++static UINT32 get_device_spatial_output_type(AudioDeviceID dev_id) ++{ ++ AudioObjectPropertyAddress addr = ++ { ++ .mSelector = kAudioDevicePropertyStreams, ++ .mScope = kAudioDevicePropertyScopeOutput, ++ .mElement = kAudioObjectPropertyElementMain, ++ }; ++ AudioStreamID *streams = NULL; ++ UInt32 transport, size, count, i; ++ BOOL speaker = FALSE; ++ OSStatus sc; ++ ++ sc = AudioObjectGetPropertyDataSize(dev_id, &addr, 0, NULL, &size); ++ if (sc == noErr && (streams = malloc(size))) ++ { ++ sc = AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, streams); ++ count = sc == noErr ? size / sizeof(*streams) : 0; ++ ++ addr.mSelector = kAudioStreamPropertyTerminalType; ++ addr.mScope = kAudioObjectPropertyScopeGlobal; ++ for (i = 0; i < count; ++i) ++ { ++ UInt32 terminal; ++ ++ size = sizeof(terminal); ++ if (AudioObjectGetPropertyData(streams[i], &addr, 0, NULL, &size, &terminal) != noErr) ++ continue; ++ if (terminal == kAudioStreamTerminalTypeHeadphones) ++ { ++ free(streams); ++ return kSpatialMixerOutputType_Headphones; ++ } ++ if (terminal == kAudioStreamTerminalTypeSpeaker) ++ speaker = TRUE; ++ } ++ } ++ free(streams); ++ ++ addr.mSelector = kAudioDevicePropertyTransportType; ++ addr.mScope = kAudioObjectPropertyScopeGlobal; ++ size = sizeof(transport); ++ if (AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, &transport) != noErr) ++ transport = kAudioDeviceTransportTypeUnknown; ++ ++ if (transport == kAudioDeviceTransportTypeBluetooth || ++ transport == kAudioDeviceTransportTypeBluetoothLE) ++ return kSpatialMixerOutputType_Headphones; ++ if (speaker) ++ return transport == kAudioDeviceTransportTypeBuiltIn ++ ? kSpatialMixerOutputType_BuiltInSpeakers ++ : kSpatialMixerOutputType_ExternalSpeakers; ++ if (transport == kAudioDeviceTransportTypeBuiltIn) ++ return kSpatialMixerOutputType_BuiltInSpeakers; ++ return kSpatialMixerOutputType_ExternalSpeakers; ++} ++ + static void dump_adesc(const char *aux, AudioStreamBasicDescription *desc) + { + TRACE("%s: mSampleRate: %f\n", aux, desc->mSampleRate); +@@ -692,17 +1583,991 @@ static HRESULT ca_setup_audiounit(EDataFlow dataflow, AudioComponentInstance uni + return S_OK; + } + +-static AudioDeviceID dev_id_from_device(const char *device) ++static HRESULT get_device_mix_format(const char *device, WAVEFORMATEXTENSIBLE *format) + { +- AudioDeviceID id; +- CFStringRef uid; +- UInt32 size; +- OSStatus sc; +- const AudioObjectPropertyAddress addr = ++ AudioObjectPropertyAddress addr = + { +- .mScope = kAudioObjectPropertyScopeGlobal, ++ .mSelector = kAudioDevicePropertyPreferredChannelLayout, ++ .mScope = kAudioDevicePropertyScopeOutput, + .mElement = kAudioObjectPropertyElementMain, +- .mSelector = kAudioHardwarePropertyTranslateUIDToDevice, ++ }; ++ AudioChannelLayout *expanded = NULL, *layout = NULL, *original_layout = NULL; ++ const AudioDeviceID dev_id = dev_id_from_device(device); ++ AudioChannelLayoutTag tag; ++ DWORD mask = 0; ++ UInt32 channels = 0, expanded_size, size; ++ OSStatus sc; ++ ++ memset(format, 0, sizeof(*format)); ++ ++ sc = AudioObjectGetPropertyDataSize(dev_id, &addr, 0, NULL, &size); ++ if (sc != noErr || !(layout = malloc(size))) ++ goto fallback; ++ original_layout = layout; ++ sc = AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, layout); ++ if (sc != noErr) ++ goto fallback; ++ ++ if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) ++ { ++ mask = layout->mChannelBitmap; ++ channels = count_channel_mask_bits(mask); ++ } ++ else ++ { ++ if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions) ++ { ++ tag = layout->mChannelLayoutTag; ++ sc = AudioFormatGetPropertyInfo(kAudioFormatProperty_ChannelLayoutForTag, ++ sizeof(tag), &tag, &expanded_size); ++ if (sc != noErr || !(expanded = malloc(expanded_size))) ++ goto fallback; ++ sc = AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag, ++ sizeof(tag), &tag, &expanded_size, expanded); ++ if (sc != noErr || ++ expanded->mChannelLayoutTag != ++ kAudioChannelLayoutTag_UseChannelDescriptions) ++ goto fallback; ++ layout = expanded; ++ } ++ ++ channels = layout->mNumberChannelDescriptions; ++ mask = ca_channel_layout_to_channel_mask(layout); ++ } ++ ++ if (!channels || count_channel_mask_bits(mask) != channels) ++ goto fallback; ++ ++ format->Format.nChannels = channels; ++ format->dwChannelMask = mask; ++ free(original_layout); ++ free(expanded); ++ return S_OK; ++ ++fallback: ++ free(original_layout); ++ free(expanded); ++ ++ /* Stereo/mono endpoints occasionally omit a preferred layout. Their ++ * fallback masks are unambiguous; fail closed for larger devices rather ++ * than claiming a guessed speaker topology is physically lossless. */ ++ { ++ struct get_mix_format_params params = ++ { ++ .device = device, ++ .flow = eRender, ++ .fmt = format, ++ }; ++ ++ memset(format, 0, sizeof(*format)); ++ unix_get_mix_format(¶ms); ++ if (FAILED(params.result)) ++ return params.result; ++ if (format->Format.nChannels > 2 || ++ count_channel_mask_bits(format->dwChannelMask) != ++ format->Format.nChannels) ++ return AUDCLNT_E_UNSUPPORTED_FORMAT; ++ return S_OK; ++ } ++} ++ ++static UINT32 count_channel_mask_bits(DWORD mask) ++{ ++ UINT32 count = 0; ++ ++ while (mask) ++ { ++ mask &= mask - 1; ++ ++count; ++ } ++ return count; ++} ++ ++struct spatial_static_channel ++{ ++ AudioObjectType type; ++ DWORD speaker; ++}; ++ ++static const struct spatial_static_channel spatial_static_channels[] = ++{ ++ {AudioObjectType_FrontLeft, SPEAKER_FRONT_LEFT}, ++ {AudioObjectType_FrontRight, SPEAKER_FRONT_RIGHT}, ++ {AudioObjectType_FrontCenter, SPEAKER_FRONT_CENTER}, ++ {AudioObjectType_LowFrequency, SPEAKER_LOW_FREQUENCY}, ++ {AudioObjectType_SideLeft, SPEAKER_SIDE_LEFT}, ++ {AudioObjectType_SideRight, SPEAKER_SIDE_RIGHT}, ++ {AudioObjectType_BackLeft, SPEAKER_BACK_LEFT}, ++ {AudioObjectType_BackRight, SPEAKER_BACK_RIGHT}, ++ {AudioObjectType_TopFrontLeft, SPEAKER_TOP_FRONT_LEFT}, ++ {AudioObjectType_TopFrontRight, SPEAKER_TOP_FRONT_RIGHT}, ++ {AudioObjectType_TopBackLeft, SPEAKER_TOP_BACK_LEFT}, ++ {AudioObjectType_TopBackRight, SPEAKER_TOP_BACK_RIGHT}, ++ {AudioObjectType_BottomFrontLeft, SPATIAL_AUDIO_BOTTOM_FRONT_LEFT_SPEAKER}, ++ {AudioObjectType_BottomFrontRight, SPATIAL_AUDIO_BOTTOM_FRONT_RIGHT_SPEAKER}, ++ {AudioObjectType_BottomBackLeft, SPATIAL_AUDIO_BOTTOM_BACK_LEFT_SPEAKER}, ++ {AudioObjectType_BottomBackRight, SPATIAL_AUDIO_BOTTOM_BACK_RIGHT_SPEAKER}, ++ {AudioObjectType_BackCenter, SPEAKER_BACK_CENTER}, ++}; ++ ++static DWORD spatial_static_mask_to_transport_mask(UINT32 static_mask) ++{ ++ DWORD mask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | ++ SPATIAL_AUDIO_DRY_SPEAKER; ++ unsigned int i; ++ ++ for (i = 0; i < ARRAY_SIZE(spatial_static_channels); ++i) ++ if (static_mask & spatial_static_channels[i].type) ++ mask |= spatial_static_channels[i].speaker; ++ return mask; ++} ++ ++static HRESULT get_spatial_bed_format(const WAVEFORMATEX *transport, ++ UINT32 static_mask, UINT32 dynamic_objects, WAVEFORMATEXTENSIBLE *bed, ++ UINT32 *dry_channel, UINT32 *dynamic_channel) ++{ ++ const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *)transport; ++ ++ if (transport->wFormatTag != WAVE_FORMAT_EXTENSIBLE || ++ !IsEqualGUID(&ext->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) || ++ transport->wBitsPerSample != 32 || ++ static_mask & ~SPATIAL_AUDIO_STATIC_OBJECT_MASK || ++ ext->dwChannelMask != spatial_static_mask_to_transport_mask(static_mask) || ++ dynamic_objects > UINT16_MAX || ++ count_channel_mask_bits(ext->dwChannelMask) + dynamic_objects != ++ transport->nChannels) ++ return AUDCLNT_E_UNSUPPORTED_FORMAT; ++ ++ *bed = *ext; ++ bed->dwChannelMask &= ~SPATIAL_AUDIO_DRY_SPEAKER; ++ bed->Format.nChannels -= dynamic_objects + 1; ++ bed->Format.nBlockAlign = bed->Format.nChannels * sizeof(float); ++ bed->Format.nAvgBytesPerSec = bed->Format.nSamplesPerSec * ++ bed->Format.nBlockAlign; ++ ++ if (!bed->Format.nChannels || ++ count_channel_mask_bits(bed->dwChannelMask) != bed->Format.nChannels || ++ (bed->dwChannelMask & (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT)) != ++ (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT)) ++ return AUDCLNT_E_UNSUPPORTED_FORMAT; ++ ++ *dry_channel = count_channel_mask_bits(ext->dwChannelMask & ++ (SPATIAL_AUDIO_DRY_SPEAKER - 1)); ++ *dynamic_channel = count_channel_mask_bits(ext->dwChannelMask); ++ return S_OK; ++} ++ ++static HRESULT configure_spatial_dry_output(struct coreaudio_stream *stream, DWORD mask, ++ UINT32 channels) ++{ ++ if (count_channel_mask_bits(mask) != channels) ++ return AUDCLNT_E_UNSUPPORTED_FORMAT; ++ ++ stream->spatial_dry_output_count = 0; ++ if ((mask & (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT)) == ++ (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT)) ++ { ++ stream->spatial_dry_output[stream->spatial_dry_output_count++] = ++ count_channel_mask_bits(mask & (SPEAKER_FRONT_LEFT - 1)); ++ stream->spatial_dry_output[stream->spatial_dry_output_count++] = ++ count_channel_mask_bits(mask & (SPEAKER_FRONT_RIGHT - 1)); ++ } ++ else if (mask & SPEAKER_FRONT_CENTER) ++ { ++ stream->spatial_dry_output[stream->spatial_dry_output_count++] = ++ count_channel_mask_bits(mask & (SPEAKER_FRONT_CENTER - 1)); ++ } ++ else ++ { ++ WARN("Output channel layout has no front pair or center for dry spatial audio.\n"); ++ return AUDCLNT_E_UNSUPPORTED_FORMAT; ++ } ++ ++ return S_OK; ++} ++ ++static HRESULT configure_spatial_max_frames(struct coreaudio_stream *stream) ++{ ++ UINT32 metadata_capacity, parameter_events; ++ UInt32 max_frames, size = sizeof(max_frames); ++ UINT64 count; ++ OSStatus sc; ++ ++ sc = AudioUnitGetProperty(stream->unit, kAudioUnitProperty_MaximumFramesPerSlice, ++ kAudioUnitScope_Global, 0, &max_frames, &size); ++ if (sc != noErr || !max_frames) ++ { ++ WARN("Failed to query output maximum frames per slice: %x.\n", (int)sc); ++ return sc == noErr ? E_FAIL : osstatus_to_hresult(sc); ++ } ++ if (max_frames < stream->period_frames) ++ max_frames = stream->period_frames; ++ ++ sc = AudioUnitSetProperty(stream->unit, kAudioUnitProperty_MaximumFramesPerSlice, ++ kAudioUnitScope_Global, 0, &max_frames, sizeof(max_frames)); ++ if (sc != noErr) ++ { ++ WARN("Failed to configure output maximum frames per slice: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ if (stream->spatial_unit) ++ { ++ sc = AudioUnitSetProperty(stream->spatial_unit, ++ kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, ++ 0, &max_frames, sizeof(max_frames)); ++ if (sc != noErr) ++ { ++ WARN("Failed to configure spatial mixer maximum frames per slice: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ } ++ ++ if (max_frames > UINT32_MAX / sizeof(float) || ++ stream->spatial_bed_channels > ++ UINT32_MAX / sizeof(float) / max_frames) ++ { ++ WARN("Spatial render slice is too large (%u frames, %u channels).\n", ++ max_frames, stream->spatial_bed_channels); ++ return AUDCLNT_E_UNSUPPORTED_FORMAT; ++ } ++ ++ if (!(stream->spatial_dry_buffer = malloc(max_frames * ++ sizeof(*stream->spatial_dry_buffer)))) ++ return E_OUTOFMEMORY; ++ if (!(stream->spatial_bed_buffer = malloc((size_t)max_frames * ++ stream->spatial_bed_channels * sizeof(*stream->spatial_bed_buffer)))) ++ { ++ free(stream->spatial_dry_buffer); ++ stream->spatial_dry_buffer = NULL; ++ return E_OUTOFMEMORY; ++ } ++ stream->spatial_dry_capacity = max_frames; ++ ++ if (!stream->spatial_dynamic_objects) ++ return S_OK; ++ ++ count = (UINT64)max_frames * stream->spatial_dynamic_objects; ++ if (count > SIZE_MAX / sizeof(*stream->spatial_dynamic_buffer) || ++ !(stream->spatial_dynamic_buffer = calloc(count, ++ sizeof(*stream->spatial_dynamic_buffer)))) ++ return E_OUTOFMEMORY; ++ ++ count = ((UINT64)stream->bufsize_frames + stream->period_frames - 1) / ++ stream->period_frames + 2; ++ if (count > UINT32_MAX) ++ return E_OUTOFMEMORY; ++ metadata_capacity = count; ++ if (metadata_capacity < 3) ++ metadata_capacity = 3; ++ count = (UINT64)metadata_capacity * stream->spatial_dynamic_objects; ++ if (count > SIZE_MAX / sizeof(*stream->spatial_object_states) || ++ !(stream->spatial_object_states = calloc(count, ++ sizeof(*stream->spatial_object_states)))) ++ return E_OUTOFMEMORY; ++ if (!(stream->spatial_metadata_sequences = malloc( ++ metadata_capacity * sizeof(*stream->spatial_metadata_sequences)))) ++ return E_OUTOFMEMORY; ++ for (size = 0; size < metadata_capacity; ++size) ++ stream->spatial_metadata_sequences[size] = UINT64_MAX; ++ stream->spatial_metadata_capacity = metadata_capacity; ++ ++ count = (UINT64)(max_frames / stream->period_frames + 2) * ++ stream->spatial_dynamic_objects * 3; ++ if (count > UINT32_MAX || ++ count > SIZE_MAX / sizeof(*stream->spatial_parameter_events) || ++ !(parameter_events = count) || ++ !(stream->spatial_parameter_events = malloc((size_t)parameter_events * ++ sizeof(*stream->spatial_parameter_events)))) ++ return E_OUTOFMEMORY; ++ stream->spatial_parameter_event_capacity = parameter_events; ++ return S_OK; ++} ++ ++static HRESULT configure_spatial_dry_delay(struct coreaudio_stream *stream) ++{ ++ Float64 latency, frame_latency; ++ UInt32 size = sizeof(latency), frames; ++ OSStatus sc; ++ ++ if (!stream->spatial_unit) ++ return S_OK; ++ ++ sc = AudioUnitGetProperty(stream->spatial_unit, kAudioUnitProperty_Latency, ++ kAudioUnitScope_Global, 0, &latency, &size); ++ if (sc != noErr) ++ { ++ WARN("Failed to query spatial mixer latency: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ frame_latency = latency * stream->fmt->nSamplesPerSec; ++ if (!(latency >= 0.0) || !(frame_latency >= 0.0) || ++ frame_latency > UINT32_MAX) ++ { ++ WARN("Spatial mixer returned an invalid latency %f.\n", latency); ++ return E_FAIL; ++ } ++ ++ frames = (UINT32)frame_latency; ++ if (frame_latency - frames >= 0.5 && frames != UINT32_MAX) ++ ++frames; ++ if (!frames) ++ return S_OK; ++ ++ if (!(stream->spatial_dry_delay_buffer = calloc(frames, ++ sizeof(*stream->spatial_dry_delay_buffer)))) ++ return E_OUTOFMEMORY; ++ ++ stream->spatial_dry_delay_frames = frames; ++ TRACE("Delaying non-spatial objects by %u frames (%f seconds) to match the spatial mixer.\n", ++ frames, latency); ++ return S_OK; ++} ++ ++static BOOL device_supports_spatial_format(const char *device, const WAVEFORMATEX *format) ++{ ++ const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *)format; ++ WAVEFORMATEXTENSIBLE mix; ++ ++ if (format->wFormatTag != WAVE_FORMAT_EXTENSIBLE || !ext->dwChannelMask) ++ return FALSE; ++ if (FAILED(get_device_mix_format(device, &mix))) ++ return FALSE; ++ ++ return mix.Format.nChannels >= format->nChannels && ++ !(ext->dwChannelMask & ~mix.dwChannelMask); ++} ++ ++struct wave_channel_layout ++{ ++ AudioChannelLayout layout; ++ AudioChannelDescription extra_descriptions[17]; ++}; ++ ++static AudioChannelLabel wave_speaker_to_channel_label(DWORD speaker) ++{ ++ switch (speaker) ++ { ++ case SPEAKER_FRONT_LEFT: return kAudioChannelLabel_Left; ++ case SPEAKER_FRONT_RIGHT: return kAudioChannelLabel_Right; ++ case SPEAKER_FRONT_CENTER: return kAudioChannelLabel_Center; ++ case SPEAKER_LOW_FREQUENCY: return kAudioChannelLabel_LFEScreen; ++ case SPEAKER_BACK_LEFT: return kAudioChannelLabel_LeftBackSurround; ++ case SPEAKER_BACK_RIGHT: return kAudioChannelLabel_RightBackSurround; ++ case SPEAKER_FRONT_LEFT_OF_CENTER: return kAudioChannelLabel_LeftCenter; ++ case SPEAKER_FRONT_RIGHT_OF_CENTER: return kAudioChannelLabel_RightCenter; ++ case SPEAKER_BACK_CENTER: return kAudioChannelLabel_CenterSurround; ++ case SPEAKER_SIDE_LEFT: return kAudioChannelLabel_LeftSideSurround; ++ case SPEAKER_SIDE_RIGHT: return kAudioChannelLabel_RightSideSurround; ++ case SPEAKER_TOP_CENTER: return kAudioChannelLabel_CenterTopMiddle; ++ case SPEAKER_TOP_FRONT_LEFT: return kAudioChannelLabel_LeftTopFront; ++ case SPEAKER_TOP_FRONT_CENTER: return kAudioChannelLabel_CenterTopFront; ++ case SPEAKER_TOP_FRONT_RIGHT: return kAudioChannelLabel_RightTopFront; ++ case SPEAKER_TOP_BACK_LEFT: return kAudioChannelLabel_LeftTopRear; ++ case SPEAKER_TOP_BACK_CENTER: return kAudioChannelLabel_CenterTopRear; ++ case SPEAKER_TOP_BACK_RIGHT: return kAudioChannelLabel_RightTopRear; ++ default: return kAudioChannelLabel_Unknown; ++ } ++} ++ ++static HRESULT wave_mask_to_channel_layout(DWORD mask, UINT32 channels, ++ struct wave_channel_layout *layout, UInt32 *size) ++{ ++ AudioChannelLabel label; ++ DWORD speaker; ++ UINT32 index = 0; ++ ++ memset(layout, 0, sizeof(*layout)); ++ layout->layout.mChannelLayoutTag = kAudioChannelLayoutTag_UseChannelDescriptions; ++ ++ for (speaker = 1; speaker && speaker <= SPEAKER_TOP_BACK_RIGHT; speaker <<= 1) ++ { ++ if (!(mask & speaker)) ++ continue; ++ if ((label = wave_speaker_to_channel_label(speaker)) == kAudioChannelLabel_Unknown) ++ return E_INVALIDARG; ++ ++ layout->layout.mChannelDescriptions[index++].mChannelLabel = label; ++ } ++ ++ if (index != channels || mask & ~(SPEAKER_TOP_BACK_RIGHT * 2 - 1)) ++ return E_INVALIDARG; ++ ++ layout->layout.mNumberChannelDescriptions = channels; ++ *size = offsetof(AudioChannelLayout, mChannelDescriptions) + ++ channels * sizeof(AudioChannelDescription); ++ return S_OK; ++} ++ ++/* Physical output layouts must not be round-tripped through a Windows ++ * speaker mask: e.g. Left/RightTopMiddle have no WAVE mask equivalents. ++ * Canonical descriptions preserve device channel order and coordinates. */ ++#define SPATIAL_OUTPUT_MAX_CHANNELS 64 ++struct spatial_output_layout ++{ ++ AudioChannelLayout layout; ++ AudioChannelDescription extra[SPATIAL_OUTPUT_MAX_CHANNELS - 1]; ++}; ++ ++static HRESULT get_spatial_output_layout(const char *device, ++ struct spatial_output_layout *output, UInt32 *output_size) ++{ ++ AudioObjectPropertyAddress addr = {kAudioDevicePropertyPreferredChannelLayout, ++ kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMain}; ++ AudioDeviceID dev_id = dev_id_from_device(device); ++ AudioChannelLayout *raw = NULL, *expanded = NULL, *layout; ++ AudioBufferList *buffers = NULL; ++ UInt32 size, expanded_size, value, channels = 0, i, j; ++ AudioFormatPropertyID property; ++ BOOL used_fallback = FALSE; ++ OSStatus sc; ++ HRESULT hr = AUDCLNT_E_UNSUPPORTED_FORMAT; ++ ++ memset(output, 0, sizeof(*output)); ++ if (dev_id == kAudioObjectUnknown) ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ sc = AudioObjectGetPropertyDataSize(dev_id, &addr, 0, NULL, &size); ++ if (sc != noErr) goto fallback; ++ if (size < offsetof(AudioChannelLayout, mChannelDescriptions)) goto done; ++ if (!(raw = malloc(size))) { hr = E_OUTOFMEMORY; goto done; } ++ sc = AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, raw); ++ if (sc != noErr || size < offsetof(AudioChannelLayout, mChannelDescriptions)) goto done; ++ layout = raw; ++ if (raw->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions) ++ { ++ property = raw->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap ++ ? kAudioFormatProperty_ChannelLayoutForBitmap : kAudioFormatProperty_ChannelLayoutForTag; ++ value = property == kAudioFormatProperty_ChannelLayoutForBitmap ++ ? raw->mChannelBitmap : raw->mChannelLayoutTag; ++ sc = AudioFormatGetPropertyInfo(property, sizeof(value), &value, &expanded_size); ++ if (sc != noErr || expanded_size < offsetof(AudioChannelLayout, mChannelDescriptions)) goto done; ++ if (!(expanded = malloc(expanded_size))) { hr = E_OUTOFMEMORY; goto done; } ++ sc = AudioFormatGetProperty(property, sizeof(value), &value, &expanded_size, expanded); ++ if (sc != noErr) goto done; ++ layout = expanded; ++ size = expanded_size; ++ } ++ if (size < offsetof(AudioChannelLayout, mChannelDescriptions) || ++ !layout->mNumberChannelDescriptions || ++ layout->mNumberChannelDescriptions > SPATIAL_OUTPUT_MAX_CHANNELS || ++ layout->mNumberChannelDescriptions > ++ (size - offsetof(AudioChannelLayout, mChannelDescriptions)) / sizeof(AudioChannelDescription)) ++ goto done; ++ output->layout.mChannelLayoutTag = kAudioChannelLayoutTag_UseChannelDescriptions; ++ output->layout.mNumberChannelDescriptions = layout->mNumberChannelDescriptions; ++ for (i = 0; i < layout->mNumberChannelDescriptions; ++i) ++ { ++ const AudioChannelDescription *src = &layout->mChannelDescriptions[i]; ++ AudioChannelDescription *dst = &output->layout.mChannelDescriptions[i]; ++ if (src->mChannelLabel == kAudioChannelLabel_Unknown || ++ src->mChannelLabel == kAudioChannelLabel_Unused || ++ src->mChannelLabel >= kAudioChannelLabel_Discrete_0) ++ goto done; ++ dst->mChannelLabel = src->mChannelLabel; ++ if (src->mChannelLabel == kAudioChannelLabel_UseCoordinates && ++ !(src->mChannelFlags & (kAudioChannelFlags_RectangularCoordinates | ++ kAudioChannelFlags_SphericalCoordinates))) goto done; ++ dst->mChannelFlags = src->mChannelFlags; ++ for (j = 0; j < 3; ++j) ++ { ++ if (!isfinite(src->mCoordinates[j])) goto done; ++ dst->mCoordinates[j] = src->mCoordinates[j]; ++ } ++ } ++ goto verify_channels; ++ ++fallback: ++ used_fallback = TRUE; ++ memset(output, 0, sizeof(*output)); ++ channels = 0; ++ free(buffers); ++ buffers = NULL; ++ /* No guessed topology for multichannel devices. */ ++ { ++ WAVEFORMATEXTENSIBLE mix; ++ struct wave_channel_layout wave; ++ UInt32 wave_size; ++ if (FAILED(hr = get_device_mix_format(device, &mix))) goto done; ++ if (mix.Format.nChannels > 2) { hr = AUDCLNT_E_UNSUPPORTED_FORMAT; goto done; } ++ if (FAILED(hr = wave_mask_to_channel_layout(mix.dwChannelMask, ++ mix.Format.nChannels, &wave, &wave_size))) goto done; ++ memcpy(output, &wave, wave_size); ++ hr = AUDCLNT_E_UNSUPPORTED_FORMAT; ++ } ++verify_channels: ++ /* Preferred layout must describe every actual output channel. */ ++ addr.mSelector = kAudioDevicePropertyStreamConfiguration; ++ sc = AudioObjectGetPropertyDataSize(dev_id, &addr, 0, NULL, &size); ++ if (sc != noErr || size < offsetof(AudioBufferList, mBuffers)) goto done; ++ if (!(buffers = malloc(size))) { hr = E_OUTOFMEMORY; goto done; } ++ sc = AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, buffers); ++ if (sc != noErr || size < offsetof(AudioBufferList, mBuffers) || ++ buffers->mNumberBuffers > (size - offsetof(AudioBufferList, mBuffers)) / sizeof(AudioBuffer)) goto done; ++ for (i = 0; i < buffers->mNumberBuffers; ++i) ++ { ++ if (buffers->mBuffers[i].mNumberChannels > SPATIAL_OUTPUT_MAX_CHANNELS - channels) goto done; ++ channels += buffers->mBuffers[i].mNumberChannels; ++ } ++ if (channels != output->layout.mNumberChannelDescriptions) goto done; ++ *output_size = offsetof(AudioChannelLayout, mChannelDescriptions) + channels * sizeof(AudioChannelDescription); ++ TRACE("Native spatial output layout: %u channels.\n", channels); ++ for (i = 0; i < channels; ++i) ++ TRACE("Output channel %u label %#x.\n", i, (unsigned int)output->layout.mChannelDescriptions[i].mChannelLabel); ++ hr = S_OK; ++done: ++ if (hr == AUDCLNT_E_UNSUPPORTED_FORMAT && !used_fallback) ++ goto fallback; ++ free(buffers); ++ free(expanded); ++ free(raw); ++ return hr; ++} ++ ++static HRESULT configure_native_spatial_dry_output(struct coreaudio_stream *stream, ++ const AudioChannelLayout *layout) ++{ ++ UINT32 i, left = UINT32_MAX, right = UINT32_MAX, center = UINT32_MAX; ++ for (i = 0; i < layout->mNumberChannelDescriptions; ++i) ++ { ++ switch (layout->mChannelDescriptions[i].mChannelLabel) ++ { ++ case kAudioChannelLabel_Left: left = i; break; ++ case kAudioChannelLabel_Right: right = i; break; ++ case kAudioChannelLabel_Center: center = i; break; ++ default: break; ++ } ++ } ++ stream->spatial_dry_output_count = 0; ++ if (left != UINT32_MAX && right != UINT32_MAX) ++ { ++ stream->spatial_dry_output[stream->spatial_dry_output_count++] = left; ++ stream->spatial_dry_output[stream->spatial_dry_output_count++] = right; ++ } ++ else if (center != UINT32_MAX) ++ stream->spatial_dry_output[stream->spatial_dry_output_count++] = center; ++ else return AUDCLNT_E_UNSUPPORTED_FORMAT; ++ return S_OK; ++} ++ ++static BOOL spatial_transport_speaker_to_coordinates(DWORD speaker, float *x, ++ float *back_front, float *down_up) ++{ ++ switch (speaker) ++ { ++ case SPATIAL_AUDIO_BOTTOM_FRONT_LEFT_SPEAKER: ++ *x = -0.3535534f; ++ *back_front = 0.6123724f; ++ *down_up = -0.7071068f; ++ return TRUE; ++ case SPATIAL_AUDIO_BOTTOM_FRONT_RIGHT_SPEAKER: ++ *x = 0.3535534f; ++ *back_front = 0.6123724f; ++ *down_up = -0.7071068f; ++ return TRUE; ++ case SPATIAL_AUDIO_BOTTOM_BACK_LEFT_SPEAKER: ++ *x = -0.3535534f; ++ *back_front = -0.6123724f; ++ *down_up = -0.7071068f; ++ return TRUE; ++ case SPATIAL_AUDIO_BOTTOM_BACK_RIGHT_SPEAKER: ++ *x = 0.3535534f; ++ *back_front = -0.6123724f; ++ *down_up = -0.7071068f; ++ return TRUE; ++ default: ++ return FALSE; ++ } ++} ++ ++static HRESULT spatial_mask_to_channel_layout(DWORD mask, UINT32 channels, ++ struct wave_channel_layout *layout, UInt32 *size) ++{ ++ AudioChannelDescription *description; ++ AudioChannelLabel label; ++ DWORD speaker; ++ UINT32 index = 0; ++ ++ memset(layout, 0, sizeof(*layout)); ++ layout->layout.mChannelLayoutTag = kAudioChannelLayoutTag_UseChannelDescriptions; ++ ++ for (speaker = 1; speaker && speaker <= SPEAKER_TOP_BACK_RIGHT; speaker <<= 1) ++ { ++ if (!(mask & speaker)) ++ continue; ++ ++ description = &layout->layout.mChannelDescriptions[index++]; ++ if (spatial_transport_speaker_to_coordinates(speaker, ++ &description->mCoordinates[kAudioChannelCoordinates_LeftRight], ++ &description->mCoordinates[kAudioChannelCoordinates_BackFront], ++ &description->mCoordinates[kAudioChannelCoordinates_DownUp])) ++ { ++ description->mChannelLabel = kAudioChannelLabel_UseCoordinates; ++ description->mChannelFlags = kAudioChannelFlags_RectangularCoordinates; ++ } ++ else ++ { ++ label = wave_speaker_to_channel_label(speaker); ++ if (label == kAudioChannelLabel_Unknown) ++ return E_INVALIDARG; ++ description->mChannelLabel = label; ++ } ++ } ++ ++ if (index != channels || mask & ~(SPEAKER_TOP_BACK_RIGHT * 2 - 1) || ++ mask & SPATIAL_AUDIO_DRY_SPEAKER) ++ return E_INVALIDARG; ++ ++ layout->layout.mNumberChannelDescriptions = channels; ++ *size = offsetof(AudioChannelLayout, mChannelDescriptions) + ++ channels * sizeof(AudioChannelDescription); ++ return S_OK; ++} ++ ++#if MAC_OS_X_VERSION_MAX_ALLOWED >= 120300 ++static HRESULT disable_spatial_head_tracking(AudioComponentInstance unit) ++{ ++ UInt32 value, size = sizeof(value); ++ Boolean writable; ++ OSStatus sc; ++ ++ sc = AudioUnitGetPropertyInfo(unit, ++ kAudioUnitProperty_SpatialMixerEnableHeadTracking, ++ kAudioUnitScope_Global, 0, &size, &writable); ++ if (sc != noErr || size != sizeof(value)) ++ { ++ WARN("Failed to inspect spatial mixer head tracking: %x.\n", (int)sc); ++ return sc == noErr ? E_FAIL : osstatus_to_hresult(sc); ++ } ++ ++ sc = AudioUnitGetProperty(unit, ++ kAudioUnitProperty_SpatialMixerEnableHeadTracking, ++ kAudioUnitScope_Global, 0, &value, &size); ++ if (sc != noErr) ++ { ++ WARN("Failed to query spatial mixer head tracking: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ if (!value) ++ return S_OK; ++ if (!writable) ++ { ++ WARN("Spatial mixer head tracking is enabled but read-only.\n"); ++ return E_FAIL; ++ } ++ ++ value = 0; ++ sc = AudioUnitSetProperty(unit, ++ kAudioUnitProperty_SpatialMixerEnableHeadTracking, ++ kAudioUnitScope_Global, 0, &value, sizeof(value)); ++ if (sc != noErr) ++ { ++ WARN("Failed to disable spatial mixer head tracking: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ return S_OK; ++} ++#endif ++ ++static HRESULT ca_setup_spatial_audiounit(struct coreaudio_stream *stream, const char *device, ++ const WAVEFORMATEXTENSIBLE *bed) ++{ ++ AudioStreamBasicDescription input_desc, dynamic_desc, output_desc; ++ struct wave_channel_layout input_layout; ++ struct spatial_output_layout output_layout; ++ AURenderCallbackStruct callback; ++ UInt32 algorithm, bus, input_layout_size, output_layout_size; ++ UInt32 output_type, rendering_flags, source_mode, value; ++ OSStatus sc; ++ HRESULT hr; ++ ++ if (FAILED(hr = get_spatial_output_layout(device, &output_layout, &output_layout_size))) ++ return hr; ++ ++ if (!(stream->spatial_unit = get_spatial_mixer())) ++ return AUDCLNT_E_UNSUPPORTED_FORMAT; ++ ++ if (FAILED(hr = ca_get_audiodesc(&input_desc, &bed->Format))) ++ return hr; ++ input_desc.mFormatFlags = kAudioFormatFlagsNativeFloatPacked; ++ ++ output_desc.mSampleRate = input_desc.mSampleRate; ++ output_desc.mFormatID = kAudioFormatLinearPCM; ++ output_desc.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved; ++ output_desc.mBytesPerPacket = sizeof(float); ++ output_desc.mFramesPerPacket = 1; ++ output_desc.mBytesPerFrame = sizeof(float); ++ output_desc.mChannelsPerFrame = output_layout.layout.mNumberChannelDescriptions; ++ output_desc.mBitsPerChannel = sizeof(float) * 8; ++ output_desc.mReserved = 0; ++ ++ if (FAILED(hr = spatial_mask_to_channel_layout(bed->dwChannelMask, ++ bed->Format.nChannels, &input_layout, &input_layout_size))) ++ { ++ WARN("Cannot translate a WAVE channel mask for the spatial mixer.\n"); ++ return hr; ++ } ++ ++ if (stream->spatial_dynamic_objects == UINT32_MAX) ++ return E_INVALIDARG; ++ value = stream->spatial_dynamic_objects + 1; ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_ElementCount, ++ kAudioUnitScope_Input, 0, &value, sizeof(value)); ++ if (sc != noErr) ++ { ++ WARN("Failed to configure spatial mixer input count: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_StreamFormat, ++ kAudioUnitScope_Input, 0, &input_desc, sizeof(input_desc)); ++ if (sc != noErr) ++ { ++ WARN("Failed to set spatial mixer input format: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_AudioChannelLayout, ++ kAudioUnitScope_Input, 0, &input_layout.layout, input_layout_size); ++ if (sc != noErr) ++ { ++ WARN("Failed to set spatial mixer input layout: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_StreamFormat, ++ kAudioUnitScope_Output, 0, &output_desc, sizeof(output_desc)); ++ if (sc != noErr) ++ { ++ WARN("Failed to set spatial mixer output format: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_AudioChannelLayout, ++ kAudioUnitScope_Output, 0, &output_layout.layout, output_layout_size); ++ if (sc != noErr) ++ { ++ WARN("Failed to set spatial mixer output layout: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ output_type = get_device_spatial_output_type(stream->dev_id); ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_SpatialMixerOutputType, ++ kAudioUnitScope_Global, 0, &output_type, sizeof(output_type)); ++ if (sc != noErr) ++ { ++ WARN("Failed to select spatial mixer output type: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ algorithm = kSpatializationAlgorithm_UseOutputType; ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_SpatializationAlgorithm, ++ kAudioUnitScope_Input, 0, &algorithm, sizeof(algorithm)); ++ if (sc != noErr) ++ { ++ algorithm = output_type == kSpatialMixerOutputType_Headphones ++ ? kSpatializationAlgorithm_HRTFHQ : kSpatializationAlgorithm_VectorBasedPanning; ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_SpatializationAlgorithm, ++ kAudioUnitScope_Input, 0, &algorithm, sizeof(algorithm)); ++ } ++ if (sc != noErr) ++ { ++ WARN("Failed to select a spatialization algorithm: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ source_mode = kSpatialMixerSourceMode_AmbienceBed; ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_SpatialMixerSourceMode, ++ kAudioUnitScope_Input, 0, &source_mode, sizeof(source_mode)); ++ if (sc != noErr) ++ { ++ WARN("Failed to configure the spatial ambience bed: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ rendering_flags = 0; ++ sc = AudioUnitSetProperty(stream->spatial_unit, ++ kAudioUnitProperty_SpatialMixerRenderingFlags, kAudioUnitScope_Input, ++ 0, &rendering_flags, sizeof(rendering_flags)); ++ if (sc != noErr) ++ { ++ WARN("Failed to disable spatial distance processing: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ value = 0; ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_UsesInternalReverb, ++ kAudioUnitScope_Global, 0, &value, sizeof(value)); ++ if (sc != noErr) ++ { ++ WARN("Failed to disable spatial mixer reverb: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++#if MAC_OS_X_VERSION_MAX_ALLOWED >= 120300 ++ if (output_type == kSpatialMixerOutputType_Headphones) ++ { ++ if (__builtin_available(macOS 12.3, *)) ++ { ++ if (FAILED(hr = disable_spatial_head_tracking(stream->spatial_unit))) ++ return hr; ++ } ++ } ++#endif ++#if MAC_OS_X_VERSION_MAX_ALLOWED >= 130000 ++ if (output_type == kSpatialMixerOutputType_Headphones) ++ { ++ if (__builtin_available(macOS 13.0, *)) ++ { ++ value = kSpatialMixerPersonalizedHRTFMode_Auto; ++ sc = AudioUnitSetProperty(stream->spatial_unit, ++ kAudioUnitProperty_SpatialMixerPersonalizedHRTFMode, ++ kAudioUnitScope_Global, 0, &value, sizeof(value)); ++ if (sc != noErr) ++ WARN("Failed to select automatic personalized HRTF: %x.\n", (int)sc); ++ } ++ } ++#endif ++ ++ callback.inputProc = ca_spatial_bed_render_cb; ++ callback.inputProcRefCon = stream; ++ sc = AudioUnitSetProperty(stream->spatial_unit, kAudioUnitProperty_SetRenderCallback, ++ kAudioUnitScope_Input, 0, &callback, sizeof(callback)); ++ if (sc != noErr) ++ { ++ WARN("Failed to set spatial mixer input callback: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ if (stream->spatial_dynamic_objects) ++ { ++ UInt32 point_source_flags = ++ kSpatialMixerRenderingFlags_InterAuralDelay | ++ kSpatialMixerRenderingFlags_DistanceAttenuation; ++ ++ if (!(stream->spatial_input_contexts = calloc( ++ stream->spatial_dynamic_objects, ++ sizeof(*stream->spatial_input_contexts)))) ++ return E_OUTOFMEMORY; ++ ++ dynamic_desc = input_desc; ++ dynamic_desc.mBytesPerPacket = sizeof(float); ++ dynamic_desc.mBytesPerFrame = sizeof(float); ++ dynamic_desc.mChannelsPerFrame = 1; ++ for (bus = 1; bus <= stream->spatial_dynamic_objects; ++bus) ++ { ++ struct spatial_input_context *context = ++ &stream->spatial_input_contexts[bus - 1]; ++ ++ sc = AudioUnitSetProperty(stream->spatial_unit, ++ kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, ++ bus, &dynamic_desc, sizeof(dynamic_desc)); ++ if (sc != noErr) ++ { ++ WARN("Failed to configure PointSource %u format: %x.\n", ++ bus - 1, (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ source_mode = kSpatialMixerSourceMode_PointSource; ++ sc = AudioUnitSetProperty(stream->spatial_unit, ++ kAudioUnitProperty_SpatialMixerSourceMode, ++ kAudioUnitScope_Input, bus, &source_mode, ++ sizeof(source_mode)); ++ if (sc == noErr) ++ sc = AudioUnitSetProperty(stream->spatial_unit, ++ kAudioUnitProperty_SpatializationAlgorithm, ++ kAudioUnitScope_Input, bus, &algorithm, ++ sizeof(algorithm)); ++ if (sc == noErr) ++ sc = AudioUnitSetProperty(stream->spatial_unit, ++ kAudioUnitProperty_SpatialMixerRenderingFlags, ++ kAudioUnitScope_Input, bus, &point_source_flags, ++ sizeof(point_source_flags)); ++ if (sc != noErr) ++ { ++ WARN("Failed to configure PointSource %u spatial mode: %x.\n", ++ bus - 1, (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ context->stream = stream; ++ context->slot = bus - 1; ++ callback.inputProc = ca_spatial_dynamic_render_cb; ++ callback.inputProcRefCon = context; ++ sc = AudioUnitSetProperty(stream->spatial_unit, ++ kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, ++ bus, &callback, sizeof(callback)); ++ if (sc != noErr) ++ { ++ WARN("Failed to set PointSource %u callback: %x.\n", ++ bus - 1, (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ sc = AudioUnitSetParameter(stream->spatial_unit, ++ kSpatialMixerParam_Azimuth, kAudioUnitScope_Input, ++ bus, 0.0f, 0); ++ if (sc == noErr) ++ sc = AudioUnitSetParameter(stream->spatial_unit, ++ kSpatialMixerParam_Elevation, kAudioUnitScope_Input, ++ bus, 0.0f, 0); ++ if (sc == noErr) ++ sc = AudioUnitSetParameter(stream->spatial_unit, ++ kSpatialMixerParam_Distance, kAudioUnitScope_Input, ++ bus, 0.0f, 0); ++ if (sc != noErr) ++ { ++ WARN("Failed to initialize PointSource %u position: %x.\n", ++ bus - 1, (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ } ++ } ++ ++ sc = AudioUnitSetProperty(stream->unit, kAudioUnitProperty_StreamFormat, ++ kAudioUnitScope_Input, 0, &output_desc, sizeof(output_desc)); ++ if (sc != noErr) ++ { ++ WARN("Failed to set spatial output format: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ sc = AudioUnitSetProperty(stream->unit, kAudioUnitProperty_AudioChannelLayout, ++ kAudioUnitScope_Input, 0, &output_layout.layout, output_layout_size); ++ if (sc != noErr) ++ { ++ WARN("Failed to set spatial output layout: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ callback.inputProc = ca_spatial_render_cb; ++ callback.inputProcRefCon = stream; ++ sc = AudioUnitSetProperty(stream->unit, kAudioUnitProperty_SetRenderCallback, ++ kAudioUnitScope_Input, 0, &callback, sizeof(callback)); ++ if (sc != noErr) ++ { ++ WARN("Failed to set spatial output callback: %x.\n", (int)sc); ++ return osstatus_to_hresult(sc); ++ } ++ ++ if (FAILED(hr = configure_native_spatial_dry_output(stream, &output_layout.layout)) || ++ FAILED(hr = configure_spatial_max_frames(stream))) ++ return hr; ++ ++ stream->dev_desc = output_desc; ++ TRACE("Using the spatial mixer for a %u-channel bed, %u PointSources, and %u output channels (type %u, algorithm %u).\n", ++ bed->Format.nChannels, stream->spatial_dynamic_objects, ++ output_layout.layout.mNumberChannelDescriptions, output_type, algorithm); ++ return S_OK; ++} ++ ++static AudioDeviceID dev_id_from_device(const char *device) ++{ ++ AudioDeviceID id; ++ CFStringRef uid; ++ UInt32 size; ++ OSStatus sc; ++ const AudioObjectPropertyAddress addr = ++ { ++ .mScope = kAudioObjectPropertyScopeGlobal, ++ .mElement = kAudioObjectPropertyElementMain, ++ .mSelector = kAudioHardwarePropertyTranslateUIDToDevice, + }; + + uid = CFStringCreateWithCStringNoCopy(NULL, device, kCFStringEncodingUTF8, kCFAllocatorNull); +@@ -721,35 +2586,386 @@ static AudioDeviceID dev_id_from_device(const char *device) + return id; + } + ++static UINT32 spatial_generation_hash(UINT32 hash, const void *data, size_t size) ++{ ++ const BYTE *bytes = data; ++ ++ while (size--) ++ { ++ hash ^= *bytes++; ++ hash *= 16777619u; ++ } ++ return hash; ++} ++ ++static HRESULT get_device_timing(AudioDeviceID dev_id, UINT32 *period_frames, ++ UINT32 *minimum_frames, UINT32 *sample_rate) ++{ ++ AudioObjectPropertyAddress addr = ++ { ++ .mSelector = kAudioDevicePropertyDeviceIsAlive, ++ .mScope = kAudioObjectPropertyScopeGlobal, ++ .mElement = kAudioObjectPropertyElementMain, ++ }; ++ AudioValueRange range; ++ Float64 rate; ++ UInt32 alive, frames, size; ++ OSStatus sc; ++ ++ size = sizeof(alive); ++ sc = AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, &alive); ++ if (sc != noErr || !alive) ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ ++ addr.mSelector = kAudioDevicePropertyBufferFrameSize; ++ size = sizeof(frames); ++ if ((sc = AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, ++ &frames)) != noErr || !frames) ++ return sc == noErr ? E_FAIL : osstatus_to_hresult(sc); ++ ++ addr.mSelector = kAudioDevicePropertyBufferFrameSizeRange; ++ size = sizeof(range); ++ if ((sc = AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, ++ &range)) != noErr || !isfinite(range.mMinimum) || ++ range.mMinimum < 1.0 || range.mMinimum > UINT32_MAX) ++ return sc == noErr ? E_FAIL : osstatus_to_hresult(sc); ++ ++ addr.mSelector = kAudioDevicePropertyNominalSampleRate; ++ size = sizeof(rate); ++ if ((sc = AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, ++ &rate)) != noErr || !isfinite(rate) || rate < 1.0 || ++ rate > UINT32_MAX) ++ return sc == noErr ? E_FAIL : osstatus_to_hresult(sc); ++ ++ *period_frames = frames; ++ *minimum_frames = (UINT32)ceil(range.mMinimum); ++ *sample_rate = (UINT32)llround(rate); ++ return S_OK; ++} ++ ++static void release_spatial_probe(struct coreaudio_stream *stream) ++{ ++ if (stream->unit_initialized) ++ AudioUnitUninitialize(stream->unit); ++ if (stream->spatial_unit_initialized) ++ AudioUnitUninitialize(stream->spatial_unit); ++ if (stream->spatial_unit) ++ AudioComponentInstanceDispose(stream->spatial_unit); ++ if (stream->unit) ++ AudioComponentInstanceDispose(stream->unit); ++ free(stream->spatial_bed_buffer); ++ free(stream->spatial_dry_buffer); ++ free(stream->spatial_dynamic_buffer); ++ free(stream->spatial_input_contexts); ++ free(stream->spatial_parameter_events); ++ free(stream->spatial_object_states); ++ free(stream->spatial_metadata_sequences); ++} ++ ++static HRESULT validate_spatial_dynamic_capacity(const char *device, ++ AudioDeviceID dev_id, UINT32 endpoint_period_frames, ++ UINT32 endpoint_sample_rate, UINT32 dynamic_objects) ++{ ++ struct coreaudio_stream probe = {0}; ++ WAVEFORMATEXTENSIBLE bed = {0}; ++ UINT64 period_time, object_period_frames; ++ HRESULT hr; ++ OSStatus sc; ++ ++ /* Windows exposes one 48 kHz object format even when the endpoint runs at ++ * another nominal rate. Probe the graph in that actual client format, ++ * leaving the output AudioUnit to perform its normal rate conversion. */ ++ period_time = ((UINT64)endpoint_period_frames * 10000000 + ++ endpoint_sample_rate / 2) / endpoint_sample_rate; ++ object_period_frames = (period_time * 48000 + 5000000) / 10000000; ++ if (!object_period_frames || object_period_frames > UINT32_MAX / 3) ++ return E_INVALIDARG; ++ ++ bed.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; ++ bed.Format.nChannels = 2; ++ bed.Format.nSamplesPerSec = 48000; ++ bed.Format.wBitsPerSample = 32; ++ bed.Format.nBlockAlign = 2 * sizeof(float); ++ bed.Format.nAvgBytesPerSec = bed.Format.nSamplesPerSec * ++ bed.Format.nBlockAlign; ++ bed.Format.cbSize = sizeof(bed) - sizeof(bed.Format); ++ bed.Samples.wValidBitsPerSample = 32; ++ bed.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; ++ bed.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; ++ ++ probe.dev_id = dev_id; ++ probe.spatial = TRUE; ++ probe.spatial_dynamic_objects = dynamic_objects; ++ probe.spatial_bed_channels = bed.Format.nChannels; ++ probe.spatial_dry_channel = 2; ++ probe.spatial_dynamic_channel = 3; ++ probe.period_frames = object_period_frames; ++ probe.bufsize_frames = probe.period_frames * 3; ++ if (!(probe.unit = get_audiounit(eRender, dev_id))) ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ ++ hr = ca_setup_spatial_audiounit(&probe, device, &bed); ++ if (SUCCEEDED(hr)) ++ { ++ sc = AudioUnitInitialize(probe.spatial_unit); ++ if (sc == noErr) ++ { ++ probe.spatial_unit_initialized = TRUE; ++ sc = AudioUnitInitialize(probe.unit); ++ } ++ if (sc == noErr) ++ probe.unit_initialized = TRUE; ++ else ++ hr = osstatus_to_hresult(sc); ++ } ++ release_spatial_probe(&probe); ++ return hr; ++} ++ ++static HRESULT query_spatial_audio_capabilities(const char *device, ++ struct spatial_audio_capabilities *capabilities, BOOL validate_graph) ++{ ++ struct spatial_output_layout layout, verify_layout; ++ UInt32 layout_size, verify_layout_size; ++ AudioComponentInstance mixer; ++ AudioDeviceID dev_id; ++ UInt32 minimum_frames, verify_minimum, input_buses, size; ++ UINT32 candidate, low, high, verify_period, verify_rate; ++ UINT32 hash = 2166136261u; ++ OSStatus sc; ++ HRESULT hr; ++ ++ memset(capabilities, 0, sizeof(*capabilities)); ++ if (!device || (dev_id = dev_id_from_device(device)) == kAudioObjectUnknown) ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ if (FAILED(hr = get_device_timing(dev_id, &capabilities->period_frames, ++ &minimum_frames, &capabilities->sample_rate)) || ++ FAILED(hr = get_spatial_output_layout(device, &layout, &layout_size))) ++ return hr; ++ ++ hash = spatial_generation_hash(hash, &dev_id, sizeof(dev_id)); ++ hash = spatial_generation_hash(hash, &capabilities->period_frames, ++ sizeof(capabilities->period_frames)); ++ hash = spatial_generation_hash(hash, &minimum_frames, ++ sizeof(minimum_frames)); ++ hash = spatial_generation_hash(hash, &capabilities->sample_rate, ++ sizeof(capabilities->sample_rate)); ++ hash = spatial_generation_hash(hash, &layout, layout_size); ++ capabilities->endpoint_generation = hash ? hash : 1; ++ ++ if (!(mixer = get_spatial_mixer())) ++ return S_OK; ++ size = sizeof(input_buses); ++ sc = AudioUnitGetProperty(mixer, kAudioUnitProperty_ElementCount, ++ kAudioUnitScope_Input, 0, &input_buses, &size); ++ AudioComponentInstanceDispose(mixer); ++ if (sc != noErr || input_buses <= 1) ++ return S_OK; ++ ++ capabilities->max_dynamic_objects = min(input_buses - 1, ++ SPATIAL_AUDIO_MAX_DYNAMIC_OBJECTS); ++ ++ if (!validate_graph || !capabilities->max_dynamic_objects) ++ return S_OK; ++ ++ /* A positive count is useful only if an activated stream can subscribe to ++ * every property needed to revoke that capacity safely. Probe with the ++ * same registration path used by stream creation so discovery and ++ * activation cannot disagree indefinitely on this endpoint. */ ++ hr = validate_spatial_device_listener_capability(dev_id); ++ if (FAILED(hr)) ++ { ++ if (hr == E_OUTOFMEMORY) ++ return hr; ++ capabilities->max_dynamic_objects = 0; ++ return S_OK; ++ } ++ ++ candidate = capabilities->max_dynamic_objects; ++ hr = validate_spatial_dynamic_capacity(device, dev_id, ++ capabilities->period_frames, capabilities->sample_rate, candidate); ++ if (FAILED(hr) && hr != E_OUTOFMEMORY) ++ { ++ /* ElementCount is only an upper bound. Some AudioUnits expose more ++ * buses than a concrete endpoint can initialize, so find the highest ++ * viable PointSource count without turning a mixer limitation into a ++ * static-stream or timing failure. */ ++ low = 0; ++ high = candidate - 1; ++ while (low < high) ++ { ++ candidate = low + (high - low + 1) / 2; ++ hr = validate_spatial_dynamic_capacity(device, dev_id, ++ capabilities->period_frames, capabilities->sample_rate, ++ candidate); ++ if (SUCCEEDED(hr)) ++ low = candidate; ++ else if (hr == E_OUTOFMEMORY) ++ return hr; ++ else ++ high = candidate - 1; ++ } ++ capabilities->max_dynamic_objects = low; ++ } ++ else if (FAILED(hr)) ++ return hr; ++ ++ /* A graph error is a supported max=0 fallback only while the endpoint ++ * queried above is still the same endpoint at the same timing. */ ++ if (FAILED(hr = get_device_timing(dev_id, &verify_period, ++ &verify_minimum, &verify_rate)) || ++ FAILED(hr = get_spatial_output_layout(device, &verify_layout, &verify_layout_size))) ++ return hr; ++ if (verify_period != capabilities->period_frames || ++ verify_minimum != minimum_frames || ++ verify_rate != capabilities->sample_rate || ++ verify_layout_size != layout_size || ++ memcmp(&verify_layout, &layout, layout_size)) ++ return AUDCLNT_E_DEVICE_INVALIDATED; ++ return S_OK; ++} ++ + static NTSTATUS unix_create_stream(void *args) + { + struct create_stream_params *params = args; ++ struct spatial_audio_capabilities capabilities; + struct coreaudio_stream *stream; ++ WAVEFORMATEXTENSIBLE spatial_bed = {0}; + AURenderCallbackStruct input; ++ kern_return_t kr; ++ HRESULT hr; + OSStatus sc; ++ int computed_frames; + SIZE_T size; + + params->result = S_OK; + +- if (!(stream = calloc(1, sizeof(*stream)))) { +- params->result = E_OUTOFMEMORY; +- return STATUS_SUCCESS; ++ if (!(stream = calloc(1, sizeof(*stream)))) { ++ params->result = E_OUTOFMEMORY; ++ return STATUS_SUCCESS; ++ } ++ ++ stream->fmt = clone_format(params->fmt); ++ if(!stream->fmt){ ++ params->result = E_OUTOFMEMORY; ++ goto end; ++ } ++ ++ stream->period = params->period; ++ computed_frames = muldiv(params->period, stream->fmt->nSamplesPerSec, ++ 10000000); ++ if (computed_frames <= 0) ++ { ++ params->result = E_INVALIDARG; ++ goto end; ++ } ++ stream->period_frames = computed_frames; ++ ++ stream->dev_id = dev_id_from_device(params->device); ++ stream->flow = params->flow; ++ stream->flags = params->flags; ++ stream->spatial = params->spatial; ++ stream->spatial_static_mask = params->spatial_static_mask; ++ stream->spatial_dynamic_objects = params->spatial_dynamic_objects; ++ stream->spatial_endpoint_generation = params->spatial_endpoint_generation; ++ stream->spatial_invalidation_event = params->spatial_invalidation_event; ++ stream->share = params->share; ++ if (stream->spatial) ++ { ++ kr = semaphore_create(mach_task_self(), ++ &stream->callback_drain_semaphore, SYNC_POLICY_FIFO, 0); ++ if (kr != KERN_SUCCESS) ++ { ++ params->result = E_OUTOFMEMORY; ++ goto end; ++ } ++ stream->callback_drain_semaphore_created = TRUE; ++ } ++ if (stream->spatial && (stream->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)) ++ { ++ kr = semaphore_create(mach_task_self(), &stream->event_semaphore, ++ SYNC_POLICY_FIFO, 0); ++ if (kr != KERN_SUCCESS) ++ { ++ params->result = E_OUTOFMEMORY; ++ goto end; ++ } ++ stream->event_semaphore_created = TRUE; ++ } ++ ++ if (stream->spatial) ++ { ++ UINT32 i; ++ ++ if (stream->flow != eRender || stream->share != AUDCLNT_SHAREMODE_SHARED) ++ { ++ params->result = E_INVALIDARG; ++ goto end; ++ } ++ if (FAILED(params->result = query_spatial_audio_capabilities( ++ params->device, &capabilities, FALSE))) ++ goto end; ++ if (stream->spatial_endpoint_generation && ++ stream->spatial_endpoint_generation != ++ capabilities.endpoint_generation) ++ { ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ goto end; ++ } ++ if (stream->spatial_dynamic_objects > ++ capabilities.max_dynamic_objects) ++ { ++ params->result = SPTLAUDCLNT_E_NO_MORE_OBJECTS; ++ goto end; ++ } ++ if (FAILED(params->result = get_spatial_bed_format(stream->fmt, ++ stream->spatial_static_mask, stream->spatial_dynamic_objects, ++ &spatial_bed, &stream->spatial_dry_channel, ++ &stream->spatial_dynamic_channel))) ++ goto end; ++ stream->spatial_bed_channels = spatial_bed.Format.nChannels; ++ ++ if (!(stream->spatial_volume_bits = malloc(stream->fmt->nChannels * ++ sizeof(*stream->spatial_volume_bits)))) ++ { ++ params->result = E_OUTOFMEMORY; ++ goto end; ++ } ++ for (i = 0; i < stream->fmt->nChannels; ++i) ++ { ++ float volume = 1.0f; ++ ++ memcpy(&stream->spatial_volume_bits[i], &volume, ++ sizeof(stream->spatial_volume_bits[i])); ++ } ++ stream->spatial_volumes_are_unity = TRUE; ++ if (getenv("SWITCHYARD_SPATIAL_AUDIO_PROFILE")) ++ { ++ if (!(stream->callback_timings = calloc( ++ SPATIAL_AUDIO_PROFILE_SAMPLES, ++ sizeof(*stream->callback_timings)))) ++ { ++ params->result = E_OUTOFMEMORY; ++ goto end; ++ } ++ stream->profile_callbacks = TRUE; ++ } ++ stream->fault_invalidate_on_start = ++ stream->spatial_dynamic_objects && ++ stream->spatial_invalidation_event && ++ params->spatial_fault_invalidate_on_start; ++ if (FAILED(params->result = register_spatial_device_listeners(stream))) ++ goto end; + } + +- stream->fmt = clone_format(params->fmt); +- if(!stream->fmt){ +- params->result = E_OUTOFMEMORY; ++ computed_frames = muldiv(params->duration, stream->fmt->nSamplesPerSec, ++ 10000000); ++ if (computed_frames <= 0) ++ { ++ params->result = E_INVALIDARG; + goto end; + } +- +- stream->period = params->period; +- stream->period_frames = muldiv(params->period, stream->fmt->nSamplesPerSec, 10000000); +- stream->dev_id = dev_id_from_device(params->device); +- stream->flow = params->flow; +- stream->flags = params->flags; +- stream->share = params->share; +- +- stream->bufsize_frames = muldiv(params->duration, stream->fmt->nSamplesPerSec, 10000000); ++ stream->bufsize_frames = computed_frames; + if(params->share == AUDCLNT_SHAREMODE_EXCLUSIVE) + stream->bufsize_frames -= stream->bufsize_frames % stream->period_frames; + +@@ -758,23 +2974,75 @@ static NTSTATUS unix_create_stream(void *args) + goto end; + } + +- params->result = ca_setup_audiounit(stream->flow, stream->unit, stream->fmt, &stream->dev_desc, &stream->converter); +- if(FAILED(params->result)) goto end; +- +- input.inputProcRefCon = stream; +- if(stream->flow == eCapture){ +- input.inputProc = ca_capture_cb; +- sc = AudioUnitSetProperty(stream->unit, kAudioOutputUnitProperty_SetInputCallback, +- kAudioUnitScope_Output, 1, &input, sizeof(input)); +- }else{ +- input.inputProc = ca_render_cb; +- sc = AudioUnitSetProperty(stream->unit, kAudioUnitProperty_SetRenderCallback, +- kAudioUnitScope_Input, 0, &input, sizeof(input)); ++ if (stream->spatial && ++ (stream->spatial_dynamic_objects || ++ get_device_spatial_output_type(stream->dev_id) == ++ kSpatialMixerOutputType_Headphones || ++ (spatial_bed.dwChannelMask & SPATIAL_AUDIO_PRIVATE_BED_SPEAKERS) || ++ !device_supports_spatial_format(params->device, &spatial_bed.Format))) ++ { ++ params->result = ca_setup_spatial_audiounit(stream, params->device, ++ &spatial_bed); ++ if (FAILED(params->result)) ++ goto end; + } +- if(sc != noErr){ +- WARN("Couldn't set callback: %x\n", (int)sc); +- params->result = osstatus_to_hresult(sc); +- goto end; ++ else ++ { ++ params->result = ca_setup_audiounit(stream->flow, stream->unit, ++ stream->spatial ? &spatial_bed.Format : stream->fmt, ++ &stream->dev_desc, &stream->converter); ++ if (FAILED(params->result)) ++ goto end; ++ ++ input.inputProcRefCon = stream; ++ if (stream->flow == eCapture) ++ { ++ input.inputProc = ca_capture_cb; ++ sc = AudioUnitSetProperty(stream->unit, kAudioOutputUnitProperty_SetInputCallback, ++ kAudioUnitScope_Output, 1, &input, sizeof(input)); ++ } ++ else ++ { ++ input.inputProc = stream->spatial ++ ? ca_native_spatial_render_cb : ca_render_cb; ++ sc = AudioUnitSetProperty(stream->unit, kAudioUnitProperty_SetRenderCallback, ++ kAudioUnitScope_Input, 0, &input, sizeof(input)); ++ if (stream->spatial) ++ { ++ stream->spatial_native_output = TRUE; ++ TRACE("Using lossless native output for a %u-channel spatial bed.\n", ++ spatial_bed.Format.nChannels); ++ } ++ } ++ if (sc != noErr) ++ { ++ WARN("Couldn't set callback: %x\n", (int)sc); ++ params->result = osstatus_to_hresult(sc); ++ goto end; ++ } ++ if (stream->spatial && ++ (FAILED(hr = configure_spatial_dry_output(stream, ++ spatial_bed.dwChannelMask, spatial_bed.Format.nChannels)) || ++ FAILED(hr = configure_spatial_max_frames(stream)))) ++ { ++ params->result = hr; ++ goto end; ++ } ++ } ++ ++ if (stream->spatial_unit) ++ { ++ sc = AudioUnitInitialize(stream->spatial_unit); ++ if (sc != noErr) ++ { ++ WARN("Couldn't initialize spatial mixer: %x\n", (int)sc); ++ params->result = osstatus_to_hresult(sc); ++ goto end; ++ } ++ stream->spatial_unit_initialized = TRUE; ++ ++ if (FAILED(params->result = configure_spatial_dry_delay(stream))) ++ goto end; + } + + if (stream->flow == eCapture) { +@@ -799,6 +3067,7 @@ static NTSTATUS unix_create_stream(void *args) + params->result = osstatus_to_hresult(sc); + goto end; + } ++ stream->unit_initialized = TRUE; + + /* we play audio continuously because AudioOutputUnitStart sometimes takes + * a while to return */ +@@ -808,8 +3077,14 @@ static NTSTATUS unix_create_stream(void *args) + params->result = osstatus_to_hresult(sc); + goto end; + } ++ stream->unit_started = TRUE; + +- size = stream->bufsize_frames * stream->fmt->nBlockAlign; ++ if (stream->bufsize_frames > SIZE_MAX / stream->fmt->nBlockAlign) ++ { ++ params->result = E_OUTOFMEMORY; ++ goto end; ++ } ++ size = (SIZE_T)stream->bufsize_frames * stream->fmt->nBlockAlign; + if(NtAllocateVirtualMemory(GetCurrentProcess(), (void **)&stream->local_buffer, zero_bits, + &size, MEM_COMMIT, PAGE_READWRITE)){ + params->result = E_OUTOFMEMORY; +@@ -817,16 +3092,98 @@ static NTSTATUS unix_create_stream(void *args) + } + silence_buffer(stream, stream->local_buffer, stream->bufsize_frames); + ++ if (stream->spatial) ++ { ++ size = (SIZE_T)stream->bufsize_frames * stream->fmt->nBlockAlign; ++ if (NtAllocateVirtualMemory(GetCurrentProcess(), ++ (void **)&stream->tmp_buffer, zero_bits, &size, MEM_COMMIT, ++ PAGE_READWRITE)) ++ { ++ params->result = E_OUTOFMEMORY; ++ goto end; ++ } ++ stream->tmp_buffer_frames = stream->bufsize_frames; ++ } ++ + if(stream->flow == eCapture){ + stream->cap_bufsize_frames = muldiv(params->duration, stream->dev_desc.mSampleRate, 10000000); +- stream->cap_buffer = malloc(stream->cap_bufsize_frames * stream->fmt->nBlockAlign); ++ if (stream->cap_bufsize_frames > SIZE_MAX / stream->fmt->nBlockAlign || ++ !(stream->cap_buffer = malloc((size_t)stream->cap_bufsize_frames * ++ stream->fmt->nBlockAlign))) ++ { ++ params->result = E_OUTOFMEMORY; ++ goto end; ++ } ++ } ++ if (stream->spatial) ++ { ++ struct spatial_audio_capabilities verified; ++ ++ /* Close the activation/listener registration window. A device can ++ * change after the caller's capability snapshot but before the graph ++ * is constructed; re-snapshot after graph initialization, then drain ++ * every property callback queued before this point. */ ++ params->result = query_spatial_audio_capabilities(params->device, ++ &verified, FALSE); ++ if (SUCCEEDED(params->result) && stream->device_listener_queue) ++ dispatch_sync_f(stream->device_listener_queue, NULL, ++ dispatch_barrier_noop); ++ if (SUCCEEDED(params->result) && ++ (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE) || ++ (stream->spatial_endpoint_generation && ++ verified.endpoint_generation != ++ stream->spatial_endpoint_generation) || ++ stream->spatial_dynamic_objects > ++ verified.max_dynamic_objects)) ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ if (FAILED(params->result)) ++ goto end; + } + params->result = S_OK; + + end: + if(FAILED(params->result)){ + if(stream->converter) AudioConverterDispose(stream->converter); ++ __atomic_store_n(&stream->shutting_down, TRUE, __ATOMIC_RELEASE); ++ unregister_spatial_device_listeners(stream); ++ if (stream->unit_started) ++ { ++ AudioOutputUnitStop(stream->unit); ++ if (stream->spatial) ++ wait_for_spatial_callbacks(stream); ++ } ++ if (stream->unit_initialized) AudioUnitUninitialize(stream->unit); ++ if (stream->spatial_unit_initialized) AudioUnitUninitialize(stream->spatial_unit); ++ if (stream->spatial_unit) AudioComponentInstanceDispose(stream->spatial_unit); + if(stream->unit) AudioComponentInstanceDispose(stream->unit); ++ free(stream->spatial_volume_bits); ++ free(stream->spatial_bed_buffer); ++ free(stream->spatial_dry_buffer); ++ free(stream->spatial_dry_delay_buffer); ++ free(stream->spatial_dynamic_buffer); ++ free(stream->spatial_input_contexts); ++ free(stream->spatial_parameter_events); ++ free(stream->spatial_object_states); ++ free(stream->spatial_metadata_sequences); ++ free(stream->callback_timings); ++ free(stream->cap_buffer); ++ if (stream->local_buffer) ++ { ++ size = 0; ++ NtFreeVirtualMemory(GetCurrentProcess(), ++ (void **)&stream->local_buffer, &size, MEM_RELEASE); ++ } ++ if (stream->tmp_buffer) ++ { ++ size = 0; ++ NtFreeVirtualMemory(GetCurrentProcess(), ++ (void **)&stream->tmp_buffer, &size, MEM_RELEASE); ++ } ++ if (stream->event_semaphore_created) ++ semaphore_destroy(mach_task_self(), stream->event_semaphore); ++ if (stream->callback_drain_semaphore_created) ++ semaphore_destroy(mach_task_self(), ++ stream->callback_drain_semaphore); + free(stream->fmt); + free(stream); + } else { +@@ -837,24 +3194,102 @@ end: + return STATUS_SUCCESS; + } + ++static int compare_uint64(const void *left, const void *right) ++{ ++ UINT64 a = *(const UINT64 *)left; ++ UINT64 b = *(const UINT64 *)right; ++ ++ return a < b ? -1 : a > b; ++} ++ ++static UINT64 spatial_profile_nanoseconds(UINT64 ticks, ++ const mach_timebase_info_data_t *timebase) ++{ ++ long double value = (long double)ticks * timebase->numer / timebase->denom; ++ ++ return (UINT64)value; ++} ++ ++static void report_spatial_profile(struct coreaudio_stream *stream) ++{ ++ mach_timebase_info_data_t timebase; ++ UINT32 count; ++ ++ if (!stream->profile_callbacks) ++ return; ++ count = min(__atomic_load_n(&stream->callback_timing_count, ++ __ATOMIC_ACQUIRE), SPATIAL_AUDIO_PROFILE_SAMPLES); ++ if (!count || mach_timebase_info(&timebase) != KERN_SUCCESS) ++ return; ++ ++ qsort(stream->callback_timings, count, sizeof(*stream->callback_timings), ++ compare_uint64); ++ TRACE("Spatial callback profile: native %u, dynamic objects %u, samples %u, p50 %llu ns, p95 %llu ns, p99 %llu ns, underruns %llu, overruns %llu, reentrant rejects %llu, callback allocations 0.\n", ++ stream->spatial_native_output, stream->spatial_dynamic_objects, ++ count, (unsigned long long)spatial_profile_nanoseconds( ++ stream->callback_timings[(count - 1) * 50 / 100], &timebase), ++ (unsigned long long)spatial_profile_nanoseconds( ++ stream->callback_timings[(count - 1) * 95 / 100], &timebase), ++ (unsigned long long)spatial_profile_nanoseconds( ++ stream->callback_timings[(count - 1) * 99 / 100], &timebase), ++ (unsigned long long)__atomic_load_n(&stream->underruns, ++ __ATOMIC_RELAXED), ++ (unsigned long long)__atomic_load_n(&stream->overruns, ++ __ATOMIC_RELAXED), ++ (unsigned long long)__atomic_load_n(&stream->reentrant_callbacks, ++ __ATOMIC_RELAXED)); ++} ++ + static NTSTATUS unix_release_stream( void *args ) + { + struct release_stream_params *params = args; + struct coreaudio_stream *stream = handle_get_stream(params->stream); + SIZE_T size; + ++ __atomic_store_n(&stream->shutting_down, TRUE, __ATOMIC_RELEASE); ++ unregister_spatial_device_listeners(stream); + if(params->timer_thread){ +- stream->please_quit = TRUE; ++ __atomic_store_n(&stream->please_quit, TRUE, __ATOMIC_RELEASE); ++ if (stream->event_semaphore_created) ++ semaphore_signal(stream->event_semaphore); + NtWaitForSingleObject(params->timer_thread, FALSE, NULL); + NtClose(params->timer_thread); + } + + if(stream->unit){ +- AudioOutputUnitStop(stream->unit); +- AudioComponentInstanceDispose(stream->unit); ++ if (stream->unit_started) ++ { ++ AudioOutputUnitStop(stream->unit); ++ if (stream->spatial) ++ wait_for_spatial_callbacks(stream); ++ } ++ if (stream->unit_initialized) AudioUnitUninitialize(stream->unit); ++ } ++ if (stream->spatial_unit) ++ { ++ if (stream->spatial_unit_initialized) AudioUnitUninitialize(stream->spatial_unit); ++ AudioComponentInstanceDispose(stream->spatial_unit); + } ++ if (stream->unit) ++ AudioComponentInstanceDispose(stream->unit); ++ ++ report_spatial_profile(stream); + + if(stream->converter) AudioConverterDispose(stream->converter); ++ free(stream->spatial_volume_bits); ++ free(stream->spatial_bed_buffer); ++ free(stream->spatial_dry_buffer); ++ free(stream->spatial_dry_delay_buffer); ++ free(stream->spatial_dynamic_buffer); ++ free(stream->spatial_input_contexts); ++ free(stream->spatial_parameter_events); ++ free(stream->spatial_object_states); ++ free(stream->spatial_metadata_sequences); ++ free(stream->callback_timings); ++ if (stream->event_semaphore_created) ++ semaphore_destroy(mach_task_self(), stream->event_semaphore); ++ if (stream->callback_drain_semaphore_created) ++ semaphore_destroy(mach_task_self(), stream->callback_drain_semaphore); + free(stream->resamp_buffer); + free(stream->wrap_buffer); + free(stream->cap_buffer); +@@ -888,18 +3323,28 @@ static UINT ca_channel_layout_to_channel_mask(const AudioChannelLayout *layout) + case kAudioChannelLabel_Mono: + case kAudioChannelLabel_Center: mask |= SPEAKER_FRONT_CENTER; break; + case kAudioChannelLabel_Right: mask |= SPEAKER_FRONT_RIGHT; break; ++ case kAudioChannelLabel_RearSurroundLeft: ++ case kAudioChannelLabel_LeftBackSurround: + case kAudioChannelLabel_LeftSurround: mask |= SPEAKER_BACK_LEFT; break; ++ case kAudioChannelLabel_CenterSurroundDirect: + case kAudioChannelLabel_CenterSurround: mask |= SPEAKER_BACK_CENTER; break; ++ case kAudioChannelLabel_RearSurroundRight: ++ case kAudioChannelLabel_RightBackSurround: + case kAudioChannelLabel_RightSurround: mask |= SPEAKER_BACK_RIGHT; break; + case kAudioChannelLabel_LFEScreen: mask |= SPEAKER_LOW_FREQUENCY; break; ++ case kAudioChannelLabel_LeftSideSurround: + case kAudioChannelLabel_LeftSurroundDirect: mask |= SPEAKER_SIDE_LEFT; break; ++ case kAudioChannelLabel_RightSideSurround: + case kAudioChannelLabel_RightSurroundDirect: mask |= SPEAKER_SIDE_RIGHT; break; + case kAudioChannelLabel_TopCenterSurround: mask |= SPEAKER_TOP_CENTER; break; + case kAudioChannelLabel_VerticalHeightLeft: mask |= SPEAKER_TOP_FRONT_LEFT; break; + case kAudioChannelLabel_VerticalHeightCenter: mask |= SPEAKER_TOP_FRONT_CENTER; break; + case kAudioChannelLabel_VerticalHeightRight: mask |= SPEAKER_TOP_FRONT_RIGHT; break; ++ case kAudioChannelLabel_LeftTopRear: + case kAudioChannelLabel_TopBackLeft: mask |= SPEAKER_TOP_BACK_LEFT; break; ++ case kAudioChannelLabel_CenterTopRear: + case kAudioChannelLabel_TopBackCenter: mask |= SPEAKER_TOP_BACK_CENTER; break; ++ case kAudioChannelLabel_RightTopRear: + case kAudioChannelLabel_TopBackRight: mask |= SPEAKER_TOP_BACK_RIGHT; break; + case kAudioChannelLabel_LeftCenter: mask |= SPEAKER_FRONT_LEFT_OF_CENTER; break; + case kAudioChannelLabel_RightCenter: mask |= SPEAKER_FRONT_RIGHT_OF_CENTER; break; +@@ -1142,17 +3587,42 @@ static NTSTATUS unix_is_format_supported(void *args) + static NTSTATUS unix_get_device_period(void *args) + { + struct get_device_period_params *params = args; ++ AudioDeviceID dev_id; ++ UINT32 frames, minimum_frames, rate; ++ HRESULT hr; ++ ++ if (!params->device || ++ (dev_id = dev_id_from_device(params->device)) == kAudioObjectUnknown) ++ { ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ return STATUS_SUCCESS; ++ } ++ if (FAILED(hr = get_device_timing(dev_id, &frames, &minimum_frames, ++ &rate))) ++ { ++ params->result = hr; ++ return STATUS_SUCCESS; ++ } + + if (params->def_period) +- *params->def_period = def_period; ++ *params->def_period = ((UINT64)frames * 10000000 + rate / 2) / rate; + if (params->min_period) +- *params->min_period = min_period; +- ++ *params->min_period = ((UINT64)minimum_frames * 10000000 + rate / 2) / ++ rate; + params->result = S_OK; + + return STATUS_SUCCESS; + } + ++static NTSTATUS unix_get_spatial_audio_capabilities(void *args) ++{ ++ struct get_spatial_audio_capabilities_params *params = args; ++ ++ params->result = query_spatial_audio_capabilities(params->device, ++ ¶ms->capabilities, TRUE); ++ return STATUS_SUCCESS; ++} ++ + static UINT buf_ptr_diff(UINT left, UINT right, UINT bufsize) + { + if(left <= right) +@@ -1321,12 +3791,23 @@ static NTSTATUS unix_get_latency(void *args) + { + struct get_latency_params *params = args; + struct coreaudio_stream *stream = handle_get_stream(params->stream); +- UInt32 latency, stream_latency, size; ++ AudioDeviceID dev_id = stream->dev_id; ++ UINT32 period_frames, minimum_frames, sample_rate; ++ UInt32 latency, safety_offset, stream_latency, size; ++ UINT64 device_frames, latency_time; + AudioObjectPropertyAddress addr; ++ HRESULT hr; + OSStatus sc; + + os_unfair_lock_lock(&stream->lock); + ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ { ++ os_unfair_lock_unlock(&stream->lock); ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ return STATUS_SUCCESS; ++ } ++ + addr.mScope = get_scope(stream->flow); + addr.mSelector = kAudioDevicePropertyLatency; + addr.mElement = 0; +@@ -1346,10 +3827,56 @@ static NTSTATUS unix_get_latency(void *args) + return STATUS_SUCCESS; + } + +- latency += stream_latency; +- /* pretend we process audio in Period chunks, so max latency includes +- * the period time */ +- *params->latency = muldiv(latency, 10000000, stream->fmt->nSamplesPerSec) + stream->period; ++ addr.mSelector = kAudioDevicePropertySafetyOffset; ++ size = sizeof(safety_offset); ++ sc = AudioObjectGetPropertyData(dev_id, &addr, 0, NULL, &size, ++ &safety_offset); ++ if (sc != noErr) ++ { ++ WARN("Couldn't get _SafetyOffset property: %x\n", (int)sc); ++ os_unfair_lock_unlock(&stream->lock); ++ params->result = osstatus_to_hresult(sc); ++ return STATUS_SUCCESS; ++ } ++ if (FAILED(hr = get_device_timing(dev_id, &period_frames, ++ &minimum_frames, &sample_rate))) ++ { ++ os_unfair_lock_unlock(&stream->lock); ++ params->result = hr; ++ return STATUS_SUCCESS; ++ } ++ ++ device_frames = (UINT64)latency + safety_offset + stream_latency; ++ if (device_frames > (~(UINT64)0 - sample_rate + 1) / 10000000) ++ { ++ os_unfair_lock_unlock(&stream->lock); ++ params->result = E_FAIL; ++ return STATUS_SUCCESS; ++ } ++ latency_time = (device_frames * 10000000 + sample_rate - 1) / ++ sample_rate; ++ if (latency_time > INT64_MAX - stream->period) ++ { ++ os_unfair_lock_unlock(&stream->lock); ++ params->result = E_FAIL; ++ return STATUS_SUCCESS; ++ } ++ /* Include one producer quantum in the worst-case stream latency. */ ++ *params->latency = latency_time + stream->period; ++ if (stream->spatial_dry_delay_frames) ++ { ++ UINT64 spatial_time = ((UINT64)stream->spatial_dry_delay_frames * ++ 10000000 + stream->fmt->nSamplesPerSec - 1) / ++ stream->fmt->nSamplesPerSec; ++ ++ if (spatial_time > INT64_MAX - *params->latency) ++ { ++ os_unfair_lock_unlock(&stream->lock); ++ params->result = E_FAIL; ++ return STATUS_SUCCESS; ++ } ++ *params->latency += spatial_time; ++ } + + os_unfair_lock_unlock(&stream->lock); + params->result = S_OK; +@@ -1358,6 +3885,17 @@ static NTSTATUS unix_get_latency(void *args) + + static UINT32 get_current_padding_nolock(struct coreaudio_stream *stream) + { ++ if (stream->spatial) ++ { ++ UINT64 read_frame = __atomic_load_n(&stream->spatial_read_frames, ++ __ATOMIC_ACQUIRE); ++ UINT64 write_frame = __atomic_load_n(&stream->spatial_write_frames, ++ __ATOMIC_ACQUIRE); ++ ++ if (write_frame < read_frame) ++ return 0; ++ return min(write_frame - read_frame, stream->bufsize_frames); ++ } + if(stream->flow == eCapture) capture_resample(stream); + return stream->held_frames; + } +@@ -1368,9 +3906,14 @@ static NTSTATUS unix_get_current_padding(void *args) + struct coreaudio_stream *stream = handle_get_stream(params->stream); + + os_unfair_lock_lock(&stream->lock); +- *params->padding = get_current_padding_nolock(stream); ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ else ++ { ++ *params->padding = get_current_padding_nolock(stream); ++ params->result = S_OK; ++ } + os_unfair_lock_unlock(&stream->lock); +- params->result = S_OK; + return STATUS_SUCCESS; + } + +@@ -1381,16 +3924,25 @@ static NTSTATUS unix_start(void *args) + + os_unfair_lock_lock(&stream->lock); + +- if((stream->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !stream->event) ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ else if((stream->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !stream->event) + params->result = AUDCLNT_E_EVENTHANDLE_NOT_SET; +- else if(stream->playing) ++ else if(__atomic_load_n(&stream->playing, __ATOMIC_ACQUIRE)) + params->result = AUDCLNT_E_NOT_STOPPED; + else{ +- stream->playing = TRUE; ++ __atomic_store_n(&stream->playing, TRUE, __ATOMIC_RELEASE); + params->result = S_OK; + } + + os_unfair_lock_unlock(&stream->lock); ++ if (SUCCEEDED(params->result) && stream->spatial) ++ { ++ signal_spatial_event(stream); ++ if (__atomic_exchange_n(&stream->fault_invalidate_on_start, FALSE, ++ __ATOMIC_ACQ_REL)) ++ invalidate_spatial_stream_rt(stream); ++ } + + return STATUS_SUCCESS; + } +@@ -1402,10 +3954,12 @@ static NTSTATUS unix_stop(void *args) + + os_unfair_lock_lock(&stream->lock); + +- if(!stream->playing) ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ else if(!__atomic_load_n(&stream->playing, __ATOMIC_ACQUIRE)) + params->result = S_FALSE; + else{ +- stream->playing = FALSE; ++ __atomic_store_n(&stream->playing, FALSE, __ATOMIC_RELEASE); + params->result = S_OK; + } + +@@ -1414,31 +3968,105 @@ static NTSTATUS unix_stop(void *args) + return STATUS_SUCCESS; + } + ++static void wait_for_spatial_callbacks(struct coreaudio_stream *stream) ++{ ++ while (__atomic_load_n(&stream->spatial_callbacks_inflight, ++ __ATOMIC_ACQUIRE)) ++ semaphore_wait(stream->callback_drain_semaphore); ++} ++ ++static void wait_for_device_callbacks(struct coreaudio_stream *stream) ++{ ++ LARGE_INTEGER delay; ++ ++ delay.QuadPart = -10000; /* One millisecond, off the real-time thread. */ ++ while (__atomic_load_n(&stream->device_callbacks_inflight, ++ __ATOMIC_ACQUIRE)) ++ NtDelayExecution(FALSE, &delay); ++} ++ + static NTSTATUS unix_reset(void *args) + { + struct reset_params *params = args; + struct coreaudio_stream *stream = handle_get_stream(params->stream); ++ BOOL reset_spatial = FALSE; ++ OSStatus sc; + + os_unfair_lock_lock(&stream->lock); + +- if(stream->playing) ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ else if(__atomic_load_n(&stream->playing, __ATOMIC_ACQUIRE)) + params->result = AUDCLNT_E_NOT_STOPPED; + else if(stream->getbuf_last) + params->result = AUDCLNT_E_BUFFER_OPERATION_PENDING; + else{ +- if(stream->flow == eRender) +- stream->written_frames = 0; ++ if (stream->spatial) ++ { ++ reset_spatial = TRUE; ++ __atomic_store_n(&stream->spatial_resetting, TRUE, ++ __ATOMIC_RELEASE); ++ } + else +- stream->written_frames += stream->held_frames; ++ { ++ if(stream->flow == eRender) ++ stream->written_frames = 0; ++ else ++ stream->written_frames += stream->held_frames; ++ stream->held_frames = 0; ++ stream->lcl_offs_frames = 0; ++ stream->wri_offs_frames = 0; ++ stream->cap_offs_frames = 0; ++ stream->cap_held_frames = 0; ++ if (stream->spatial_dry_delay_frames) ++ { ++ memset(stream->spatial_dry_delay_buffer, 0, ++ stream->spatial_dry_delay_frames * ++ sizeof(*stream->spatial_dry_delay_buffer)); ++ stream->spatial_dry_delay_pos = 0; ++ } ++ } ++ params->result = S_OK; ++ } ++ ++ os_unfair_lock_unlock(&stream->lock); ++ ++ if (reset_spatial) ++ { ++ UINT32 i; ++ ++ wait_for_spatial_callbacks(stream); ++ os_unfair_lock_lock(&stream->lock); ++ stream->written_frames = 0; + stream->held_frames = 0; + stream->lcl_offs_frames = 0; + stream->wri_offs_frames = 0; + stream->cap_offs_frames = 0; + stream->cap_held_frames = 0; +- params->result = S_OK; ++ if (stream->spatial_dry_delay_frames) ++ { ++ memset(stream->spatial_dry_delay_buffer, 0, ++ stream->spatial_dry_delay_frames * ++ sizeof(*stream->spatial_dry_delay_buffer)); ++ stream->spatial_dry_delay_pos = 0; ++ } ++ __atomic_store_n(&stream->spatial_read_frames, 0, __ATOMIC_RELEASE); ++ __atomic_store_n(&stream->spatial_write_frames, 0, __ATOMIC_RELEASE); ++ for (i = 0; i < stream->spatial_metadata_capacity; ++i) ++ __atomic_store_n(&stream->spatial_metadata_sequences[i], UINT64_MAX, ++ __ATOMIC_RELEASE); ++ os_unfair_lock_unlock(&stream->lock); ++ ++ sc = stream->spatial_unit ? AudioUnitReset(stream->spatial_unit, ++ kAudioUnitScope_Global, 0) : noErr; ++ __atomic_store_n(&stream->spatial_resetting, FALSE, __ATOMIC_RELEASE); ++ if (sc != noErr) ++ { ++ WARN("Failed to reset spatial mixer state: %x.\n", (int)sc); ++ params->result = osstatus_to_hresult(sc); ++ } + } + +- os_unfair_lock_unlock(&stream->lock); + return STATUS_SUCCESS; + } + +@@ -1449,11 +4077,28 @@ static NTSTATUS unix_timer_loop(void *args) + LARGE_INTEGER delay, next, last; + int adjust; + ++ if (stream->spatial) ++ { ++ while (!__atomic_load_n(&stream->please_quit, __ATOMIC_ACQUIRE)) ++ { ++ semaphore_wait(stream->event_semaphore); ++ if (__atomic_load_n(&stream->please_quit, __ATOMIC_ACQUIRE)) ++ break; ++ __atomic_store_n(&stream->event_pending, 0, __ATOMIC_RELEASE); ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE) && ++ stream->spatial_invalidation_event) ++ NtSetEvent(stream->spatial_invalidation_event, NULL); ++ if (__atomic_load_n(&stream->playing, __ATOMIC_ACQUIRE) && stream->event) ++ NtSetEvent(stream->event, NULL); ++ } ++ return STATUS_SUCCESS; ++ } ++ + delay.QuadPart = -stream->period; + NtQueryPerformanceCounter(&last, NULL); + next.QuadPart = last.QuadPart + stream->period; + +- while(!stream->please_quit){ ++ while(!__atomic_load_n(&stream->please_quit, __ATOMIC_ACQUIRE)){ + NtSetEvent(stream->event, NULL); + NtDelayExecution(FALSE, &delay); + NtQueryPerformanceCounter(&last, NULL); +@@ -1480,6 +4125,12 @@ static NTSTATUS unix_get_render_buffer(void *args) + + os_unfair_lock_lock(&stream->lock); + ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ { ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ goto end; ++ } ++ + pad = get_current_padding_nolock(stream); + + if(stream->getbuf_last){ +@@ -1490,7 +4141,10 @@ static NTSTATUS unix_get_render_buffer(void *args) + params->result = S_OK; + goto end; + } +- if(pad + params->frames > stream->bufsize_frames){ ++ if (pad > stream->bufsize_frames || ++ params->frames > stream->bufsize_frames - pad){ ++ if (stream->spatial) ++ __atomic_add_fetch(&stream->overruns, 1, __ATOMIC_RELAXED); + params->result = AUDCLNT_E_BUFFER_TOO_LARGE; + goto end; + } +@@ -1532,11 +4186,18 @@ static NTSTATUS unix_release_render_buffer(void *args) + { + struct release_render_buffer_params *params = args; + struct coreaudio_stream *stream = handle_get_stream(params->stream); ++ UINT64 spatial_write = 0, sequence; ++ UINT32 record, slot; + BYTE *buffer; + + os_unfair_lock_lock(&stream->lock); + +- if(!params->written_frames){ ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ { ++ stream->getbuf_last = 0; ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ } ++ else if(!params->written_frames){ + stream->getbuf_last = 0; + params->result = S_OK; + }else if(!stream->getbuf_last) +@@ -1544,6 +4205,31 @@ static NTSTATUS unix_release_render_buffer(void *args) + else if(params->written_frames > (stream->getbuf_last >= 0 ? stream->getbuf_last : -stream->getbuf_last)) + params->result = AUDCLNT_E_INVALID_SIZE; + else{ ++ if (stream->spatial) ++ { ++ spatial_write = __atomic_load_n(&stream->spatial_write_frames, ++ __ATOMIC_RELAXED); ++ if (params->spatial_object_count != ++ stream->spatial_dynamic_objects || ++ (params->spatial_object_count && !params->spatial_objects) || ++ spatial_write % stream->period_frames || ++ params->written_frames != stream->period_frames) ++ { ++ params->result = E_INVALIDARG; ++ goto done; ++ } ++ for (slot = 0; slot < params->spatial_object_count; ++slot) ++ if (params->spatial_objects[slot].active_frames > ++ params->written_frames || ++ !isfinite(params->spatial_objects[slot].x) || ++ !isfinite(params->spatial_objects[slot].y) || ++ !isfinite(params->spatial_objects[slot].z)) ++ { ++ params->result = E_INVALIDARG; ++ goto done; ++ } ++ } ++ + if(stream->getbuf_last >= 0) + buffer = stream->local_buffer + stream->wri_offs_frames * stream->fmt->nBlockAlign; + else +@@ -1558,15 +4244,33 @@ static NTSTATUS unix_release_render_buffer(void *args) + stream->bufsize_frames * stream->fmt->nBlockAlign, + buffer, params->written_frames * stream->fmt->nBlockAlign); + ++ if (stream->spatial_dynamic_objects) ++ { ++ sequence = spatial_write / stream->period_frames; ++ record = sequence % stream->spatial_metadata_capacity; ++ for (slot = 0; slot < stream->spatial_dynamic_objects; ++slot) ++ spatial_position_to_parameters(¶ms->spatial_objects[slot], ++ &stream->spatial_object_states[(size_t)record * ++ stream->spatial_dynamic_objects + slot]); ++ __atomic_store_n(&stream->spatial_metadata_sequences[record], ++ sequence, __ATOMIC_RELEASE); ++ } ++ + stream->wri_offs_frames += params->written_frames; + stream->wri_offs_frames %= stream->bufsize_frames; +- stream->held_frames += params->written_frames; ++ if (!stream->spatial) ++ stream->held_frames += params->written_frames; + stream->written_frames += params->written_frames; + stream->getbuf_last = 0; + ++ if (stream->spatial) ++ __atomic_store_n(&stream->spatial_write_frames, ++ spatial_write + params->written_frames, __ATOMIC_RELEASE); ++ + params->result = S_OK; + } + ++done: + os_unfair_lock_unlock(&stream->lock); + + return STATUS_SUCCESS; +@@ -1690,7 +4394,17 @@ static NTSTATUS unix_get_position(void *args) + + os_unfair_lock_lock(&stream->lock); + +- *params->pos = stream->written_frames - stream->held_frames; ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ { ++ os_unfair_lock_unlock(&stream->lock); ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ return STATUS_SUCCESS; ++ } ++ if (stream->spatial) ++ *params->pos = __atomic_load_n(&stream->spatial_read_frames, ++ __ATOMIC_ACQUIRE); ++ else ++ *params->pos = stream->written_frames - stream->held_frames; + + if(stream->share == AUDCLNT_SHAREMODE_SHARED) + *params->pos *= stream->fmt->nBlockAlign; +@@ -1725,7 +4439,9 @@ static NTSTATUS unix_is_started(void *args) + struct is_started_params *params = args; + struct coreaudio_stream *stream = handle_get_stream(params->stream); + +- if(stream->playing) ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ else if(__atomic_load_n(&stream->playing, __ATOMIC_ACQUIRE)) + params->result = S_OK; + else + params->result = S_FALSE; +@@ -1755,6 +4471,30 @@ static NTSTATUS unix_set_volumes(void *args) + kAudioObjectPropertyElementMain + }; + ++ if (stream->spatial) ++ { ++ BOOL unity = params->master_volume == 1.0f; ++ ++ os_unfair_lock_lock(&stream->lock); ++ ++ for (i = 0; i < stream->fmt->nChannels; ++i) ++ { ++ UINT32 bits; ++ float volume = params->master_volume * params->session_volumes[i] * ++ params->volumes[i]; ++ ++ memcpy(&bits, &volume, sizeof(bits)); ++ __atomic_store_n(&stream->spatial_volume_bits[i], bits, ++ __ATOMIC_RELAXED); ++ if (volume != 1.0f) ++ unity = FALSE; ++ } ++ __atomic_store_n(&stream->spatial_volumes_are_unity, unity, ++ __ATOMIC_RELEASE); ++ os_unfair_lock_unlock(&stream->lock); ++ return STATUS_SUCCESS; ++ } ++ + sc = AudioObjectSetPropertyData(stream->dev_id, &prop_addr, 0, NULL, sizeof(float), &level); + if (sc == noErr) + level = 1.0f; +@@ -1782,7 +4522,9 @@ static NTSTATUS unix_set_event_handle(void *args) + HRESULT hr = S_OK; + + os_unfair_lock_lock(&stream->lock); +- if(!stream->unit) ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ hr = AUDCLNT_E_DEVICE_INVALIDATED; ++ else if(!stream->unit) + hr = AUDCLNT_E_DEVICE_INVALIDATED; + else if(!(stream->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)) + hr = AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED; +@@ -1835,6 +4577,7 @@ const unixlib_entry_t __wine_unix_call_funcs[] = + unix_midi_in_message, + unix_midi_notify_wait, + unix_not_implemented, ++ unix_get_spatial_audio_capabilities, + }; + + C_ASSERT(ARRAYSIZE(__wine_unix_call_funcs) == funcs_count); +@@ -1890,6 +4633,12 @@ static NTSTATUS unix_wow64_create_stream(void *args) + EDataFlow flow; + AUDCLNT_SHAREMODE share; + DWORD flags; ++ BOOL spatial; ++ UINT32 spatial_static_mask; ++ UINT32 spatial_dynamic_objects; ++ UINT32 spatial_endpoint_generation; ++ PTR32 spatial_invalidation_event; ++ BOOL spatial_fault_invalidate_on_start; + REFERENCE_TIME duration; + REFERENCE_TIME period; + PTR32 fmt; +@@ -1904,6 +4653,15 @@ static NTSTATUS unix_wow64_create_stream(void *args) + .flow = params32->flow, + .share = params32->share, + .flags = params32->flags, ++ .spatial = params32->spatial, ++ .spatial_static_mask = params32->spatial_static_mask, ++ .spatial_dynamic_objects = params32->spatial_dynamic_objects, ++ .spatial_endpoint_generation = ++ params32->spatial_endpoint_generation, ++ .spatial_invalidation_event = ULongToPtr( ++ params32->spatial_invalidation_event), ++ .spatial_fault_invalidate_on_start = ++ params32->spatial_fault_invalidate_on_start, + .duration = params32->duration, + .period = params32->period, + .fmt = ULongToPtr(params32->fmt), +@@ -1955,6 +4713,50 @@ static NTSTATUS unix_wow64_get_render_buffer(void *args) + return STATUS_SUCCESS; + } + ++static NTSTATUS unix_wow64_release_render_buffer(void *args) ++{ ++ struct ++ { ++ stream_handle stream; ++ UINT32 written_frames; ++ UINT flags; ++ PTR32 spatial_objects; ++ UINT32 spatial_object_count; ++ HRESULT result; ++ } *params32 = args; ++ struct release_render_buffer_params params = ++ { ++ .stream = params32->stream, ++ .written_frames = params32->written_frames, ++ .flags = params32->flags, ++ .spatial_objects = ULongToPtr(params32->spatial_objects), ++ .spatial_object_count = params32->spatial_object_count, ++ }; ++ ++ unix_release_render_buffer(¶ms); ++ params32->result = params.result; ++ return STATUS_SUCCESS; ++} ++ ++static NTSTATUS unix_wow64_get_spatial_audio_capabilities(void *args) ++{ ++ struct ++ { ++ PTR32 device; ++ HRESULT result; ++ struct spatial_audio_capabilities capabilities; ++ } *params32 = args; ++ struct get_spatial_audio_capabilities_params params = ++ { ++ .device = ULongToPtr(params32->device), ++ }; ++ ++ unix_get_spatial_audio_capabilities(¶ms); ++ params32->result = params.result; ++ params32->capabilities = params.capabilities; ++ return STATUS_SUCCESS; ++} ++ + static NTSTATUS unix_wow64_get_capture_buffer(void *args) + { + struct +@@ -2265,7 +5067,7 @@ const unixlib_entry_t __wine_unix_call_wow64_funcs[] = + unix_reset, + unix_timer_loop, + unix_wow64_get_render_buffer, +- unix_release_render_buffer, ++ unix_wow64_release_render_buffer, + unix_wow64_get_capture_buffer, + unix_release_capture_buffer, + unix_wow64_is_format_supported, +@@ -2291,6 +5093,7 @@ const unixlib_entry_t __wine_unix_call_wow64_funcs[] = + unix_wow64_midi_in_message, + unix_wow64_midi_notify_wait, + unix_not_implemented, ++ unix_wow64_get_spatial_audio_capabilities, + }; + + C_ASSERT(ARRAYSIZE(__wine_unix_call_wow64_funcs) == funcs_count); diff --git a/patches/wine11/0006-spatial-audio-tests.patch b/patches/wine11/0006-spatial-audio-tests.patch new file mode 100644 index 0000000..d414d32 --- /dev/null +++ b/patches/wine11/0006-spatial-audio-tests.patch @@ -0,0 +1,1265 @@ +From: jungwuk-ryu +Subject: [MGU] spatial audio tests +Origin: https://github.com/jungwuk-ryu/switchyard-wine +Source-revision: ba57a08921dfe8f3a4281692b040cd2fa5acd94e +License: LGPL-2.1-or-later + +Backported to CodeWeavers CrossOver 26.3.0 FOSS sources. +Port adaptations retain CrossOver HALOutput and PE-owned timer threads. +Apply the complete ordered patch set; shared Unix ABI and all audio tables +must be updated together. See docs/SPATIAL_AUDIO.md for provenance. + +diff --git a/dlls/mmdevapi/tests/render.c b/dlls/mmdevapi/tests/render.c +index 9ac82a6..7d1f396 100644 +--- a/dlls/mmdevapi/tests/render.c ++++ b/dlls/mmdevapi/tests/render.c +@@ -959,11 +959,13 @@ static void test_padding(void) + { + HRESULT hr; + IAudioClient *ac; ++ IAudioClient3 *ac3; + IAudioRenderClient *arc; + WAVEFORMATEX *pwfx; +- REFERENCE_TIME minp, defp; ++ REFERENCE_TIME minp, defp, engine_defp = 0; + BYTE *buf, silence; +- UINT32 psize, pad, written, i; ++ UINT32 psize, pad, written, i, default_frames, fundamental_frames, ++ min_frames, max_frames; + + hr = IMMDevice_Activate(dev, &IID_IAudioClient, CLSCTX_INPROC_SERVER, + NULL, (void**)&ac); +@@ -976,6 +978,17 @@ static void test_padding(void) + if(hr != S_OK) + return; + ++ hr = IAudioClient_QueryInterface(ac, &IID_IAudioClient3, (void **)&ac3); ++ if (hr == S_OK) ++ { ++ hr = IAudioClient3_GetSharedModeEnginePeriod(ac3, pwfx, ++ &default_frames, &fundamental_frames, &min_frames, &max_frames); ++ if (hr == S_OK) ++ engine_defp = ((UINT64)default_frames * 10000000 + ++ pwfx->nSamplesPerSec / 2) / pwfx->nSamplesPerSec; ++ IAudioClient3_Release(ac3); ++ } ++ + hr = IAudioClient_Initialize(ac, AUDCLNT_SHAREMODE_SHARED, + 0, 5000000, 0, pwfx, NULL); + ok(hr == S_OK, "Initialize failed: %08lx\n", hr); +@@ -994,9 +1007,17 @@ static void test_padding(void) + * 441 observed with Vista, 448 with w7 on the same HW! */ + hr = IAudioClient_GetDevicePeriod(ac, &defp, &minp); + ok(hr == S_OK, "GetDevicePeriod failed: %08lx\n", hr); +- /* some wineXYZ.drv use 20ms, not seen on native */ +- ok(defp == 100000 || broken(defp == 101587) || defp == 200000, +- "Expected 10ms default period: %lu\n", (ULONG)defp); ++ /* Modern backends expose the endpoint's actual shared engine quantum. ++ * Older Windows versions lack IAudioClient3 and historically report the ++ * fixed values below. */ ++ if (engine_defp) ++ ok(defp == engine_defp || defp + 1 == engine_defp || ++ defp == engine_defp + 1, ++ "Expected engine period %s, got %s\n", ++ wine_dbgstr_longlong(engine_defp), wine_dbgstr_longlong(defp)); ++ else ++ ok(defp == 100000 || broken(defp == 101587) || defp == 200000, ++ "Expected a legacy default period: %lu\n", (ULONG)defp); + ok(minp != 0, "Minimum period is 0\n"); + ok(minp <= defp, "Minimum period is greater than default period\n"); + +diff --git a/dlls/mmdevapi/tests/spatialaudio.c b/dlls/mmdevapi/tests/spatialaudio.c +index 2a7fd04..226084e 100644 +--- a/dlls/mmdevapi/tests/spatialaudio.c ++++ b/dlls/mmdevapi/tests/spatialaudio.c +@@ -37,6 +37,15 @@ static ISpatialAudioClient *sac = NULL; + static UINT32 max_dyn_count; + static HANDLE event; + static WAVEFORMATEX format; ++static BOOL spatial_stream_supported = TRUE; ++ ++#define ALL_STATIC_OBJECTS (AudioObjectType_FrontLeft | AudioObjectType_FrontRight | \ ++ AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft | \ ++ AudioObjectType_SideRight | AudioObjectType_BackLeft | AudioObjectType_BackRight | \ ++ AudioObjectType_TopFrontLeft | AudioObjectType_TopFrontRight | AudioObjectType_TopBackLeft | \ ++ AudioObjectType_TopBackRight | AudioObjectType_BottomFrontLeft | \ ++ AudioObjectType_BottomFrontRight | AudioObjectType_BottomBackLeft | \ ++ AudioObjectType_BottomBackRight | AudioObjectType_BackCenter) + + static void test_formats(void) + { +@@ -55,6 +64,11 @@ static void test_formats(void) + hr = IAudioFormatEnumerator_GetFormat(afe, 0, &fmt); + ok(hr == S_OK, "Getting format failed: 0x%08lx\n", hr); + ok(fmt != NULL, "Expected to get non-NULL format\n"); ++ if (!fmt) ++ { ++ IAudioFormatEnumerator_Release(afe); ++ return; ++ } + + ok(fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT, "Wrong format, expected WAVE_FORMAT_IEEE_FLOAT got %hx\n", fmt->wFormatTag); + ok(fmt->nChannels == 1, "Wrong number of channels, expected 1 got %hu\n", fmt->nChannels); +@@ -90,21 +104,65 @@ static void test_formats(void) + IAudioFormatEnumerator_Release(afe); + } + ++static void test_static_object_properties(void) ++{ ++ static const AudioObjectType types[] = ++ { ++ AudioObjectType_FrontLeft, ++ AudioObjectType_FrontRight, ++ AudioObjectType_FrontCenter, ++ AudioObjectType_LowFrequency, ++ AudioObjectType_SideLeft, ++ AudioObjectType_SideRight, ++ AudioObjectType_BackLeft, ++ AudioObjectType_BackRight, ++ AudioObjectType_TopFrontLeft, ++ AudioObjectType_TopFrontRight, ++ AudioObjectType_TopBackLeft, ++ AudioObjectType_TopBackRight, ++ AudioObjectType_BottomFrontLeft, ++ AudioObjectType_BottomFrontRight, ++ AudioObjectType_BottomBackLeft, ++ AudioObjectType_BottomBackRight, ++ AudioObjectType_BackCenter, ++ }; ++ AudioObjectType mask; ++ float x, y, z; ++ unsigned int i; ++ HRESULT hr; ++ ++ hr = ISpatialAudioClient_GetNativeStaticObjectTypeMask(sac, &mask); ++ ok(hr == S_OK, "Failed to get native static object mask: %#lx.\n", hr); ++ if (hr == S_OK) ++ { ++ ok(mask != AudioObjectType_None, "Expected at least one native static object.\n"); ++ ok(!(mask & AudioObjectType_Dynamic), "Got dynamic object in native mask %#x.\n", mask); ++ ok(!(mask & ~ALL_STATIC_OBJECTS), "Got unknown static objects in native mask %#x.\n", mask); ++ ok(mask == ALL_STATIC_OBJECTS, "Expected all static objects, got %#x.\n", mask); ++ } ++ ++ for (i = 0; i < ARRAY_SIZE(types); ++i) ++ { ++ x = y = z = NAN; ++ hr = ISpatialAudioClient_GetStaticObjectPosition(sac, types[i], &x, &y, &z); ++ ok(hr == S_OK, "Failed to get position for object %#x: %#lx.\n", types[i], hr); ++ if (hr == S_OK) ++ ok(isfinite(x) && isfinite(y) && isfinite(z), ++ "Got invalid position {%f, %f, %f} for object %#x.\n", x, y, z, types[i]); ++ } ++ ++ hr = ISpatialAudioClient_GetStaticObjectPosition(sac, AudioObjectType_None, &x, &y, &z); ++ ok(hr == E_INVALIDARG, "Got %#lx for a non-spatialized object.\n", hr); ++ hr = ISpatialAudioClient_GetStaticObjectPosition(sac, AudioObjectType_Dynamic, &x, &y, &z); ++ ok(hr == E_INVALIDARG, "Got %#lx for a dynamic object.\n", hr); ++ hr = ISpatialAudioClient_GetStaticObjectPosition(sac, ++ AudioObjectType_FrontLeft | AudioObjectType_FrontRight, &x, &y, &z); ++ ok(hr == E_INVALIDARG, "Got %#lx for a combined object mask.\n", hr); ++} ++ + static void fill_activation_params(SpatialAudioObjectRenderStreamActivationParams *activation_params) + { +- activation_params->StaticObjectTypeMask = \ +- AudioObjectType_FrontLeft | +- AudioObjectType_FrontRight | +- AudioObjectType_FrontCenter | +- AudioObjectType_LowFrequency | +- AudioObjectType_SideLeft | +- AudioObjectType_SideRight | +- AudioObjectType_BackLeft | +- AudioObjectType_BackRight | +- AudioObjectType_TopFrontLeft | +- AudioObjectType_TopFrontRight | +- AudioObjectType_TopBackLeft | +- AudioObjectType_TopBackRight; ++ activation_params->StaticObjectTypeMask = ALL_STATIC_OBJECTS; + + activation_params->MinDynamicObjectCount = 0; + activation_params->MaxDynamicObjectCount = 0; +@@ -119,6 +177,13 @@ typedef struct NotifyObject + { + ISpatialAudioObjectRenderStreamNotify ISpatialAudioObjectRenderStreamNotify_iface; + LONG ref; ++ LONG calls; ++ BOOL expect_notification; ++ BOOL reenter_stream; ++ BOOL release_stream; ++ HANDLE callback_event; ++ LONGLONG deadline; ++ UINT32 object_count; + } NotifyObject; + + static WINAPI HRESULT notifyobj_QueryInterface( +@@ -126,6 +191,14 @@ static WINAPI HRESULT notifyobj_QueryInterface( + REFIID riid, + void **ppvObject) + { ++ if (!ppvObject) ++ return E_POINTER; ++ *ppvObject = NULL; ++ if (!IsEqualIID(riid, &IID_IUnknown) && ++ !IsEqualIID(riid, &IID_ISpatialAudioObjectRenderStreamNotify)) ++ return E_NOINTERFACE; ++ *ppvObject = This; ++ ISpatialAudioObjectRenderStreamNotify_AddRef(This); + return S_OK; + } + +@@ -151,10 +224,74 @@ static WINAPI HRESULT notifyobj_OnAvailableDynamicObjectCountChange( + LONGLONG deadline, + UINT32 object_count) + { +- ok(FALSE, "Expected to never be notified of dynamic object count change\n"); ++ NotifyObject *obj = CONTAINING_RECORD(This, NotifyObject, ++ ISpatialAudioObjectRenderStreamNotify_iface); ++ ++ if (!obj->expect_notification) ++ ok(FALSE, "Expected to never be notified of dynamic object count change\n"); ++ obj->deadline = deadline; ++ obj->object_count = object_count; ++ InterlockedIncrement(&obj->calls); ++ if (obj->release_stream) ++ IUnknown_Release((IUnknown *)stream); ++ else if (obj->reenter_stream) ++ { ++ IUnknown_AddRef((IUnknown *)stream); ++ IUnknown_Release((IUnknown *)stream); ++ } ++ if (obj->callback_event) ++ SetEvent(obj->callback_event); + return S_OK; + } + ++static HRESULT activate_fault_stream(const char *fault_name, NotifyObject *notify, ++ ISpatialAudioObjectRenderStream **stream) ++{ ++ SpatialAudioObjectRenderStreamActivationParams params; ++ PROPVARIANT prop; ++ char *old_fault = NULL; ++ DWORD old_fault_len; ++ BOOL had_old_fault; ++ HRESULT hr; ++ ++ *stream = NULL; ++ SetLastError(ERROR_SUCCESS); ++ old_fault_len = GetEnvironmentVariableA(fault_name, NULL, 0); ++ had_old_fault = old_fault_len || GetLastError() != ERROR_ENVVAR_NOT_FOUND; ++ if (old_fault_len) ++ { ++ old_fault = malloc(old_fault_len); ++ if (!old_fault) ++ return E_OUTOFMEMORY; ++ GetEnvironmentVariableA(fault_name, old_fault, old_fault_len); ++ } ++ if (!SetEnvironmentVariableA(fault_name, "1")) ++ { ++ hr = HRESULT_FROM_WIN32(GetLastError()); ++ free(old_fault); ++ return hr; ++ } ++ ++ fill_activation_params(¶ms); ++ params.StaticObjectTypeMask = AudioObjectType_None; ++ params.MinDynamicObjectCount = 1; ++ params.MaxDynamicObjectCount = 1; ++ params.NotifyObject = ¬ify->ISpatialAudioObjectRenderStreamNotify_iface; ++ PropVariantInit(&prop); ++ prop.vt = VT_BLOB; ++ prop.blob.cbSize = sizeof(params); ++ prop.blob.pBlobData = (BYTE *)¶ms; ++ ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)stream); ++ if (had_old_fault) ++ SetEnvironmentVariableA(fault_name, old_fault ? old_fault : ""); ++ else ++ SetEnvironmentVariableA(fault_name, NULL); ++ free(old_fault); ++ return hr; ++} ++ + static const ISpatialAudioObjectRenderStreamNotifyVtbl notifyobjvtbl = + { + notifyobj_QueryInterface, +@@ -168,6 +305,7 @@ static void test_stream_activation(void) + HRESULT hr; + WAVEFORMATEX wrong_format; + ISpatialAudioObjectRenderStream *sas = NULL; ++ ISpatialAudioObject *object; + + SpatialAudioObjectRenderStreamActivationParams activation_params; + PROPVARIANT activation_params_prop; +@@ -178,11 +316,65 @@ static void test_stream_activation(void) + activation_params_prop.blob.cbSize = sizeof(activation_params); + activation_params_prop.blob.pBlobData = (BYTE*) &activation_params; + ++ fill_activation_params(&activation_params); ++ activation_params_prop.vt = VT_EMPTY; ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == E_INVALIDARG, "Expected a non-blob activation value to fail: %#lx.\n", hr); ++ ok(!sas, "Expected no stream for a malformed activation value.\n"); ++ ++ activation_params_prop.vt = VT_BLOB; ++ activation_params_prop.blob.cbSize = sizeof(activation_params) - 1; ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == E_INVALIDARG, "Expected a truncated activation blob to fail: %#lx.\n", hr); ++ ok(!sas, "Expected no stream for a truncated activation blob.\n"); ++ ++ activation_params_prop.blob.cbSize = sizeof(activation_params); ++ activation_params_prop.blob.pBlobData = NULL; ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == E_INVALIDARG, "Expected a null activation blob to fail: %#lx.\n", hr); ++ ok(!sas, "Expected no stream for a null activation blob.\n"); ++ activation_params_prop.blob.pBlobData = (BYTE *)&activation_params; ++ + /* correct params */ + fill_activation_params(&activation_params); + hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, &IID_ISpatialAudioObjectRenderStream, (void**)&sas); +- ok(hr == S_OK, "Failed to activate spatial audio stream: 0x%08lx\n", hr); +- ok(ISpatialAudioObjectRenderStream_Release(sas) == 0, "Expected to release the last reference\n"); ++ if (hr == AUDCLNT_E_UNSUPPORTED_FORMAT) ++ { ++ win_skip("The audio backend does not support spatial render streams.\n"); ++ spatial_stream_supported = FALSE; ++ } ++ else ++ { ++ ok(hr == S_OK, "Failed to activate spatial audio stream: 0x%08lx\n", hr); ++ spatial_stream_supported = hr == S_OK; ++ if (hr == S_OK) ++ ok(ISpatialAudioObjectRenderStream_Release(sas) == 0, ++ "Expected to release the last reference\n"); ++ } ++ sas = NULL; ++ ++ /* AudioObjectType_None is independent of the static spatial channel mask. */ ++ if (spatial_stream_supported) ++ { ++ fill_activation_params(&activation_params); ++ activation_params.StaticObjectTypeMask = AudioObjectType_None; ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == S_OK, "Failed to activate a non-spatial-only stream: %#lx.\n", hr); ++ if (hr == S_OK) ++ { ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_None, &object); ++ ok(hr == S_OK, "Failed to activate a non-spatialized object: %#lx.\n", hr); ++ if (hr == S_OK) ++ ISpatialAudioObject_Release(object); ++ ISpatialAudioObjectRenderStream_Release(sas); ++ } ++ sas = NULL; ++ } + + /* event handle */ + fill_activation_params(&activation_params); +@@ -206,46 +398,298 @@ static void test_stream_activation(void) + ok(hr == AUDCLNT_E_UNSUPPORTED_FORMAT, "Expected format to be unsupported: 0x%08lx\n", hr); + ok(sas == NULL, "Expected spatial audio stream to be set to NULL upon failed activation\n"); + +- /* dynamic objects are not supported */ +- if (max_dyn_count == 0) +- { +- fill_activation_params(&activation_params); +- activation_params.StaticObjectTypeMask |= AudioObjectType_Dynamic; +- hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, &IID_ISpatialAudioObjectRenderStream, (void**)&sas); +- ok(hr == E_INVALIDARG, "Expected dynamic objects type be invalid: 0x%08lx\n", hr); +- ok(sas == NULL, "Expected spatial audio stream to be set to NULL upon failed activation\n"); +- } ++ /* Dynamic is an activatable object type, not a static-bed mask bit. */ ++ fill_activation_params(&activation_params); ++ activation_params.StaticObjectTypeMask |= AudioObjectType_Dynamic; ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == E_INVALIDARG, "Expected dynamic static-mask bit to be invalid: 0x%08lx\n", hr); ++ ok(sas == NULL, "Expected spatial audio stream to be set to NULL upon failed activation\n"); + ++ fill_activation_params(&activation_params); + activation_params.MinDynamicObjectCount = max_dyn_count + 1; + activation_params.MaxDynamicObjectCount = max_dyn_count + 1; +- hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, &IID_ISpatialAudioObjectRenderStream, (void**)&sas); +- if (max_dyn_count) +- ok(hr == AUDCLNT_E_UNSUPPORTED_FORMAT, "Expected dynamic object count exceeding max to be unsupported: 0x%08lx\n", hr); +- else +- ok(hr == E_INVALIDARG, "Expected setting dynamic object count to be invalid: 0x%08lx\n", hr); ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == SPTLAUDCLNT_E_NO_MORE_OBJECTS, ++ "Expected an unsatisfied dynamic minimum to fail: 0x%08lx\n", hr); ++ ++ fill_activation_params(&activation_params); ++ activation_params.MinDynamicObjectCount = 1; ++ activation_params.MaxDynamicObjectCount = 0; ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == E_INVALIDARG, "Expected reversed dynamic range to be invalid: 0x%08lx\n", hr); ++ ++ if (spatial_stream_supported) ++ { ++ fill_activation_params(&activation_params); ++ activation_params.MaxDynamicObjectCount = max_dyn_count + 1; ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == S_OK, "Expected dynamic maximum to be capped: 0x%08lx\n", hr); ++ if (hr == S_OK) ++ ISpatialAudioObjectRenderStream_Release(sas); ++ sas = NULL; ++ } + + /* ISpatialAudioObjectRenderStreamNotify */ + fill_activation_params(&activation_params); ++ memset(¬ify_object, 0, sizeof(notify_object)); + notify_object.ISpatialAudioObjectRenderStreamNotify_iface.lpVtbl = ¬ifyobjvtbl; +- notify_object.ref = 0; ++ activation_params.MaxDynamicObjectCount = max_dyn_count ? 1 : 0; + activation_params.NotifyObject = ¬ify_object.ISpatialAudioObjectRenderStreamNotify_iface; +- hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, &IID_ISpatialAudioObjectRenderStream, (void**)&sas); +- ok(hr == S_OK, "Failed to activate spatial audio stream: 0x%08lx\n", hr); +- ok(notify_object.ref == 1, "Expected to get increased NotifyObject's ref count\n"); +- ok(ISpatialAudioObjectRenderStream_Release(sas) == 0, "Expected to release the last reference\n"); +- ok(notify_object.ref == 0, "Expected to get lowered NotifyObject's ref count\n"); ++ if (spatial_stream_supported) ++ { ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == S_OK, "Failed to activate spatial audio stream: 0x%08lx\n", hr); ++ if (hr == S_OK) ++ { ++ ok(notify_object.ref == 1, "Expected to get increased NotifyObject's ref count\n"); ++ ok(ISpatialAudioObjectRenderStream_Release(sas) == 0, ++ "Expected to release the last reference\n"); ++ ok(notify_object.ref == 0, "Expected to get lowered NotifyObject's ref count\n"); ++ } ++ } ++} ++ ++static void test_proactive_invalidation(void) ++{ ++ static const char fault_name[] = ++ "SWITCHYARD_SPATIAL_AUDIO_FAULT_INVALIDATE_ON_START"; ++ ISpatialAudioObjectRenderStream *stream = NULL; ++ ISpatialAudioObject *object = NULL; ++ NotifyObject notify; ++ BYTE *buffer = NULL; ++ UINT32 available = ~0u; ++ UINT32 bytes = ~0u; ++ BOOL active = TRUE; ++ DWORD wait; ++ HRESULT hr; ++ ++ if (!spatial_stream_supported || !max_dyn_count) ++ { ++ win_skip("Dynamic endpoint-loss notification is unavailable.\n"); ++ return; ++ } ++ ++ memset(¬ify, 0, sizeof(notify)); ++ notify.ISpatialAudioObjectRenderStreamNotify_iface.lpVtbl = ¬ifyobjvtbl; ++ notify.expect_notification = TRUE; ++ notify.reenter_stream = TRUE; ++ notify.callback_event = CreateEventW(NULL, FALSE, FALSE, NULL); ++ ok(!!notify.callback_event, "Failed to create the notification event: %lu.\n", ++ GetLastError()); ++ if (!notify.callback_event) ++ return; ++ ++ hr = activate_fault_stream(fault_name, ¬ify, &stream); ++ ok(hr == S_OK, "Failed to activate the fault-injection stream: %#lx.\n", hr); ++ if (hr != S_OK || !stream) ++ goto done; ++ ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(stream, ++ AudioObjectType_Dynamic, &object); ++ ok(hr == S_OK && object, "Failed to activate the endpoint-loss object: %#lx/%p.\n", ++ hr, object); ++ if (hr != S_OK || !object) ++ goto done; ++ ++ hr = ISpatialAudioObjectRenderStream_Start(stream); ++ ok(hr == S_OK || hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED || ++ hr == AUDCLNT_E_DEVICE_INVALIDATED || ++ hr == AUDCLNT_E_RESOURCES_INVALIDATED, ++ "Unexpected fault-injection Start result: %#lx.\n", hr); ++ wait = WaitForSingleObject(notify.callback_event, 5000); ++ ok(wait == WAIT_OBJECT_0, "Timed out waiting for proactive notification: %#lx.\n", ++ wait); ++ if (wait == WAIT_OBJECT_0) ++ { ++ ok(notify.calls == 1, "Expected one notification, got %ld.\n", notify.calls); ++ ok(!notify.deadline, "Expected a zero deadline, got %s.\n", ++ wine_dbgstr_longlong(notify.deadline)); ++ ok(!notify.object_count, "Expected zero available objects, got %u.\n", ++ notify.object_count); ++ hr = ISpatialAudioObject_IsActive(object, &active); ++ ok(hr == S_OK && !active, ++ "Expected the endpoint-loss object to be inactive, got %#lx/%d.\n", ++ hr, active); ++ hr = ISpatialAudioObject_SetPosition(object, 1.0f, 0.0f, -1.0f); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, ++ "Expected invalidated position state, got %#lx.\n", hr); ++ hr = ISpatialAudioObject_GetBuffer(object, &buffer, &bytes); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, ++ "Expected invalidated object buffer, got %#lx.\n", hr); ++ hr = ISpatialAudioObjectRenderStream_GetAvailableDynamicObjectCount(stream, ++ &available); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED && !available, ++ "Expected invalidated resources and zero objects, got %#lx/%u.\n", ++ hr, available); ++ wait = WaitForSingleObject(notify.callback_event, 100); ++ ok(wait == WAIT_TIMEOUT, "Expected a one-shot notification, got %#lx.\n", wait); ++ } ++ ++ ISpatialAudioObject_Release(object); ++ object = NULL; ++ ISpatialAudioObjectRenderStream_Release(stream); ++ stream = NULL; ++ for (wait = 0; wait < 100 && ++ InterlockedCompareExchange(¬ify.ref, 0, 0); ++wait) ++ Sleep(1); ++ ok(!InterlockedCompareExchange(¬ify.ref, 0, 0), ++ "Notification reference was not released, got %ld.\n", ++ InterlockedCompareExchange(¬ify.ref, 0, 0)); ++ ++done: ++ if (object) ++ ISpatialAudioObject_Release(object); ++ if (stream) ++ ISpatialAudioObjectRenderStream_Release(stream); ++ CloseHandle(notify.callback_event); ++} ++ ++static void test_proactive_reentrant_release(void) ++{ ++ static const char fault_name[] = ++ "SWITCHYARD_SPATIAL_AUDIO_FAULT_INVALIDATE_ON_START"; ++ ISpatialAudioObjectRenderStream *stream = NULL; ++ NotifyObject notify; ++ DWORD wait; ++ HRESULT hr; ++ ++ if (!spatial_stream_supported || !max_dyn_count) ++ { ++ win_skip("Dynamic endpoint-loss notification is unavailable.\n"); ++ return; ++ } ++ ++ memset(¬ify, 0, sizeof(notify)); ++ notify.ISpatialAudioObjectRenderStreamNotify_iface.lpVtbl = ¬ifyobjvtbl; ++ notify.expect_notification = TRUE; ++ notify.release_stream = TRUE; ++ notify.callback_event = CreateEventW(NULL, FALSE, FALSE, NULL); ++ ok(!!notify.callback_event, "Failed to create the notification event: %lu.\n", ++ GetLastError()); ++ if (!notify.callback_event) ++ return; ++ ++ hr = activate_fault_stream(fault_name, ¬ify, &stream); ++ ok(hr == S_OK, "Failed to activate the reentrant-release stream: %#lx.\n", hr); ++ if (hr != S_OK || !stream) ++ goto done; ++ ++ hr = ISpatialAudioObjectRenderStream_Start(stream); ++ ok(hr == S_OK || hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED || ++ hr == AUDCLNT_E_DEVICE_INVALIDATED || ++ hr == AUDCLNT_E_RESOURCES_INVALIDATED, ++ "Unexpected reentrant-release Start result: %#lx.\n", hr); ++ wait = WaitForSingleObject(notify.callback_event, 5000); ++ ok(wait == WAIT_OBJECT_0, ++ "Timed out waiting for the reentrant-release notification: %#lx.\n", ++ wait); ++ if (wait == WAIT_OBJECT_0) ++ { ++ stream = NULL; /* The callback released the application's reference. */ ++ ok(notify.calls == 1, "Expected one notification, got %ld.\n", notify.calls); ++ } ++ ++done: ++ if (stream) ++ ISpatialAudioObjectRenderStream_Release(stream); ++ for (wait = 0; wait < 100 && ++ InterlockedCompareExchange(¬ify.ref, 0, 0); ++wait) ++ Sleep(1); ++ ok(!InterlockedCompareExchange(¬ify.ref, 0, 0), ++ "Notification reference was not released, got %ld.\n", ++ InterlockedCompareExchange(¬ify.ref, 0, 0)); ++ CloseHandle(notify.callback_event); ++} ++ ++static void test_prestart_invalidation(void) ++{ ++ static const char fault_name[] = ++ "SWITCHYARD_SPATIAL_AUDIO_FAULT_INVALIDATE_BEFORE_START"; ++ ISpatialAudioObjectRenderStream *stream = NULL; ++ ISpatialAudioObject *object = NULL; ++ NotifyObject notify; ++ UINT32 available = ~0u; ++ DWORD wait; ++ HRESULT hr; ++ ++ if (!spatial_stream_supported || !max_dyn_count) ++ { ++ win_skip("Dynamic endpoint-loss notification is unavailable.\n"); ++ return; ++ } ++ ++ memset(¬ify, 0, sizeof(notify)); ++ notify.ISpatialAudioObjectRenderStreamNotify_iface.lpVtbl = ¬ifyobjvtbl; ++ notify.expect_notification = TRUE; ++ notify.callback_event = CreateEventW(NULL, FALSE, FALSE, NULL); ++ ok(!!notify.callback_event, "Failed to create the notification event: %lu.\n", ++ GetLastError()); ++ if (!notify.callback_event) ++ return; ++ ++ hr = activate_fault_stream(fault_name, ¬ify, &stream); ++ ok(hr == S_OK, "Failed to activate the pre-start fault stream: %#lx.\n", hr); ++ if (hr != S_OK || !stream) ++ goto done; ++ ++ hr = ISpatialAudioObjectRenderStream_GetAvailableDynamicObjectCount(stream, ++ &available); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED && !available, ++ "Expected pre-start invalidation and zero objects, got %#lx/%u.\n", ++ hr, available); ++ ok(!notify.calls, "Notification escaped before Start, got %ld calls.\n", ++ notify.calls); ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(stream, ++ AudioObjectType_Dynamic, &object); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED && !object, ++ "Expected object activation to observe endpoint loss, got %#lx/%p.\n", ++ hr, object); ++ ++ hr = ISpatialAudioObjectRenderStream_Start(stream); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, ++ "Expected Start to report endpoint loss, got %#lx.\n", hr); ++ wait = WaitForSingleObject(notify.callback_event, 5000); ++ ok(wait == WAIT_OBJECT_0, ++ "Timed out waiting for the armed pre-start notification: %#lx.\n", ++ wait); ++ ok(notify.calls == 1, "Expected one notification, got %ld.\n", notify.calls); ++ ++done: ++ if (object) ++ ISpatialAudioObject_Release(object); ++ if (stream) ++ ISpatialAudioObjectRenderStream_Release(stream); ++ for (wait = 0; wait < 100 && ++ InterlockedCompareExchange(¬ify.ref, 0, 0); ++wait) ++ Sleep(1); ++ ok(!InterlockedCompareExchange(¬ify.ref, 0, 0), ++ "Notification reference was not released, got %ld.\n", ++ InterlockedCompareExchange(¬ify.ref, 0, 0)); ++ CloseHandle(notify.callback_event); + } + + static void test_audio_object_activation(void) + { ++ AudioObjectType type; + HRESULT hr; + BOOL is_active; + ISpatialAudioObjectRenderStream *sas = NULL; +- ISpatialAudioObject *sao1, *sao2; ++ ISpatialAudioObject *sao1, *sao2, *sao3; + + SpatialAudioObjectRenderStreamActivationParams activation_params; + PROPVARIANT activation_params_prop; + ++ if (!spatial_stream_supported) ++ { ++ win_skip("The audio backend does not support spatial audio objects.\n"); ++ return; ++ } ++ + PropVariantInit(&activation_params_prop); + activation_params_prop.vt = VT_BLOB; + activation_params_prop.blob.cbSize = sizeof(activation_params); +@@ -255,11 +699,18 @@ static void test_audio_object_activation(void) + activation_params.StaticObjectTypeMask &= ~AudioObjectType_FrontRight; + hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, &IID_ISpatialAudioObjectRenderStream, (void**)&sas); + ok(hr == S_OK, "Failed to activate spatial audio stream: 0x%08lx\n", hr); ++ if (hr != S_OK) ++ return; + + hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, AudioObjectType_FrontLeft, &sao1); + ok(hr == S_OK, "Failed to activate spatial audio object: 0x%08lx\n", hr); ++ if (hr != S_OK) ++ { ++ ISpatialAudioObjectRenderStream_Release(sas); ++ return; ++ } + hr = ISpatialAudioObject_IsActive(sao1, &is_active); +- todo_wine ok(hr == S_OK, "Failed to check if spatial audio object is active: 0x%08lx\n", hr); ++ ok(hr == S_OK, "Failed to check if spatial audio object is active: 0x%08lx\n", hr); + if (hr == S_OK) + ok(is_active, "Expected spatial audio object to be active\n"); + +@@ -269,9 +720,53 @@ static void test_audio_object_activation(void) + hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, AudioObjectType_FrontRight, &sao2); + ok(hr == SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE, "Expected static object to be not available: 0x%08lx\n", hr); + ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_FrontLeft | AudioObjectType_SideLeft, &sao2); ++ ok(hr == SPTLAUDCLNT_E_OBJECT_ALREADY_ACTIVE, ++ "Expected a combined static object overlapping an active channel to fail: 0x%08lx\n", hr); ++ ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_SideLeft | AudioObjectType_SideRight, &sao2); ++ ok(hr == S_OK, "Failed to activate a combined static object: 0x%08lx\n", hr); ++ if (hr == S_OK) ++ { ++ hr = ISpatialAudioObject_GetAudioObjectType(sao2, &type); ++ ok(hr == S_OK, "Failed to query combined static object type: %#lx.\n", hr); ++ ok(type == (AudioObjectType_SideLeft | AudioObjectType_SideRight), ++ "Got unexpected combined object type %#x.\n", type); ++ ISpatialAudioObject_Release(sao2); ++ } ++ + hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, AudioObjectType_Dynamic, &sao2); + ok(hr == SPTLAUDCLNT_E_NO_MORE_OBJECTS, "Expected to not have no more dynamic objects: 0x%08lx\n", hr); + ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_None, &sao2); ++ ok(hr == S_OK, "Failed to activate a non-spatialized audio object: %#lx.\n", hr); ++ if (hr == S_OK) ++ { ++ hr = ISpatialAudioObject_GetAudioObjectType(sao2, &type); ++ ok(hr == S_OK, "Failed to query non-spatialized object type: %#lx.\n", hr); ++ ok(type == AudioObjectType_None, "Got unexpected object type %#x.\n", type); ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_None, &sao3); ++ ok(hr == SPTLAUDCLNT_E_OBJECT_ALREADY_ACTIVE, ++ "Expected the non-spatialized slot to be bounded: %#lx.\n", hr); ++ ISpatialAudioObject_Release(sao2); ++ } ++ ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_BottomBackRight, &sao2); ++ ok(hr == S_OK, "Failed to activate a bottom spatial audio object: %#lx.\n", hr); ++ if (hr == S_OK) ++ { ++ hr = ISpatialAudioObject_GetAudioObjectType(sao2, &type); ++ ok(hr == S_OK, "Failed to query bottom spatial audio object type: %#lx.\n", hr); ++ ok(type == AudioObjectType_BottomBackRight, ++ "Got unexpected object type %#x.\n", type); ++ ISpatialAudioObject_Release(sao2); ++ } ++ + ISpatialAudioObject_Release(sao1); + ISpatialAudioObjectRenderStream_Release(sas); + } +@@ -296,10 +791,17 @@ static void test_audio_object_buffers(void) + ISpatialAudioObjectRenderStream *sas = NULL; + PROPVARIANT activation_params_prop; + ISpatialAudioObject *sao[4]; ++ BOOL is_active; + BYTE *buffer; + INT i, j, k; + HRESULT hr; + ++ if (!spatial_stream_supported) ++ { ++ win_skip("The audio backend does not support spatial object buffers.\n"); ++ return; ++ } ++ + PropVariantInit(&activation_params_prop); + activation_params_prop.vt = VT_BLOB; + activation_params_prop.blob.cbSize = sizeof(activation_params); +@@ -308,23 +810,29 @@ static void test_audio_object_buffers(void) + fill_activation_params(&activation_params); + hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, &IID_ISpatialAudioObjectRenderStream, (void**)&sas); + ok(hr == S_OK, "Failed to activate spatial audio stream: 0x%08lx\n", hr); ++ if (hr != S_OK) ++ return; ++ ++ hr = ISpatialAudioObjectRenderStream_Reset(sas); ++ ok(hr == S_OK, "got %#lx.\n", hr); + + hr = ISpatialAudioClient_GetMaxFrameCount(sac, &format, &max_frame_count); + ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr); +- frame_count = format.nSamplesPerSec / 100; /* 10ms */ +- /* Most of the time the frame count matches the 10ms interval exactly. +- * However (seen on some Testbot machines) it might be a bit higher for some reason. */ +- ok(max_frame_count <= frame_count + frame_count / 4, "Got unexpected frame count %u.\n", frame_count); +- +- /* The tests below which check frame count from _BeginUpdatingAudioObjects fail on some Testbot machines +- * with max_frame_count from _GetMaxFrameCount(). */ +- max_frame_count = frame_count + frame_count / 4; ++ ok(max_frame_count != 0, "Expected a nonzero endpoint processing quantum.\n"); + + hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, AudioObjectType_FrontLeft, &sao[0]); + ok(hr == S_OK, "Failed to activate spatial audio object: 0x%08lx\n", hr); + ++ hr = ISpatialAudioObject_SetVolume(sao[0], 0.5f); ++ ok(hr == SPTLAUDCLNT_E_OUT_OF_ORDER, "Got %#lx outside an update pass.\n", hr); ++ hr = ISpatialAudioObject_SetPosition(sao[0], 0.0f, 0.0f, 0.0f); ++ ok(hr == SPTLAUDCLNT_E_OUT_OF_ORDER, "Got %#lx outside an update pass.\n", hr); ++ + hr = ISpatialAudioObjectRenderStream_Start(sas); + ok(hr == S_OK, "Failed to activate spatial audio render stream: 0x%08lx\n", hr); ++ hr = ISpatialAudioObjectRenderStream_Start(sas); ++ ok(hr == SPTLAUDCLNT_E_STREAM_NOT_STOPPED, ++ "Expected a second Start to report a running stream, got %#lx.\n", hr); + + hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, AudioObjectType_FrontRight, &sao[1]); + ok(hr == S_OK, "Failed to activate spatial audio object: 0x%08lx\n", hr); +@@ -353,6 +861,16 @@ static void test_audio_object_buffers(void) + ok(is_buffer_zeroed(buffer, buffer_length), "Expected audio object's buffer to be zeroed\n"); + } + ++ hr = ISpatialAudioObject_SetVolume(sao[0], 0.5f); ++ ok(hr == S_OK, "Failed to set spatial audio object volume: %#lx.\n", hr); ++ hr = ISpatialAudioObject_SetVolume(sao[0], -0.1f); ++ ok(hr == E_INVALIDARG, "Got %#lx for an invalid volume.\n", hr); ++ hr = ISpatialAudioObject_SetVolume(sao[0], 1.1f); ++ ok(hr == E_INVALIDARG, "Got %#lx for an invalid volume.\n", hr); ++ hr = ISpatialAudioObject_SetPosition(sao[0], 0.0f, 0.0f, 0.0f); ++ ok(hr == SPTLAUDCLNT_E_PROPERTY_NOT_SUPPORTED, ++ "Got %#lx when positioning a static object.\n", hr); ++ + hr = ISpatialAudioObjectRenderStream_EndUpdatingAudioObjects(sas); + ok(hr == S_OK, "Failed to end updating audio objects: 0x%08lx\n", hr); + +@@ -428,13 +946,13 @@ static void test_audio_object_buffers(void) + + /* ending the stream */ + hr = ISpatialAudioObject_SetEndOfStream(sao[0], 0); +- todo_wine ok(hr == SPTLAUDCLNT_E_OUT_OF_ORDER, "Expected that ending the stream at this point won't be allowed: 0x%08lx\n", hr); ++ ok(hr == SPTLAUDCLNT_E_OUT_OF_ORDER, "Expected that ending the stream at this point won't be allowed: 0x%08lx\n", hr); + + hr = WaitForSingleObject(event, 200); + ok(hr == WAIT_OBJECT_0, "Expected event to be flagged: 0x%08lx\n", hr); + + hr = ISpatialAudioObject_SetEndOfStream(sao[0], 0); +- todo_wine ok(hr == SPTLAUDCLNT_E_OUT_OF_ORDER, "Expected that ending the stream at this point won't be allowed: 0x%08lx\n", hr); ++ ok(hr == SPTLAUDCLNT_E_OUT_OF_ORDER, "Expected that ending the stream at this point won't be allowed: 0x%08lx\n", hr); + + hr = ISpatialAudioObjectRenderStream_BeginUpdatingAudioObjects(sas, &dyn_object_count, &frame_count); + ok(hr == S_OK, "Failed to begin updating audio objects: 0x%08lx\n", hr); +@@ -442,7 +960,7 @@ static void test_audio_object_buffers(void) + + /* expect the object that was not updated last cycle to be invalidated */ + hr = ISpatialAudioObject_GetBuffer(sao[ARRAYSIZE(sao) - 1], &buffer, &buffer_length); +- todo_wine ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, "Expected audio object to be invalidated: 0x%08lx\n", hr); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, "Expected audio object to be invalidated: 0x%08lx\n", hr); + + for (i = 0; i < ARRAYSIZE(sao) - 1; i++) + { +@@ -450,15 +968,57 @@ static void test_audio_object_buffers(void) + ok(hr == S_OK, "Expected to be able to get buffers for audio object: 0x%08lx\n", hr); + + hr = ISpatialAudioObject_SetEndOfStream(sao[i], 0); +- todo_wine ok(hr == S_OK, "Failed to end the stream: 0x%08lx\n", hr); ++ ok(hr == S_OK, "Failed to end the stream: 0x%08lx\n", hr); + + hr = ISpatialAudioObject_GetBuffer(sao[i], &buffer, &buffer_length); +- todo_wine ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, "Expected audio object to be invalidated: 0x%08lx\n", hr); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, "Expected audio object to be invalidated: 0x%08lx\n", hr); ++ ++ hr = ISpatialAudioObject_IsActive(sao[i], &is_active); ++ ok(hr == S_OK, "Failed to query object activity: %#lx.\n", hr); ++ ok(!is_active, "Expected an ended object to be inactive.\n"); + } + ++ /* Applications may release an object immediately after submitting its ++ * final buffer. The renderer must retain that buffer through this pass. */ ++ ISpatialAudioObject_Release(sao[0]); ++ sao[0] = NULL; ++ + hr = ISpatialAudioObjectRenderStream_EndUpdatingAudioObjects(sas); + ok(hr == S_OK, "Failed to end updating audio objects: 0x%08lx\n", hr); + ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_FrontLeft, &sao[0]); ++ ok(hr == S_OK, "Failed to reactivate released spatial audio object: 0x%08lx\n", hr); ++ ++ hr = ISpatialAudioObjectRenderStream_Reset(sas); ++ ok(hr == SPTLAUDCLNT_E_STREAM_NOT_STOPPED, "got %#lx.\n", hr); ++ ++ hr = ISpatialAudioObjectRenderStream_Stop(sas); ++ ok(hr == S_OK, "got %#lx.\n", hr); ++ ++ hr = ISpatialAudioObjectRenderStream_Reset(sas); ++ ok(hr == S_OK, "got %#lx.\n", hr); ++ ++ hr = ISpatialAudioObject_IsActive(sao[0], &is_active); ++ ok(hr == S_OK, "Failed to query reset object activity: %#lx.\n", hr); ++ ok(!is_active, "Expected reset to revoke the active spatial audio object.\n"); ++ ++ hr = ISpatialAudioObjectRenderStream_BeginUpdatingAudioObjects(sas, &dyn_object_count, &frame_count); ++ ok(hr == S_OK, "got %#lx.\n", hr); ++ ++ hr = ISpatialAudioObject_GetBuffer(sao[0], &buffer, &buffer_length); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, ++ "Expected the reset object to remain invalidated, got %#lx.\n", hr); ++ ++ hr = ISpatialAudioObjectRenderStream_Reset(sas); ++ todo_wine ok(hr == S_OK, "got %#lx.\n", hr); ++ ++ hr = ISpatialAudioObjectRenderStream_EndUpdatingAudioObjects(sas); ++ ok(hr == S_OK, "got %#lx.\n", hr); ++ ++ hr = ISpatialAudioObjectRenderStream_Reset(sas); ++ ok(hr == S_OK, "got %#lx.\n", hr); ++ + for (i = 0; i < ARRAYSIZE(sao); i++) + { + ISpatialAudioObject_Release(sao[i]); +@@ -467,6 +1027,335 @@ static void test_audio_object_buffers(void) + ISpatialAudioObjectRenderStream_Release(sas); + } + ++struct object_release_thread_context ++{ ++ ISpatialAudioObject *object; ++ HANDLE ready_event; ++ HANDLE release_event; ++ ULONG release_ref; ++}; ++ ++static DWORD WINAPI object_release_thread(void *arg) ++{ ++ struct object_release_thread_context *context = arg; ++ HRESULT hr; ++ ++ hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); ++ if (FAILED(hr)) ++ return 3; ++ if (!SetEvent(context->ready_event)) ++ { ++ CoUninitialize(); ++ return 1; ++ } ++ if (WaitForSingleObject(context->release_event, 5000) != WAIT_OBJECT_0) ++ { ++ CoUninitialize(); ++ return 2; ++ } ++ ++ context->release_ref = ISpatialAudioObject_Release(context->object); ++ CoUninitialize(); ++ return 0; ++} ++ ++static void test_dynamic_audio_objects(void) ++{ ++ SpatialAudioObjectRenderStreamActivationParams activation_params; ++ ISpatialAudioObjectRenderStream *sas = NULL; ++ ISpatialAudioObject **objects, *replacement = NULL, *excess = NULL; ++ PROPVARIANT activation_params_prop; ++ UINT32 available, frames, bytes, limit, i, j, iteration; ++ BOOL active; ++ BYTE *buffer; ++ HRESULT hr; ++ ++ if (!spatial_stream_supported || !max_dyn_count) ++ { ++ win_skip("The endpoint does not expose dynamic spatial objects.\n"); ++ return; ++ } ++ ++ limit = max_dyn_count; ++ objects = calloc(limit, sizeof(*objects)); ++ if (!objects) ++ { ++ skip("Not enough memory for %u dynamic object references.\n", limit); ++ return; ++ } ++ PropVariantInit(&activation_params_prop); ++ activation_params_prop.vt = VT_BLOB; ++ activation_params_prop.blob.cbSize = sizeof(activation_params); ++ activation_params_prop.blob.pBlobData = (BYTE *)&activation_params; ++ ++ fill_activation_params(&activation_params); ++ activation_params.StaticObjectTypeMask = AudioObjectType_None; ++ activation_params.MinDynamicObjectCount = 1; ++ activation_params.MaxDynamicObjectCount = limit; ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation_params_prop, ++ &IID_ISpatialAudioObjectRenderStream, (void **)&sas); ++ ok(hr == S_OK, "Failed to activate a dynamic spatial stream: %#lx.\n", hr); ++ if (hr != S_OK) ++ { ++ free(objects); ++ return; ++ } ++ ++ hr = ISpatialAudioObjectRenderStream_GetAvailableDynamicObjectCount(sas, &available); ++ ok(hr == S_OK, "Failed to query dynamic capacity: %#lx.\n", hr); ++ ok(available == limit, "Expected %u available objects, got %u.\n", limit, available); ++ ++ for (i = 0; i < limit; ++i) ++ { ++ AudioObjectType type = AudioObjectType_None; ++ ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_Dynamic, &objects[i]); ++ ok(hr == S_OK, "Failed to activate dynamic object %u: %#lx.\n", i, hr); ++ if (hr != S_OK) ++ goto cleanup; ++ hr = ISpatialAudioObject_GetAudioObjectType(objects[i], &type); ++ ok(hr == S_OK && type == AudioObjectType_Dynamic, ++ "Got type %#x and status %#lx for object %u.\n", type, hr, i); ++ } ++ ++ hr = ISpatialAudioObjectRenderStream_GetAvailableDynamicObjectCount(sas, &available); ++ ok(hr == S_OK && !available, "Expected exhausted capacity, got %u and %#lx.\n", ++ available, hr); ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_Dynamic, &excess); ++ ok(hr == SPTLAUDCLNT_E_NO_MORE_OBJECTS, ++ "Expected dynamic-object exhaustion, got %#lx.\n", hr); ++ ok(!excess, "Expected a null object on exhaustion.\n"); ++ ++ hr = ISpatialAudioObject_SetPosition(objects[0], 1.0f, 2.0f, 3.0f); ++ ok(hr == SPTLAUDCLNT_E_OUT_OF_ORDER, "Got %#lx outside an update pass.\n", hr); ++ hr = ISpatialAudioObject_SetVolume(objects[0], 0.25f); ++ ok(hr == SPTLAUDCLNT_E_OUT_OF_ORDER, "Got %#lx outside an update pass.\n", hr); ++ ++ hr = ISpatialAudioObjectRenderStream_Start(sas); ++ ok(hr == S_OK, "Failed to start dynamic stream: %#lx.\n", hr); ++ if (hr != S_OK) ++ goto cleanup; ++ hr = WaitForSingleObject(event, 500); ++ ok(hr == WAIT_OBJECT_0, "Timed out waiting for a dynamic update: %#lx.\n", hr); ++ ++ hr = ISpatialAudioObjectRenderStream_BeginUpdatingAudioObjects(sas, &available, &frames); ++ ok(hr == S_OK, "Failed to begin dynamic update: %#lx.\n", hr); ++ if (hr != S_OK) ++ goto cleanup; ++ ok(available == limit, "Expected render capacity %u with allocated objects, got %u.\n", limit, available); ++ ok(frames != 0, "Expected a nonzero dynamic update.\n"); ++ ++ for (i = 0; i < limit; ++i) ++ { ++ hr = ISpatialAudioObject_GetBuffer(objects[i], &buffer, &bytes); ++ ok(hr == S_OK, "Failed to get dynamic buffer %u: %#lx.\n", i, hr); ++ if (hr != S_OK) ++ continue; ++ ok(bytes == frames * format.nBlockAlign, ++ "Expected %u bytes, got %u for dynamic object %u.\n", ++ frames * format.nBlockAlign, bytes, i); ++ for (j = 0; j < frames; ++j) ++ ((float *)buffer)[j] = (float)(i + 1) / 16.0f; ++ } ++ ++ hr = ISpatialAudioObject_SetPosition(objects[0], 1.25f, -0.5f, 3.0f); ++ ok(hr == S_OK, "Failed to position a dynamic object: %#lx.\n", hr); ++ hr = ISpatialAudioObject_SetPosition(objects[0], NAN, 0.0f, 0.0f); ++ ok(hr == E_INVALIDARG, "Expected NaN position to be rejected, got %#lx.\n", hr); ++ hr = ISpatialAudioObject_SetPosition(objects[0], 0.0f, INFINITY, 0.0f); ++ ok(hr == E_INVALIDARG, "Expected infinite position to be rejected, got %#lx.\n", hr); ++ hr = ISpatialAudioObject_SetVolume(objects[0], 0.25f); ++ ok(hr == S_OK, "Failed to set dynamic volume: %#lx.\n", hr); ++ ++ if (limit > 1) ++ { ++ hr = ISpatialAudioObject_SetEndOfStream(objects[1], frames / 2); ++ ok(hr == S_OK, "Failed to end a dynamic object: %#lx.\n", hr); ++ hr = ISpatialAudioObject_IsActive(objects[1], &active); ++ ok(hr == S_OK && !active, "Expected ended object to be inactive, got %d, %#lx.\n", ++ active, hr); ++ } ++ ++ hr = ISpatialAudioObjectRenderStream_EndUpdatingAudioObjects(sas); ++ ok(hr == S_OK, "Failed to submit dynamic update: %#lx.\n", hr); ++ ++ /* Keep the maximum-object graph busy long enough to exercise cursor and ++ * metadata wraparound and to provide a useful callback percentile sample. ++ * The ended slot stays retained but is not rendered. */ ++ for (iteration = 0; iteration < 64; ++iteration) ++ { ++ hr = WaitForSingleObject(event, 500); ++ ok(hr == WAIT_OBJECT_0, "Timed out waiting for steady update %u: %#lx.\n", ++ iteration, hr); ++ if (hr != WAIT_OBJECT_0) ++ goto cleanup; ++ hr = ISpatialAudioObjectRenderStream_BeginUpdatingAudioObjects(sas, ++ &available, &frames); ++ ok(hr == S_OK, "Failed to begin steady update %u: %#lx.\n", iteration, hr); ++ if (hr != S_OK) ++ goto cleanup; ++ for (i = 0; i < limit; ++i) ++ { ++ if (i == 1 && limit > 1) ++ continue; ++ hr = ISpatialAudioObject_GetBuffer(objects[i], &buffer, &bytes); ++ ok(hr == S_OK, "Failed steady buffer %u/%u: %#lx.\n", iteration, i, hr); ++ if (hr == S_OK) ++ for (j = 0; j < frames; ++j) ++ ((float *)buffer)[j] = (float)(i + 1) / 32.0f; ++ } ++ hr = ISpatialAudioObject_SetPosition(objects[0], ++ (iteration & 1) ? -1.0f : 1.0f, ++ (float)(iteration % 5) * 0.1f, -2.0f); ++ ok(hr == S_OK, "Failed steady position %u: %#lx.\n", iteration, hr); ++ hr = ISpatialAudioObject_SetVolume(objects[0], ++ 0.25f + (float)(iteration % 4) * 0.125f); ++ ok(hr == S_OK, "Failed steady volume %u: %#lx.\n", iteration, hr); ++ hr = ISpatialAudioObjectRenderStream_EndUpdatingAudioObjects(sas); ++ ok(hr == S_OK, "Failed to submit steady update %u: %#lx.\n", iteration, hr); ++ } ++ ++ hr = WaitForSingleObject(event, 500); ++ ok(hr == WAIT_OBJECT_0, "Timed out waiting for a second dynamic update: %#lx.\n", hr); ++ hr = ISpatialAudioObjectRenderStream_BeginUpdatingAudioObjects(sas, &available, &frames); ++ ok(hr == S_OK, "Failed to begin second dynamic update: %#lx.\n", hr); ++ if (hr != S_OK) ++ goto cleanup; ++ ++ if (limit > 1) ++ { ++ hr = ISpatialAudioObject_GetBuffer(objects[1], &buffer, &bytes); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, ++ "Expected ended object to reject buffers, got %#lx.\n", hr); ++ ISpatialAudioObject_Release(objects[1]); ++ objects[1] = NULL; ++ hr = ISpatialAudioObjectRenderStream_GetAvailableDynamicObjectCount(sas, &available); ++ ok(hr == S_OK && !available, ++ "A slot released during an update must remain retained until End, got %u, %#lx.\n", ++ available, hr); ++ } ++ ++ /* Omit object zero after its lifetime started: this is implicit EOS. */ ++ for (i = 1; i < limit; ++i) ++ { ++ if (!objects[i]) ++ continue; ++ hr = ISpatialAudioObject_GetBuffer(objects[i], &buffer, &bytes); ++ ok(hr == S_OK, "Failed to preserve dynamic object %u: %#lx.\n", i, hr); ++ } ++ hr = ISpatialAudioObjectRenderStream_EndUpdatingAudioObjects(sas); ++ ok(hr == S_OK, "Failed to submit implicit-EOS update: %#lx.\n", hr); ++ hr = ISpatialAudioObject_IsActive(objects[0], &active); ++ ok(hr == S_OK && !active, "Expected implicit EOS, got active %d and %#lx.\n", active, hr); ++ ++ ISpatialAudioObject_Release(objects[0]); ++ objects[0] = NULL; ++ hr = ISpatialAudioObjectRenderStream_GetAvailableDynamicObjectCount(sas, &available); ++ ok(hr == S_OK && available == (limit > 1 ? 2 : 1), ++ "Expected released dynamic slots to be reusable, got %u, %#lx.\n", available, hr); ++ ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(sas, ++ AudioObjectType_Dynamic, &replacement); ++ ok(hr == S_OK, "Failed to reuse a dynamic slot: %#lx.\n", hr); ++ if (hr == S_OK) ++ { ++ hr = WaitForSingleObject(event, 500); ++ ok(hr == WAIT_OBJECT_0, "Timed out waiting for reuse update: %#lx.\n", hr); ++ hr = ISpatialAudioObjectRenderStream_BeginUpdatingAudioObjects(sas, &available, &frames); ++ ok(hr == S_OK, "Failed to begin reuse update: %#lx.\n", hr); ++ if (hr == S_OK) ++ { ++ struct object_release_thread_context *release_context; ++ DWORD wait, exit_code = ~0u; ++ HANDLE thread = NULL; ++ ++ hr = ISpatialAudioObject_GetBuffer(replacement, &buffer, &bytes); ++ ok(hr == S_OK, "Failed to get reused dynamic buffer: %#lx.\n", hr); ++ hr = ISpatialAudioObject_SetPosition(replacement, -2.0f, 1.0f, -4.0f); ++ ok(hr == S_OK, "Failed to position reused dynamic object: %#lx.\n", hr); ++ hr = ISpatialAudioObject_SetEndOfStream(replacement, frames); ++ ok(hr == S_OK, "Failed to end reused dynamic object: %#lx.\n", hr); ++ ++ release_context = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*release_context)); ++ ok(!!release_context, "Failed to allocate release thread context.\n"); ++ if (release_context) ++ { ++ release_context->object = replacement; ++ release_context->ready_event = CreateEventW(NULL, TRUE, FALSE, NULL); ++ release_context->release_event = CreateEventW(NULL, TRUE, FALSE, NULL); ++ } ++ ok(release_context && release_context->ready_event && release_context->release_event, ++ "Failed to create release barriers: %lu.\n", GetLastError()); ++ if (release_context && release_context->ready_event && release_context->release_event) ++ thread = CreateThread(NULL, 0, object_release_thread, ++ release_context, 0, NULL); ++ ok(!!thread, "Failed to create object-release thread: %lu.\n", GetLastError()); ++ ++ if (thread) ++ { ++ /* Transfer the sole object reference to the worker. Both ++ * contenders leave this barrier together; either lock order ++ * must retain the final buffer and free the slot once. */ ++ replacement = NULL; ++ wait = WaitForSingleObject(release_context->ready_event, 5000); ++ ok(wait == WAIT_OBJECT_0, ++ "Object-release thread did not reach its barrier: %#lx.\n", wait); ++ ok(SetEvent(release_context->release_event), ++ "Failed to open object-release barrier: %lu.\n", GetLastError()); ++ hr = ISpatialAudioObjectRenderStream_EndUpdatingAudioObjects(sas); ++ ok(hr == S_OK, "Failed concurrent EndUpdatingAudioObjects: %#lx.\n", hr); ++ wait = WaitForSingleObject(thread, 5000); ++ ok(wait == WAIT_OBJECT_0, "Object-release thread timed out: %#lx.\n", wait); ++ ok(GetExitCodeThread(thread, &exit_code), ++ "Failed to query object-release thread: %lu.\n", GetLastError()); ++ ok(exit_code == 0, "Object-release thread failed: %lu.\n", exit_code); ++ ok(release_context->release_ref == 0, ++ "Expected worker to release the last object reference, got %lu.\n", ++ release_context->release_ref); ++ if (wait == WAIT_OBJECT_0 && exit_code != 0) ++ ISpatialAudioObject_Release(release_context->object); ++ if (wait == WAIT_OBJECT_0) ++ CloseHandle(thread); ++ } ++ else ++ { ++ ISpatialAudioObject_Release(replacement); ++ replacement = NULL; ++ hr = ISpatialAudioObjectRenderStream_EndUpdatingAudioObjects(sas); ++ ok(hr == S_OK, "Failed fallback release-during-update buffer: %#lx.\n", hr); ++ } ++ if (!thread || wait == WAIT_OBJECT_0) ++ { ++ if (release_context && release_context->release_event) ++ CloseHandle(release_context->release_event); ++ if (release_context && release_context->ready_event) ++ CloseHandle(release_context->ready_event); ++ if (release_context) ++ HeapFree(GetProcessHeap(), 0, release_context); ++ } ++ hr = ISpatialAudioObjectRenderStream_GetAvailableDynamicObjectCount(sas, &available); ++ ok(hr == S_OK && available == (limit > 1 ? 2 : 1), ++ "Concurrent release leaked or duplicated a slot, got %u, %#lx.\n", ++ available, hr); ++ } ++ } ++ ++cleanup: ++ if (replacement) ++ ISpatialAudioObject_Release(replacement); ++ for (i = 0; i < limit; ++i) ++ if (objects[i]) ++ ISpatialAudioObject_Release(objects[i]); ++ if (sas) ++ { ++ ISpatialAudioObjectRenderStream_Stop(sas); ++ ISpatialAudioObjectRenderStream_Release(sas); ++ } ++ free(objects); ++} ++ + START_TEST(spatialaudio) + { + HRESULT hr; +@@ -511,9 +1400,14 @@ START_TEST(spatialaudio) + /* ok(max_dyn_count == 0, "expected max dynamic object count to be 0 got %u\n", max_dyn_count); */ + + test_formats(); ++ test_static_object_properties(); + test_stream_activation(); + test_audio_object_activation(); + test_audio_object_buffers(); ++ test_proactive_invalidation(); ++ test_proactive_reentrant_release(); ++ test_prestart_invalidation(); ++ test_dynamic_audio_objects(); + + ISpatialAudioClient_Release(sac); + diff --git a/patches/wine11/0007-spatial-audio-services.patch b/patches/wine11/0007-spatial-audio-services.patch new file mode 100644 index 0000000..56908a1 --- /dev/null +++ b/patches/wine11/0007-spatial-audio-services.patch @@ -0,0 +1,665 @@ +From: Mac Gaming Uncle contributors +Subject: [MGU] spatial stream clock, volume services and availability +License: LGPL-2.1-or-later + +--- a/dlls/mmdevapi/spatialaudio.c ++++ b/dlls/mmdevapi/spatialaudio.c +@@ -172,6 +172,9 @@ + }; + + struct SpatialAudioStreamImpl { ++ IAudioClock IAudioClock_iface; ++ IAudioClock2 IAudioClock2_iface; ++ IAudioStreamVolume IAudioStreamVolume_iface; + ISpatialAudioObjectRenderStream ISpatialAudioObjectRenderStream_iface; + LONG ref; + CRITICAL_SECTION lock; +@@ -750,17 +753,264 @@ + return S_OK; + } + +-static HRESULT WINAPI SAORS_GetService(ISpatialAudioObjectRenderStream *iface, +- REFIID riid, void **service) +-{ +- SpatialAudioStreamImpl *This = impl_from_ISpatialAudioObjectRenderStream(iface); +- FIXME("(%p)->(%s, %p)\n", This, debugstr_guid(riid), service); +- +- if (!service) +- return E_POINTER; +- ++/* Service references retain the spatial stream, including its renderer and ++ * endpoint-loss state, rather than returning the private audio client. */ ++static HRESULT spatial_service_backend(SpatialAudioStreamImpl *stream, REFIID iid, void **out) ++{ ++ BOOL notify; ++ HRESULT hr; ++ ++ *out = NULL; ++ EnterCriticalSection(&stream->lock); ++ notify = poll_stream_invalidation_locked(stream); ++ hr = stream->invalidation_hr; ++ if (SUCCEEDED(hr)) ++ hr = IAudioClient_GetService(stream->client, iid, out); ++ LeaveCriticalSection(&stream->lock); ++ if (notify) ++ notify_dynamic_capacity_lost(stream); ++ return hr; ++} ++ ++static HRESULT WINAPI spatial_clock_QueryInterface(IAudioClock *iface, REFIID iid, void **out) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock_iface); ++ ++ if (!out) return E_POINTER; ++ *out = NULL; ++ if (IsEqualIID(iid, &IID_IUnknown) || IsEqualIID(iid, &IID_IAudioClock)) ++ *out = iface; ++ else if (IsEqualIID(iid, &IID_IAudioClock2)) ++ *out = &stream->IAudioClock2_iface; ++ else ++ return E_NOINTERFACE; ++ SAORS_AddRef(&stream->ISpatialAudioObjectRenderStream_iface); ++ return S_OK; ++} ++ ++static ULONG WINAPI spatial_clock_AddRef(IAudioClock *iface) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock_iface); ++ return SAORS_AddRef(&stream->ISpatialAudioObjectRenderStream_iface); ++} ++ ++static ULONG WINAPI spatial_clock_Release(IAudioClock *iface) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock_iface); ++ return SAORS_Release(&stream->ISpatialAudioObjectRenderStream_iface); ++} ++ ++static HRESULT WINAPI spatial_clock_GetFrequency(IAudioClock *iface, UINT64 *value) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock_iface); ++ IAudioClock *backend; ++ HRESULT hr; ++ ++ if (!value) return E_POINTER; ++ if (FAILED(hr = spatial_service_backend(stream, &IID_IAudioClock, (void **)&backend))) return hr; ++ hr = IAudioClock_GetFrequency(backend, value); ++ IAudioClock_Release(backend); ++ return hr; ++} ++ ++static HRESULT WINAPI spatial_clock_GetPosition(IAudioClock *iface, UINT64 *value, UINT64 *qpc) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock_iface); ++ IAudioClock *backend; ++ HRESULT hr; ++ ++ if (!value) return E_POINTER; ++ if (FAILED(hr = spatial_service_backend(stream, &IID_IAudioClock, (void **)&backend))) return hr; ++ hr = IAudioClock_GetPosition(backend, value, qpc); ++ IAudioClock_Release(backend); ++ return hr; ++} ++ ++static HRESULT WINAPI spatial_clock_GetCharacteristics(IAudioClock *iface, DWORD *value) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock_iface); ++ IAudioClock *backend; ++ HRESULT hr; ++ ++ if (!value) return E_POINTER; ++ if (FAILED(hr = spatial_service_backend(stream, &IID_IAudioClock, (void **)&backend))) return hr; ++ hr = IAudioClock_GetCharacteristics(backend, value); ++ IAudioClock_Release(backend); ++ return hr; ++} ++ ++static const IAudioClockVtbl spatial_clock_vtbl = ++{ ++ spatial_clock_QueryInterface, spatial_clock_AddRef, spatial_clock_Release, ++ spatial_clock_GetFrequency, spatial_clock_GetPosition, spatial_clock_GetCharacteristics ++}; ++ ++static HRESULT WINAPI spatial_clock2_QueryInterface(IAudioClock2 *iface, REFIID iid, void **out) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock2_iface); ++ return spatial_clock_QueryInterface(&stream->IAudioClock_iface, iid, out); ++} ++ ++static ULONG WINAPI spatial_clock2_AddRef(IAudioClock2 *iface) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock2_iface); ++ return SAORS_AddRef(&stream->ISpatialAudioObjectRenderStream_iface); ++} ++ ++static ULONG WINAPI spatial_clock2_Release(IAudioClock2 *iface) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock2_iface); ++ return SAORS_Release(&stream->ISpatialAudioObjectRenderStream_iface); ++} ++ ++static HRESULT WINAPI spatial_clock2_GetDevicePosition(IAudioClock2 *iface, UINT64 *position, UINT64 *qpc) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioClock2_iface); ++ IAudioClock *clock; ++ IAudioClock2 *backend; ++ HRESULT hr; ++ ++ if (!position) return E_POINTER; ++ if (FAILED(hr = spatial_service_backend(stream, &IID_IAudioClock, (void **)&clock))) return hr; ++ hr = IAudioClock_QueryInterface(clock, &IID_IAudioClock2, (void **)&backend); ++ IAudioClock_Release(clock); ++ if (FAILED(hr)) return hr; ++ hr = IAudioClock2_GetPosition(backend, position, qpc); ++ IAudioClock2_Release(backend); ++ return hr; ++} ++ ++static const IAudioClock2Vtbl spatial_clock2_vtbl = ++{ ++ spatial_clock2_QueryInterface, spatial_clock2_AddRef, spatial_clock2_Release, ++ spatial_clock2_GetDevicePosition ++}; ++ ++static HRESULT WINAPI spatial_volume_QueryInterface(IAudioStreamVolume *iface, REFIID iid, void **out) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioStreamVolume_iface); ++ ++ if (!out) return E_POINTER; ++ *out = NULL; ++ if (!IsEqualIID(iid, &IID_IUnknown) && !IsEqualIID(iid, &IID_IAudioStreamVolume)) ++ return E_NOINTERFACE; ++ *out = iface; ++ SAORS_AddRef(&stream->ISpatialAudioObjectRenderStream_iface); ++ return S_OK; ++} ++ ++static ULONG WINAPI spatial_volume_AddRef(IAudioStreamVolume *iface) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioStreamVolume_iface); ++ return SAORS_AddRef(&stream->ISpatialAudioObjectRenderStream_iface); ++} ++ ++static ULONG WINAPI spatial_volume_Release(IAudioStreamVolume *iface) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioStreamVolume_iface); ++ return SAORS_Release(&stream->ISpatialAudioObjectRenderStream_iface); ++} ++ ++static HRESULT WINAPI spatial_volume_GetChannelCount(IAudioStreamVolume *iface, UINT32 *count) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioStreamVolume_iface); ++ IAudioStreamVolume *backend; ++ HRESULT hr; ++ if (!count) return E_POINTER; ++ if (FAILED(hr = spatial_service_backend(stream, &IID_IAudioStreamVolume, (void **)&backend))) return hr; ++ hr = IAudioStreamVolume_GetChannelCount(backend, count); ++ IAudioStreamVolume_Release(backend); ++ return hr; ++} ++ ++static HRESULT WINAPI spatial_volume_GetChannelVolume(IAudioStreamVolume *iface, UINT32 index, float *level) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioStreamVolume_iface); ++ IAudioStreamVolume *backend; ++ HRESULT hr; ++ if (!level) return E_POINTER; ++ if (index >= stream->stream_fmtex.Format.nChannels) return E_INVALIDARG; ++ if (FAILED(hr = spatial_service_backend(stream, &IID_IAudioStreamVolume, (void **)&backend))) return hr; ++ hr = IAudioStreamVolume_GetChannelVolume(backend, index, level); ++ IAudioStreamVolume_Release(backend); ++ return hr; ++} ++ ++static HRESULT WINAPI spatial_volume_SetChannelVolume(IAudioStreamVolume *iface, UINT32 index, float level) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioStreamVolume_iface); ++ IAudioStreamVolume *backend; ++ HRESULT hr; ++ if (index >= stream->stream_fmtex.Format.nChannels || !isfinite(level) || level < 0.0f || level > 1.0f) return E_INVALIDARG; ++ if (FAILED(hr = spatial_service_backend(stream, &IID_IAudioStreamVolume, (void **)&backend))) return hr; ++ hr = IAudioStreamVolume_SetChannelVolume(backend, index, level); ++ IAudioStreamVolume_Release(backend); ++ return hr; ++} ++ ++static HRESULT WINAPI spatial_volume_GetAllVolumes(IAudioStreamVolume *iface, UINT32 count, float *levels) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioStreamVolume_iface); ++ IAudioStreamVolume *backend; ++ HRESULT hr; ++ if (!levels) return E_POINTER; ++ if (count != stream->stream_fmtex.Format.nChannels) return E_INVALIDARG; ++ if (FAILED(hr = spatial_service_backend(stream, &IID_IAudioStreamVolume, (void **)&backend))) return hr; ++ hr = IAudioStreamVolume_GetAllVolumes(backend, count, levels); ++ IAudioStreamVolume_Release(backend); ++ return hr; ++} ++ ++static HRESULT WINAPI spatial_volume_SetAllVolumes(IAudioStreamVolume *iface, UINT32 count, const float *levels) ++{ ++ SpatialAudioStreamImpl *stream = CONTAINING_RECORD(iface, SpatialAudioStreamImpl, IAudioStreamVolume_iface); ++ IAudioStreamVolume *backend; ++ HRESULT hr; ++ UINT32 i; ++ ++ if (!levels) return E_POINTER; ++ if (count != stream->stream_fmtex.Format.nChannels) return E_INVALIDARG; ++ for (i = 0; i < count; ++i) ++ if (!isfinite(levels[i]) || levels[i] < 0.0f || levels[i] > 1.0f) return E_INVALIDARG; ++ if (FAILED(hr = spatial_service_backend(stream, &IID_IAudioStreamVolume, (void **)&backend))) return hr; ++ hr = IAudioStreamVolume_SetAllVolumes(backend, count, levels); ++ IAudioStreamVolume_Release(backend); ++ return hr; ++} ++ ++static const IAudioStreamVolumeVtbl spatial_volume_vtbl = ++{ ++ spatial_volume_QueryInterface, spatial_volume_AddRef, spatial_volume_Release, ++ spatial_volume_GetChannelCount, spatial_volume_SetChannelVolume, ++ spatial_volume_GetChannelVolume, spatial_volume_SetAllVolumes, spatial_volume_GetAllVolumes ++}; ++ ++static HRESULT WINAPI SAORS_GetService(ISpatialAudioObjectRenderStream *iface, REFIID iid, void **service) ++{ ++ SpatialAudioStreamImpl *stream = impl_from_ISpatialAudioObjectRenderStream(iface); ++ BOOL notify; ++ HRESULT hr; ++ ++ if (!service) return E_POINTER; + *service = NULL; +- return E_NOTIMPL; ++ EnterCriticalSection(&stream->lock); ++ notify = poll_stream_invalidation_locked(stream); ++ hr = stream->invalidation_hr; ++ if (SUCCEEDED(hr)) ++ { ++ if (IsEqualIID(iid, &IID_IAudioClock)) ++ *service = &stream->IAudioClock_iface; ++ else if (IsEqualIID(iid, &IID_IAudioClock2)) ++ *service = &stream->IAudioClock2_iface; ++ else if (IsEqualIID(iid, &IID_IAudioStreamVolume)) ++ *service = &stream->IAudioStreamVolume_iface; ++ else ++ hr = E_NOINTERFACE; ++ if (*service) SAORS_AddRef(iface); ++ } ++ LeaveCriticalSection(&stream->lock); ++ if (notify) notify_dynamic_capacity_lost(stream); ++ return hr; + } + + static HRESULT WINAPI SAORS_Start(ISpatialAudioObjectRenderStream *iface) +@@ -1437,8 +1687,12 @@ + REFIID stream_uuid, const PROPVARIANT *info) + { + SpatialAudioImpl *This = impl_from_ISpatialAudioClient(iface); +- FIXME("(%p)->(%s, %p)\n", This, debugstr_guid(stream_uuid), info); +- return E_NOTIMPL; ++ struct spatial_audio_capabilities capabilities; ++ ++ TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(stream_uuid), info); ++ if (!IsEqualIID(stream_uuid, &IID_ISpatialAudioObjectRenderStream)) ++ return SPTLAUDCLNT_E_STREAM_NOT_AVAILABLE; ++ return audio_client_get_spatial_audio_capabilities(This->mmdev, &capabilities); + } + + static WAVEFORMATEX *clone_fmtex(const WAVEFORMATEX *src) +@@ -1706,6 +1960,9 @@ + return E_OUTOFMEMORY; + + obj->ISpatialAudioObjectRenderStream_iface.lpVtbl = &ISpatialAudioObjectRenderStream_vtbl; ++ obj->IAudioClock_iface.lpVtbl = &spatial_clock_vtbl; ++ obj->IAudioClock2_iface.lpVtbl = &spatial_clock2_vtbl; ++ obj->IAudioStreamVolume_iface.lpVtbl = &spatial_volume_vtbl; + obj->ref = 1; + memcpy(&obj->params, params, sizeof(obj->params)); + obj->params.MaxDynamicObjectCount = dynamic_count; +--- a/dlls/winecoreaudio.drv/coreaudio.c ++++ b/dlls/winecoreaudio.drv/coreaudio.c +@@ -143,6 +143,8 @@ + UINT32 cap_bufsize_frames, cap_offs_frames, cap_held_frames; + UINT32 wrap_bufsize_frames; + UINT64 written_frames; ++ UINT64 spatial_device_position; ++ UINT64 spatial_device_qpc; + INT32 getbuf_last; + WAVEFORMATEX *fmt; + UINT32 *spatial_volume_bits; +@@ -4386,9 +4388,55 @@ + struct coreaudio_stream *stream = handle_get_stream(params->stream); + LARGE_INTEGER stamp, freq; + +- if (params->device) { +- FIXME("Device position reporting not implemented\n"); +- params->result = E_NOTIMPL; ++ if (params->device) ++ { ++ AudioTimeStamp time = {0}; ++ mach_timebase_info_data_t timebase; ++ UINT64 host_now; ++ long double qpc; ++ OSStatus status; ++ ++ if (!stream->spatial) ++ { ++ params->result = E_NOTIMPL; ++ return STATUS_SUCCESS; ++ } ++ os_unfair_lock_lock(&stream->lock); ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ else if (!__atomic_load_n(&stream->playing, __ATOMIC_ACQUIRE)) ++ { ++ *params->pos = stream->spatial_device_position; ++ if (params->qpctime) *params->qpctime = stream->spatial_device_qpc; ++ params->result = AUDCLNT_S_POSITION_STALLED; ++ } ++ else if ((status = AudioDeviceGetCurrentTime(stream->dev_id, &time)) != noErr) ++ params->result = osstatus_to_hresult(status); ++ else if (!(time.mFlags & kAudioTimeStampSampleTimeValid) || ++ !isfinite(time.mSampleTime) || time.mSampleTime < 0.0 || ++ time.mSampleTime >= (double)~(UINT64)0) ++ params->result = E_FAIL; ++ else ++ { ++ /* CoreAudio's device timeline is in endpoint frames, not the ++ * private PCM transport's bytes or client-rate frames. */ ++ stream->spatial_device_position = time.mSampleTime; ++ NtQueryPerformanceCounter(&stamp, &freq); ++ qpc = (long double)stamp.QuadPart * 10000000 / freq.QuadPart; ++ /* Audio host time excludes sleep, while Wine QPC uses continuous ++ * time. Map the correlated device stamp relative to now rather ++ * than treating the two clock epochs as interchangeable. */ ++ host_now = mach_absolute_time(); ++ if ((time.mFlags & kAudioTimeStampHostTimeValid) && ++ mach_timebase_info(&timebase) == KERN_SUCCESS) ++ qpc -= ((long double)host_now - time.mHostTime) * ++ timebase.numer / timebase.denom / 100; ++ stream->spatial_device_qpc = qpc > 0 ? qpc : 0; ++ *params->pos = stream->spatial_device_position; ++ if (params->qpctime) *params->qpctime = stream->spatial_device_qpc; ++ params->result = S_OK; ++ } ++ os_unfair_lock_unlock(&stream->lock); + return STATUS_SUCCESS; + } + +@@ -4425,6 +4473,16 @@ + struct get_frequency_params *params = args; + struct coreaudio_stream *stream = handle_get_stream(params->stream); + ++ if (!params->freq) ++ { ++ params->result = E_POINTER; ++ return STATUS_SUCCESS; ++ } ++ if (__atomic_load_n(&stream->invalidated, __ATOMIC_ACQUIRE)) ++ { ++ params->result = AUDCLNT_E_DEVICE_INVALIDATED; ++ return STATUS_SUCCESS; ++ } + if(stream->share == AUDCLNT_SHAREMODE_SHARED) + *params->freq = (UINT64)stream->fmt->nSamplesPerSec * stream->fmt->nBlockAlign; + else +--- a/dlls/mmdevapi/tests/spatialaudio.c ++++ b/dlls/mmdevapi/tests/spatialaudio.c +@@ -461,6 +461,12 @@ + ISpatialAudioObjectRenderStream *stream = NULL; + ISpatialAudioObject *object = NULL; + NotifyObject notify; ++ IAudioClock *clock = NULL; ++ IAudioClock2 *clock2 = NULL; ++ IAudioStreamVolume *volume = NULL; ++ UINT64 position; ++ float level; ++ void *service; + BYTE *buffer = NULL; + UINT32 available = ~0u; + UINT32 bytes = ~0u; +@@ -496,6 +502,12 @@ + if (hr != S_OK || !object) + goto done; + ++ hr = ISpatialAudioObjectRenderStream_GetService(stream, &IID_IAudioClock, (void **)&clock); ++ ok(hr == S_OK, "Fault clock acquisition failed %#lx.\n", hr); ++ hr = ISpatialAudioObjectRenderStream_GetService(stream, &IID_IAudioClock2, (void **)&clock2); ++ ok(hr == S_OK, "Fault clock2 acquisition failed %#lx.\n", hr); ++ hr = ISpatialAudioObjectRenderStream_GetService(stream, &IID_IAudioStreamVolume, (void **)&volume); ++ ok(hr == S_OK, "Fault volume acquisition failed %#lx.\n", hr); + hr = ISpatialAudioObjectRenderStream_Start(stream); + ok(hr == S_OK || hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED || + hr == AUDCLNT_E_DEVICE_INVALIDATED || +@@ -511,6 +523,26 @@ + wine_dbgstr_longlong(notify.deadline)); + ok(!notify.object_count, "Expected zero available objects, got %u.\n", + notify.object_count); ++ if (clock) ++ { ++ hr = IAudioClock_GetFrequency(clock, &position); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, "Lost clock returned %#lx.\n", hr); ++ } ++ if (clock2) ++ { ++ hr = IAudioClock2_GetPosition(clock2, &position, NULL); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, "Lost device clock returned %#lx.\n", hr); ++ } ++ if (volume) ++ { ++ hr = IAudioStreamVolume_GetChannelVolume(volume, 0, &level); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, "Lost volume returned %#lx.\n", hr); ++ hr = IAudioStreamVolume_SetChannelVolume(volume, 0, 0.5f); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED, "Lost volume setter returned %#lx.\n", hr); ++ } ++ service = (void *)0xdeadbeef; ++ hr = ISpatialAudioObjectRenderStream_GetService(stream, &IID_IAudioClock, &service); ++ ok(hr == SPTLAUDCLNT_E_RESOURCES_INVALIDATED && !service, "Lost service output not cleared %#lx/%p.\n", hr, service); + hr = ISpatialAudioObject_IsActive(object, &active); + ok(hr == S_OK && !active, + "Expected the endpoint-loss object to be inactive, got %#lx/%d.\n", +@@ -530,6 +562,9 @@ + ok(wait == WAIT_TIMEOUT, "Expected a one-shot notification, got %#lx.\n", wait); + } + ++ if (volume) { IAudioStreamVolume_Release(volume); volume = NULL; } ++ if (clock2) { IAudioClock2_Release(clock2); clock2 = NULL; } ++ if (clock) { IAudioClock_Release(clock); clock = NULL; } + ISpatialAudioObject_Release(object); + object = NULL; + ISpatialAudioObjectRenderStream_Release(stream); +@@ -542,6 +577,9 @@ + InterlockedCompareExchange(¬ify.ref, 0, 0)); + + done: ++ if (volume) IAudioStreamVolume_Release(volume); ++ if (clock2) IAudioClock2_Release(clock2); ++ if (clock) IAudioClock_Release(clock); + if (object) + ISpatialAudioObject_Release(object); + if (stream) +@@ -1356,6 +1394,178 @@ + free(objects); + } + ++static void test_spatial_services(void) ++{ ++ SpatialAudioObjectRenderStreamActivationParams params; ++ PROPVARIANT activation; ++ ISpatialAudioObjectRenderStream *stream = NULL; ++ ISpatialAudioObject *object = NULL; ++ IAudioClock *clock = NULL, *other_clock; ++ IAudioClock2 *clock2 = NULL, *other_clock2; ++ IAudioStreamVolume *volume = NULL; ++ IUnknown *unknown, *other_unknown; ++ UINT64 frequency, position, later, qpc, device_position; ++ UINT32 count, available, frames, bytes, i; ++ DWORD characteristics; ++ float *levels = NULL, level; ++ BYTE *buffer; ++ HRESULT hr; ++ void *service; ++ ++ if (!spatial_stream_supported || !max_dyn_count) ++ { ++ win_skip("Spatial services need a rendering endpoint.\n"); ++ return; ++ } ++ hr = ISpatialAudioClient_IsSpatialAudioStreamAvailable(sac, &IID_ISpatialAudioObjectRenderStream, NULL); ++ ok(hr == S_OK, "Expected the base stream to be available, got %#lx.\n", hr); ++ hr = ISpatialAudioClient_IsSpatialAudioStreamAvailable(sac, &IID_IAudioClient, NULL); ++ ok(hr == SPTLAUDCLNT_E_STREAM_NOT_AVAILABLE, "Unexpected unsupported stream result %#lx.\n", hr); ++ fill_activation_params(¶ms); ++ params.StaticObjectTypeMask = AudioObjectType_FrontLeft | AudioObjectType_FrontRight; ++ params.MaxDynamicObjectCount = min(max_dyn_count, 2); ++ params.MinDynamicObjectCount = params.MaxDynamicObjectCount; ++ PropVariantInit(&activation); ++ activation.vt = VT_BLOB; ++ activation.blob.cbSize = sizeof(params); ++ activation.blob.pBlobData = (BYTE *)¶ms; ++ hr = ISpatialAudioClient_ActivateSpatialAudioStream(sac, &activation, &IID_ISpatialAudioObjectRenderStream, (void **)&stream); ++ ok(hr == S_OK, "Service stream activation failed %#lx.\n", hr); ++ if (FAILED(hr)) return; ++ hr = ISpatialAudioObjectRenderStream_GetService(stream, &IID_IAudioClock, NULL); ++ ok(hr == E_POINTER, "Expected null output rejection, got %#lx.\n", hr); ++ service = (void *)0xdeadbeef; ++ hr = ISpatialAudioObjectRenderStream_GetService(stream, &IID_IAudioClient, &service); ++ ok(hr == E_NOINTERFACE && !service, "Unknown service must clear output, got %#lx/%p.\n", hr, service); ++ hr = ISpatialAudioObjectRenderStream_GetService(stream, &IID_IAudioClock, (void **)&clock); ++ ok(hr == S_OK && clock, "Clock service failed %#lx.\n", hr); ++ hr = ISpatialAudioObjectRenderStream_GetService(stream, &IID_IAudioClock2, (void **)&clock2); ++ ok(hr == S_OK && clock2, "Clock2 service failed %#lx.\n", hr); ++ hr = ISpatialAudioObjectRenderStream_GetService(stream, &IID_IAudioStreamVolume, (void **)&volume); ++ ok(hr == S_OK && volume, "Volume service failed %#lx.\n", hr); ++ if (!clock || !clock2 || !volume) goto done; ++ ++ hr = IAudioClock_QueryInterface(clock, &IID_IAudioClock2, (void **)&other_clock2); ++ ok(hr == S_OK && other_clock2 == clock2, "Clock2 identity mismatch %#lx.\n", hr); ++ if (SUCCEEDED(hr)) IAudioClock2_Release(other_clock2); ++ hr = IAudioClock2_QueryInterface(clock2, &IID_IAudioClock, (void **)&other_clock); ++ ok(hr == S_OK && other_clock == clock, "Clock identity mismatch %#lx.\n", hr); ++ if (SUCCEEDED(hr)) IAudioClock_Release(other_clock); ++ IAudioClock_QueryInterface(clock, &IID_IUnknown, (void **)&unknown); ++ IAudioClock2_QueryInterface(clock2, &IID_IUnknown, (void **)&other_unknown); ++ ok(unknown == other_unknown, "The clocks must have the same controlling unknown.\n"); ++ IUnknown_Release(unknown); ++ IUnknown_Release(other_unknown); ++ hr = IAudioClock_GetFrequency(clock, NULL); ++ ok(hr == E_POINTER, "Expected clock pointer validation, got %#lx.\n", hr); ++ hr = IAudioClock_GetPosition(clock, NULL, NULL); ++ ok(hr == E_POINTER, "Expected position pointer validation, got %#lx.\n", hr); ++ hr = IAudioClock2_GetPosition(clock2, NULL, NULL); ++ ok(hr == E_POINTER, "Expected device pointer validation, got %#lx.\n", hr); ++ hr = IAudioClock_GetFrequency(clock, &frequency); ++ ok(hr == S_OK && frequency, "Invalid clock frequency %#lx.\n", hr); ++ hr = IAudioClock_GetCharacteristics(clock, &characteristics); ++ ok(hr == S_OK && characteristics == AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ, "Invalid clock characteristics %#lx.\n", hr); ++ hr = IAudioClock2_GetPosition(clock2, &device_position, &qpc); ++ ok(hr == AUDCLNT_S_POSITION_STALLED, "Stopped device clock must be stalled, got %#lx.\n", hr); ++ ++ hr = IAudioStreamVolume_GetChannelCount(volume, &count); ++ ok(hr == S_OK && count, "Invalid volume channel count %#lx/%u.\n", hr, count); ++ levels = calloc(count, sizeof(*levels)); ++ if (!levels) goto done; ++ hr = IAudioStreamVolume_GetAllVolumes(volume, count, levels); ++ ok(hr == S_OK, "GetAllVolumes failed %#lx.\n", hr); ++ for (i = 0; i < count; ++i) ++ ok(levels[i] == 1.0f, "Expected unity channel %u, got %f.\n", i, levels[i]); ++ hr = IAudioStreamVolume_SetChannelVolume(volume, count, 0.5f); ++ ok(hr == E_INVALIDARG, "Invalid channel accepted %#lx.\n", hr); ++ hr = IAudioStreamVolume_SetChannelVolume(volume, 0, NAN); ++ ok(hr == E_INVALIDARG, "NaN volume accepted %#lx.\n", hr); ++ hr = IAudioStreamVolume_SetChannelVolume(volume, 0, INFINITY); ++ ok(hr == E_INVALIDARG, "Infinite volume accepted %#lx.\n", hr); ++ hr = IAudioStreamVolume_SetChannelVolume(volume, 0, -0.5f); ++ ok(hr == E_INVALIDARG, "Negative volume accepted %#lx.\n", hr); ++ hr = IAudioStreamVolume_SetChannelVolume(volume, 0, 1.5f); ++ ok(hr == E_INVALIDARG, "Excess volume accepted %#lx.\n", hr); ++ hr = IAudioStreamVolume_SetAllVolumes(volume, count, NULL); ++ ok(hr == E_POINTER, "Null volumes accepted %#lx.\n", hr); ++ hr = IAudioStreamVolume_GetAllVolumes(volume, count - 1, levels); ++ ok(hr == E_INVALIDARG, "Wrong volume count accepted %#lx.\n", hr); ++ for (i = 0; i < count; ++i) levels[i] = 0.5f; ++ levels[count - 1] = NAN; ++ hr = IAudioStreamVolume_SetAllVolumes(volume, count, levels); ++ ok(hr == E_INVALIDARG, "Invalid batch accepted %#lx.\n", hr); ++ hr = IAudioStreamVolume_GetChannelVolume(volume, 0, &level); ++ ok(hr == S_OK && level == 1.0f, "Invalid batch changed earlier channels: %#lx/%f.\n", hr, level); ++ levels[count - 1] = 0.5f; ++ hr = IAudioStreamVolume_SetAllVolumes(volume, count, levels); ++ ok(hr == S_OK, "Valid volume batch failed %#lx.\n", hr); ++ hr = IAudioStreamVolume_SetChannelVolume(volume, 0, 0.25f); ++ ok(hr == S_OK, "Channel setter failed %#lx.\n", hr); ++ hr = IAudioStreamVolume_GetAllVolumes(volume, count, levels); ++ ok(hr == S_OK && levels[0] == 0.25f, "Volume round trip failed %#lx.\n", hr); ++ for (i = 1; i < count; ++i) ok(levels[i] == 0.5f, "Unexpected channel %u volume %f.\n", i, levels[i]); ++ ++ hr = ISpatialAudioObjectRenderStream_Start(stream); ++ ok(hr == S_OK, "Start failed %#lx.\n", hr); ++ if (FAILED(hr)) goto done; ++ for (i = 0; i < 8; ++i) ++ { ++ hr = WaitForSingleObject(event, 1000); ++ ok(hr == WAIT_OBJECT_0, "Service update timeout %u.\n", i); ++ if (hr != WAIT_OBJECT_0) break; ++ hr = ISpatialAudioObjectRenderStream_BeginUpdatingAudioObjects(stream, &available, &frames); ++ ok(hr == S_OK, "Begin failed %#lx.\n", hr); ++ if (FAILED(hr)) break; ++ if (!object) ++ { ++ hr = ISpatialAudioObjectRenderStream_ActivateSpatialAudioObject(stream, AudioObjectType_Dynamic, &object); ++ ok(hr == S_OK, "Object activation failed %#lx.\n", hr); ++ } ++ if (object) ++ { ++ hr = ISpatialAudioObject_GetBuffer(object, &buffer, &bytes); ++ ok(hr == S_OK, "Buffer failed %#lx.\n", hr); ++ if (SUCCEEDED(hr)) memset(buffer, 0, bytes); ++ } ++ hr = ISpatialAudioObjectRenderStream_EndUpdatingAudioObjects(stream); ++ ok(hr == S_OK, "End failed %#lx.\n", hr); ++ } ++ Sleep(20); ++ hr = IAudioClock_GetPosition(clock, &position, &qpc); ++ ok(hr == S_OK && position && qpc, "Stream clock did not advance %#lx.\n", hr); ++ ok(position <= frequency, "Unexpected stream duration %s/%s.\n", wine_dbgstr_longlong(position), wine_dbgstr_longlong(frequency)); ++ hr = IAudioClock2_GetPosition(clock2, &device_position, &qpc); ++ ok(hr == S_OK && qpc, "Device clock failed %#lx.\n", hr); ++ Sleep(20); ++ hr = IAudioClock2_GetPosition(clock2, &later, NULL); ++ ok(hr == S_OK && later >= device_position, "Device clock regressed %#lx.\n", hr); ++ hr = ISpatialAudioObjectRenderStream_Stop(stream); ++ ok(hr == S_OK, "Stop failed %#lx.\n", hr); ++ hr = IAudioClock_GetPosition(clock, &position, NULL); ++ ok(hr == S_OK, "Stopped stream clock failed %#lx.\n", hr); ++ Sleep(20); ++ hr = IAudioClock_GetPosition(clock, &later, NULL); ++ ok(hr == S_OK && later == position, "Stopped stream clock advanced %#lx.\n", hr); ++ hr = ISpatialAudioObjectRenderStream_Reset(stream); ++ ok(hr == S_OK, "Reset failed %#lx.\n", hr); ++ if (object) { ISpatialAudioObject_Release(object); object = NULL; } ++ ISpatialAudioObjectRenderStream_Release(stream); ++ stream = NULL; ++ hr = IAudioClock_GetPosition(clock, &position, NULL); ++ ok(hr == S_OK && !position, "Service did not retain reset stream %#lx.\n", hr); ++ hr = IAudioStreamVolume_GetChannelVolume(volume, 0, &level); ++ ok(hr == S_OK && level == 0.25f, "Volume did not retain stream %#lx/%f.\n", hr, level); ++ ++done: ++ free(levels); ++ if (object) ISpatialAudioObject_Release(object); ++ if (volume) IAudioStreamVolume_Release(volume); ++ if (clock2) IAudioClock2_Release(clock2); ++ if (clock) IAudioClock_Release(clock); ++ if (stream) ISpatialAudioObjectRenderStream_Release(stream); ++} ++ + START_TEST(spatialaudio) + { + HRESULT hr; +@@ -1408,6 +1618,7 @@ + test_proactive_reentrant_release(); + test_prestart_invalidation(); + test_dynamic_audio_objects(); ++ test_spatial_services(); + + ISpatialAudioClient_Release(sac); + diff --git a/patches/wine11/README.md b/patches/wine11/README.md index c5e6e51..89f73be 100644 --- a/patches/wine11/README.md +++ b/patches/wine11/README.md @@ -21,3 +21,12 @@ The exact source URLs and checksums are in `runtime/indie-wine11/source.lock.json`. Run `scripts/build-indie-wine11.sh` to verify the archives, apply this series, build all open-source dependencies, and create the redistributable runtime archive. + +4. `0004-spatial-audio-com.patch` implements base spatial object streams and + reports per-pass dynamic rendering capacity independently of allocated slots. +5. `0005-spatial-audio-coreaudio.patch` implements the CoreAudio spatial renderer + and shared transport. +6. `0006-spatial-audio-tests.patch` validates spatial objects and endpoint loss. +7. `0007-spatial-audio-services.patch` supplies retained IAudioClock/IAudioClock2 + and IAudioStreamVolume services, CoreAudio device-frame/QPC reporting, base + stream availability, and API/lifecycle/invalidation tests. diff --git a/runtime/indie-wine11/source.lock.json b/runtime/indie-wine11/source.lock.json index 74940f9..7b3c948 100644 --- a/runtime/indie-wine11/source.lock.json +++ b/runtime/indie-wine11/source.lock.json @@ -42,7 +42,10 @@ "buildToolchain": { "hostCompiler": "Apple Clang from Xcode 26.6", "peCompiler": "GCC 15.1.0 with MinGW-w64 12.0", - "peArchitectures": ["i386", "x86_64"], + "peArchitectures": [ + "i386", + "x86_64" + ], "wow64Mode": "new WoW64", "sourceDateEpoch": 1768262400, "minimumMacOS": "15.0" @@ -50,7 +53,11 @@ "indiePatches": [ "0001-allow-d3dmetal-build-without-vulkan.patch", "0002-remove-proprietary-compatdb-loader.patch", - "0003-native-winedllpath-prepend.patch" + "0003-native-winedllpath-prepend.patch", + "0004-spatial-audio-com.patch", + "0005-spatial-audio-coreaudio.patch", + "0006-spatial-audio-tests.patch", + "0007-spatial-audio-services.patch" ], "runtimeFeatures": [ "CodeWeavers macOS driver patches present in the published LGPL source", @@ -58,7 +65,9 @@ "new WoW64", "kqueue-backed inotify filesystem notifications", "native WINEDLLPATH_PREPEND support for user-imported D3DMetal", - "SDL2 winebus controller-to-XInput mapping" + "SDL2 winebus controller-to-XInput mapping", + "Windows static/dynamic spatial audio via CoreAudio Spatial Mixer (experimental; device and game validation required)", + "CoreAudio native physical output layout preservation (labels, coordinates and channel order), including 5.1.2 top-middle speakers" ], "licenses": [ "LGPL-2.1-or-later", @@ -67,5 +76,32 @@ "MIT", "Zlib" ], - "closedSourcePayloads": [] + "closedSourcePayloads": [], + "indiePatchSHA256": { + "0001-allow-d3dmetal-build-without-vulkan.patch": "9ffe9c0ab22f9a21f8a5403a7b26fc6bc2b27c2a08d89cb91b4d074db5ceaff8", + "0002-remove-proprietary-compatdb-loader.patch": "f9280f6f4374ce17d3e11f5c91b441c9bfe3588260c67124265b225e0006f7f6", + "0003-native-winedllpath-prepend.patch": "8c48a41c77bd682259b8195437896f8941f70d69aa98c8cfd790c9d54fec7b95", + "0004-spatial-audio-com.patch": "6631c310b1115b71a688047472a68bdc183a28d802fbc24d35a27439c6c7b7bb", + "0005-spatial-audio-coreaudio.patch": "33ad95044b65513e01a744037aa2ff615f0a784bb290560bb2a45a7d5dca28c3", + "0006-spatial-audio-tests.patch": "53f30627488f4d7a9ccea89c74f70a20d85539534098c846c48a45492a5f77da", + "0007-spatial-audio-services.patch": "e002e892bdb30e3b76c8751edcb8f45599076e3b8002bce5755b81535d8e3d52" + }, + "spatialAudioSource": { + "repository": "https://github.com/jungwuk-ryu/switchyard-wine", + "branch": "codex/macos-fex-pro-review-20261005", + "revision": "ba57a08921dfe8f3a4281692b040cd2fa5acd94e", + "commits": [ + "4694d9dff307277abc5f27e68a80941898d0347d", + "33905f4e445eb90abc1615714e9cfbeda2bb4dbf", + "9806392a89eb5176a51f8d2fac68423d3634e322", + "71fd097e6119c1076b67b2b7462edfa4441f2980", + "db0f01e161e4abda59d574ad8ff5a991b0e4b075" + ], + "license": "LGPL-2.1-or-later", + "scope": "Windows Spatial Audio COM, shared Unix transport, CoreAudio renderer and tests; no FEX or translation changes", + "prerequisiteCommits": [ + "e237972495de7a70aef6587f332236292d69fa22", + "d39f7c2e8958c0735d10074985ac81698b8dd023" + ] + } } diff --git a/scripts/apply-wine11-patches.py b/scripts/apply-wine11-patches.py new file mode 100644 index 0000000..e9feee6 --- /dev/null +++ b/scripts/apply-wine11-patches.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Apply only the ordered, hash-locked MGU Wine patch set to a clean source tree.""" +import argparse +import hashlib +import json +from pathlib import Path +import subprocess +import sys + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('source', type=Path) + args = parser.parse_args() + root = Path(__file__).resolve().parent.parent + lock = json.loads((root / 'runtime/indie-wine11/source.lock.json').read_text()) + names = lock['indiePatches'] + hashes = lock['indiePatchSHA256'] + patch_root = root / 'patches/wine11' + if not names or len(names) != len(set(names)): + raise ValueError('Patch manifest is empty or contains duplicates') + if any(Path(name).name != name or not name.endswith('.patch') for name in names): + raise ValueError('Patch manifest must contain plain .patch filenames') + if set(names) != {p.name for p in patch_root.glob('*.patch')} or set(hashes) != set(names): + raise ValueError('Patch directory/hash list does not match source.lock.json') + if not (args.source / 'configure').is_file(): + raise ValueError('Expected a freshly extracted Wine source directory') + # Validate all inputs before the first mutation; fail before an unreviewed + # patch can enter a build through a directory glob. + for name in names: + actual = hashlib.sha256((patch_root / name).read_bytes()).hexdigest() + if actual != hashes[name]: + raise ValueError(f'Patch SHA-256 mismatch: {name}') + for name in names: + print(f'Applying {name}', flush=True) + with (patch_root / name).open('rb') as patch: + subprocess.run(['patch', '--batch', '--forward', '--fuzz=0', + '-d', str(args.source), '-p1'], stdin=patch, check=True) + + +if __name__ == '__main__': + try: + main() + except (ValueError, KeyError, OSError, subprocess.CalledProcessError) as error: + print(f'Wine patch application failed: {error}', file=sys.stderr) + sys.exit(1) diff --git a/scripts/build-app.sh b/scripts/build-app.sh index defbd0c..ae9939d 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -3,7 +3,7 @@ set -euo pipefail project_root=${0:A:h:h} build_configuration=${MAC_GAMING_UNCLE_CONFIGURATION:-${INDIE_CONFIGURATION:-release}} -app_destination="$project_root/dist/Mac Gaming Uncle.app" +app_destination=${MAC_GAMING_UNCLE_APP_DESTINATION:-"$project_root/dist/Mac Gaming Uncle.app"} cd "$project_root" "$project_root/scripts/build-steam-wrapper.sh" diff --git a/scripts/build-indie-wine11.sh b/scripts/build-indie-wine11.sh index 00efdf1..34e6f99 100755 --- a/scripts/build-indie-wine11.sh +++ b/scripts/build-indie-wine11.sh @@ -15,9 +15,13 @@ indie_inotify_url="https://github.com/libinotify-kqueue/libinotify-kqueue/archiv indie_inotify_sha256="120398ff95336d04f3ce7ac820e0490059625976264100dcc9af9d11e992b0ca" indie_sdl_url="https://github.com/libsdl-org/SDL/releases/download/release-2.32.10/SDL2-2.32.10.tar.gz" indie_sdl_sha256="5f5993c530f084535c65a6879e9b26ad441169b3e25d789d83287040a9ca5165" -indie_runtime_version="11.0.2" +indie_runtime_version="11.0.9-services.1" indie_output_dir=${INDIE_WINE_OUTPUT_DIR:-"$indie_root/dist/runtime"} indie_work_root=${INDIE_WINE_BUILD_ROOT:-$(mktemp -d /tmp/indie-wine11.XXXXXX)} +if [[ "$indie_work_root" == *[[:space:]]* ]]; then + print -u2 "上游 Autoconf 构建不支持含空白的构建目录;请将 INDIE_WINE_BUILD_ROOT 设为无空白的绝对路径(例如 /tmp/indie-wine11-build)。输出目录可以包含空格。" + exit 2 +fi indie_source_archive=${INDIE_WINE_SOURCE_ARCHIVE:-"$indie_work_root/crossover-sources-26.3.0.tar.gz"} indie_nettle_archive=${INDIE_NETTLE_SOURCE_ARCHIVE:-"$indie_work_root/nettle-3.10.tar.gz"} indie_inotify_archive=${INDIE_INOTIFY_SOURCE_ARCHIVE:-"$indie_work_root/libinotify-kqueue-20240724.tar.gz"} @@ -38,7 +42,7 @@ indie_stage_parent="$indie_work_root/package" indie_stage="$indie_stage_parent/wine-runtime" indie_archive="$indie_output_dir/indie-wine-$indie_runtime_version-macos-x86_64.tar.xz" -for indie_tool in autoreconf cmake curl make patch shasum tar xcrun; do +for indie_tool in autoreconf cmake curl make patch python3 shasum tar xcrun; do if ! command -v "$indie_tool" >/dev/null 2>&1; then print -u2 "缺少构建工具:$indie_tool" print -u2 "建议安装:brew install cmake bison flex llvm lld" @@ -107,9 +111,7 @@ if [[ ! -f "$indie_wine_source/configure" || ! -f "$indie_freetype_source/CMakeL exit 4 fi -for indie_patch in "$indie_root"/patches/wine11/*.patch(N); do - patch -d "$indie_wine_source" -p1 < "$indie_patch" -done +python3 "$indie_root/scripts/apply-wine11-patches.py" "$indie_wine_source" tar -xf "$indie_nettle_archive" -C "$indie_work_root" tar -xf "$indie_inotify_archive" -C "$indie_work_root" @@ -220,6 +222,7 @@ arch -x86_64 /usr/bin/env \ PKG_CONFIG=/opt/homebrew/bin/pkg-config \ PKG_CONFIG_LIBDIR="$indie_dependency_root/lib/pkgconfig" \ PATH="$indie_build_path" \ + ac_cv_func_pipe2=no \ "$indie_wine_source/configure" \ --prefix="$indie_wine_install" \ --enable-archs=i386,x86_64 \ @@ -279,7 +282,8 @@ for indie_library in ${(k)indie_library_ids}; do done find "$indie_stage/bin" "$indie_stage/lib" -type f -print0 | while IFS= read -r -d '' indie_macho; do if file "$indie_macho" | grep -q "Mach-O"; then - for indie_old_dependency in ${(f)$(otool -L "$indie_macho" | awk -v root="$indie_dependency_root/lib/" 'index($1, root) == 1 { print $1 }')}; do + for indie_old_dependency in "${(@f)$(otool -L "$indie_macho" | awk -v root="$indie_dependency_root/lib/" 'index($1, root) == 1 { print $1 }')}"; do + [[ -n "$indie_old_dependency" ]] || continue install_name_tool -change "$indie_old_dependency" "@rpath/${indie_old_dependency:t}" "$indie_macho" done fi @@ -292,7 +296,11 @@ ditto "$indie_gnutls_source/LICENSE" "$indie_stage/licenses/GnuTLS-License.txt" ditto "$indie_inotify_source/LICENSE" "$indie_stage/licenses/libinotify-kqueue-MIT.txt" ditto "$indie_sdl_source/LICENSE.txt" "$indie_stage/licenses/SDL2-Zlib.txt" ditto "$indie_root/runtime/indie-wine11/source.lock.json" "$indie_stage/source.lock.json" +ditto "$indie_root/patches/wine11" "$indie_stage/source-patches/wine11" +ditto "$indie_root/docs/SPATIAL_AUDIO.md" "$indie_stage/licenses/Spatial-Audio-Provenance.md" print "$indie_runtime_version" > "$indie_stage/runtime-version.txt" +python3 "$indie_root/scripts/record-wine-build.py" "$indie_stage" +python3 "$indie_root/scripts/verify-wine-runtime.py" "$indie_stage" > "$indie_stage/package-audit.json" DYLD_LIBRARY_PATH="$indie_stage/lib" "$indie_stage/bin/wine" --version | grep -q "wine-11.0" # Normalize archive metadata so the same locked sources and toolchain produce diff --git a/scripts/check.sh b/scripts/check.sh index f07e60e..6030f9e 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -3,6 +3,7 @@ set -euo pipefail indie_root=${0:A:h:h} cd "$indie_root" +python3 scripts/test-wine11-patches.py swift test swift build -c release --product MacGamingUncleApp swift build -c release --product macgamingunclectl diff --git a/scripts/fixtures/coreaudio-layout/main.c b/scripts/fixtures/coreaudio-layout/main.c new file mode 100644 index 0000000..99d9345 --- /dev/null +++ b/scripts/fixtures/coreaudio-layout/main.c @@ -0,0 +1,30 @@ +static AudioChannelLayout *reset_layout(void) { + AudioChannelLayout *l=(void*)raw_data;memset(raw_data,0,sizeof(raw_data)); + raw_size=offsetof(AudioChannelLayout,mChannelDescriptions)+8*sizeof(AudioChannelDescription);actual_channels=8; + l->mChannelLayoutTag=kAudioChannelLayoutTag_UseChannelDescriptions;l->mNumberChannelDescriptions=8; + unsigned labels[]={1,2,3,4,5,6,49,51};for(unsigned i=0;i<8;i++)l->mChannelDescriptions[i].mChannelLabel=labels[i];return l; +} +int main(void) { + struct spatial_output_layout out, before;struct coreaudio_stream stream;UInt32 size;AudioChannelLayout *l=reset_layout(); + assert(get_spatial_output_layout("mock",&out,&size)==S_OK);assert(out.layout.mNumberChannelDescriptions==8); + assert(out.layout.mChannelDescriptions[6].mChannelLabel==49 && out.layout.mChannelDescriptions[7].mChannelLabel==51); + assert(configure_native_spatial_dry_output(&stream,&out.layout)==S_OK);assert(stream.spatial_dry_output[0]==0&&stream.spatial_dry_output[1]==1); + l->mChannelDescriptions[0].mChannelLabel=49;l->mChannelDescriptions[6].mChannelLabel=1; + assert(get_spatial_output_layout("mock",&out,&size)==S_OK);assert(configure_native_spatial_dry_output(&stream,&out.layout)==S_OK);assert(stream.spatial_dry_output[0]==6&&stream.spatial_dry_output[1]==1); + before=out;l->mChannelDescriptions[6].mChannelFlags=kAudioChannelFlags_SphericalCoordinates;l->mChannelDescriptions[6].mCoordinates[1]=45; + assert(get_spatial_output_layout("mock",&out,&size)==S_OK);assert(memcmp(&before,&out,size));assert(out.layout.mChannelDescriptions[6].mCoordinates[1]==45); + l=reset_layout();l->mChannelDescriptions[6].mChannelLabel=kAudioChannelLabel_UseCoordinates;l->mChannelDescriptions[6].mChannelFlags=kAudioChannelFlags_SphericalCoordinates;l->mChannelDescriptions[6].mCoordinates[1]=45; + assert(get_spatial_output_layout("mock",&out,&size)==S_OK); + l->mChannelDescriptions[6].mCoordinates[1]=NAN;assert(FAILED(get_spatial_output_layout("mock",&out,&size))); + l=reset_layout();actual_channels=7;assert(FAILED(get_spatial_output_layout("mock",&out,&size))); + l=reset_layout();raw_size--;assert(FAILED(get_spatial_output_layout("mock",&out,&size))); + l=reset_layout();l->mNumberChannelDescriptions=65;assert(FAILED(get_spatial_output_layout("mock",&out,&size))); + l=reset_layout();l->mChannelDescriptions[6].mChannelLabel=kAudioChannelLabel_Discrete_0;assert(FAILED(get_spatial_output_layout("mock",&out,&size))); + l=reset_layout();l->mChannelDescriptions[6].mChannelLabel=kAudioChannelLabel_Unknown;assert(FAILED(get_spatial_output_layout("mock",&out,&size))); + l=reset_layout();l->mChannelLayoutTag=kAudioChannelLayoutTag_MPEG_5_1_A;actual_channels=6;assert(get_spatial_output_layout("mock",&out,&size)==S_OK);assert(out.layout.mNumberChannelDescriptions==6); + l=reset_layout();l->mChannelLayoutTag=kAudioChannelLayoutTag_UseChannelBitmap;l->mChannelBitmap=3;actual_channels=2;assert(get_spatial_output_layout("mock",&out,&size)==S_OK); + l=reset_layout();for(unsigned i=0;i<8;i++)l->mChannelDescriptions[i].mChannelLabel=kAudioChannelLabel_Unknown; + actual_channels=2;fallback_allowed=TRUE;assert(get_spatial_output_layout("mock",&out,&size)==S_OK);assert(out.layout.mNumberChannelDescriptions==2); + actual_channels=8;assert(FAILED(get_spatial_output_layout("mock",&out,&size)));fallback_allowed=FALSE; + puts("Native layout scenarios passed: 5.1.2, reordered dry channels, coordinates/change identity, malformed/count mismatch, unknown/discrete, tag and bitmap expansion.");return 0; +} diff --git a/scripts/fixtures/coreaudio-layout/prefix.c b/scripts/fixtures/coreaudio-layout/prefix.c new file mode 100644 index 0000000..ef797ce --- /dev/null +++ b/scripts/fixtures/coreaudio-layout/prefix.c @@ -0,0 +1,27 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "windef.h" +#include "winbase.h" +#include "wingdi.h" +#include "mmreg.h" +#define AUDCLNT_E_UNSUPPORTED_FORMAT ((HRESULT)0x88890008) +#define AUDCLNT_E_DEVICE_INVALIDATED ((HRESULT)0x88890004) +#define TRACE(...) ((void)0) +struct coreaudio_stream {UINT32 spatial_dry_output[2], spatial_dry_output_count;}; +static AudioDeviceID dev_id_from_device(const char *device) {return 1;} +static BOOL fallback_allowed; +static HRESULT get_device_mix_format(const char *device, WAVEFORMATEXTENSIBLE *format) {if(!fallback_allowed)return AUDCLNT_E_UNSUPPORTED_FORMAT;memset(format,0,sizeof(*format));format->Format.nChannels=2;format->dwChannelMask=3;return S_OK;} +static UInt32 raw_size, actual_channels; +static char raw_data[8192]; +static OSStatus fake_size(AudioObjectID id, const AudioObjectPropertyAddress *addr, UInt32 qsize, const void *q, UInt32 *size) +{*size = addr->mSelector == kAudioDevicePropertyPreferredChannelLayout ? raw_size : sizeof(AudioBufferList); return noErr;} +static OSStatus fake_data(AudioObjectID id, const AudioObjectPropertyAddress *addr, UInt32 qsize, const void *q, UInt32 *size, void *data) +{if(addr->mSelector==kAudioDevicePropertyPreferredChannelLayout)memcpy(data,raw_data,raw_size);else{AudioBufferList *b=data;memset(b,0,sizeof(*b));b->mNumberBuffers=1;b->mBuffers[0].mNumberChannels=actual_channels;}return noErr;} +#define AudioObjectGetPropertyDataSize fake_size +#define AudioObjectGetPropertyData fake_data diff --git a/scripts/record-wine-build.py b/scripts/record-wine-build.py new file mode 100644 index 0000000..059e83d --- /dev/null +++ b/scripts/record-wine-build.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Record the actual host/toolchain independently of the reference source lock.""" +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys + + +def run(*args): + return subprocess.check_output(args, text=True).strip() + + +root = Path(__file__).resolve().parent.parent +payload = Path(sys.argv[1]) +info = { + "schemaVersion": 1, + "repositoryRevision": run("git", "-C", str(root), "rev-parse", "HEAD"), + "trackedDiffSHA256": hashlib.sha256(subprocess.check_output( + ["git", "-C", str(root), "diff", "HEAD", "--", "."])).hexdigest(), + "buildScriptSHA256": {name: hashlib.sha256((root / "scripts" / name).read_bytes()).hexdigest() + for name in ("build-indie-wine11.sh", "apply-wine11-patches.py", + "record-wine-build.py", "verify-wine-runtime.py")}, + "sourceLockSHA256": hashlib.sha256((payload / "source.lock.json").read_bytes()).hexdigest(), + "macOS": run("sw_vers", "-productVersion"), + "macOSBuild": run("sw_vers", "-buildVersion"), + "xcode": run("xcodebuild", "-version"), + "sdk": run("xcrun", "--show-sdk-version"), + "hostCompiler": run("/usr/bin/clang", "--version"), + "peCompilers": {arch: run(f"{arch}-w64-mingw32-gcc", "--version") + for arch in ("i686", "x86_64")}, + "cmake": run("cmake", "--version"), + "deploymentTarget": os.environ.get("MACOSX_DEPLOYMENT_TARGET", "15.0"), + "sourceDateEpoch": os.environ.get("SOURCE_DATE_EPOCH", "1768262400"), + "hostArchitecture": "x86_64", + "peArchitectures": ["i386", "x86_64"], + "configureOverrides": {"ac_cv_func_pipe2": "no"}, + "referenceToolchainReproduction": False, +} +(payload / "build-info.json").write_text(json.dumps(info, indent=2) + "\n") diff --git a/scripts/smoke-wine-runtime.py b/scripts/smoke-wine-runtime.py new file mode 100644 index 0000000..5022d76 --- /dev/null +++ b/scripts/smoke-wine-runtime.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Run packaged Wine probes in a new disposable prefix and retain evidence.""" +import argparse +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import time + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("runtime", type=Path) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--mmdevapi-tests", type=Path, help="directory with i386-windows and x86_64-windows mmdevapi_test.exe") + args = parser.parse_args() + runtime = args.runtime.resolve() + evidence = args.output.resolve() + evidence.mkdir(parents=True, exist_ok=True) + fixtures = Path(__file__).resolve().parent.parent / ".build/windows-fixtures" + results = [] + env = os.environ.copy() + for key in tuple(env): + if key.startswith(("WINE", "SWITCHYARD_SPATIAL_AUDIO_", "DYLD_")): + env.pop(key) + env.update(DYLD_LIBRARY_PATH=str(runtime / "lib"), WINEARCH="wow64", WINEDEBUG="-all", + WINEDLLOVERRIDES="mscoree,mshtml,winemenubuilder.exe=d") + + def run(name, command, timeout=180, controller=False, wine_test=False): + started = time.monotonic() + try: + process = subprocess.run(command, env=env, capture_output=True, timeout=timeout) + log = (process.stdout + process.stderr).decode(errors="replace") + code = process.returncode + except subprocess.TimeoutExpired as error: + log = ((error.stdout or b"") + (error.stderr or b"")).decode(errors="replace") + code = "timeout" + summaries = re.findall(r"[^\n]*tests executed[^\n]*", log) + passed = code == 0 + if wine_test: + passed = passed and bool(summaries) and not re.search(r"\b[1-9]\d* failures?\b", "\n".join(summaries)) + # A skipped spatial test cannot establish rendering support. + if name.endswith("spatialaudio"): + passed = passed and not re.search(r"\b[1-9]\d* skipped\b", "\n".join(summaries)) + state = "passed" if passed else "failed" + if controller and code == 2: + state = "no-controller-connected" + (evidence / f"{name}.log").write_text(log) + item = {"name": name, "exit": code, "status": state, + "seconds": round(time.monotonic() - started, 2), "summaries": summaries} + results.append(item) + (evidence / "results.json").write_text(json.dumps(results, indent=2) + "\n") + print(json.dumps(item), flush=True) + return passed + + with tempfile.TemporaryDirectory(prefix="mgu-packaged-smoke-") as prefix: + env["WINEPREFIX"] = prefix + wine = str(runtime / "bin/wine") + server = str(runtime / "bin/wineserver") + try: + if not run("wineboot", [wine, "wineboot", "--init"]): + return 1 + run("cmd-x64", [wine, "cmd", "/c", "echo MGU_PACKAGED_RUNTIME_OK"]) + run("cmd-x86", [wine, str(Path(prefix) / "drive_c/windows/syswow64/cmd.exe"), "/c", "echo MGU_PACKAGED_RUNTIME_OK"]) + for name in ("indie-smoke-x64", "indie-smoke-x86", "indie-d3d11-fixture"): + run(name, [wine, str(fixtures / f"{name}.exe"), "--smoke"], timeout=60) + run("xinput", [wine, str(fixtures / "indie-xinput-probe.exe")], timeout=30, controller=True) + if args.mmdevapi_tests: + for arch, tests in (("x86_64", ("spatialaudio", "render", "mmdevenum", "propstore")), + ("i386", ("spatialaudio",))): + for test in tests: + run(f"{arch}-{test}", [wine, str(args.mmdevapi_tests.resolve() / f"{arch}-windows/mmdevapi_test.exe"), test], wine_test=True) + finally: + subprocess.run([server, "-k"], env=env, capture_output=True, timeout=15) + subprocess.run([server, "-w"], env=env, capture_output=True, timeout=15) + return 1 if any(item["status"] == "failed" for item in results) else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/test-coreaudio-layout.py b/scripts/test-coreaudio-layout.py new file mode 100644 index 0000000..9342800 --- /dev/null +++ b/scripts/test-coreaudio-layout.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Exercise the patched Wine CoreAudio layout helpers using mocked device data. + +Requires macOS/Xcode and the patched CrossOver Wine source tree. AudioFormat +layout expansion uses Apple's real framework; device properties are fixtures. +""" +import argparse +from pathlib import Path +import subprocess +import tempfile + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('wine_source', type=Path) +args = parser.parse_args() +wine = args.wine_source.resolve() +fixtures = Path(__file__).resolve().parent / 'fixtures' / 'coreaudio-layout' +source = (wine / 'dlls/winecoreaudio.drv/coreaudio.c').read_text() +start = source.index('static AudioChannelLabel wave_speaker_to_channel_label') +end = source.index('static BOOL spatial_transport_speaker_to_coordinates', start) +text = ((fixtures / 'prefix.c').read_text() + + 'struct wave_channel_layout {AudioChannelLayout layout; AudioChannelDescription extra_descriptions[17];};\n' + + source[start:end] + (fixtures / 'main.c').read_text()) +with tempfile.TemporaryDirectory(prefix='mgu-coreaudio-layout-') as directory: + root = Path(directory) + test = root / 'layout-test.c' + test.write_text(text) + executable = root / 'layout-test' + subprocess.run(['xcrun', 'clang', '-D__WINESRC__', '-DWINE_UNIX_LIB', + '-I' + str(wine / 'include'), str(test), + '-framework', 'AudioToolbox', '-framework', 'CoreAudio', + '-o', str(executable)], check=True) + subprocess.run([str(executable)], check=True) diff --git a/scripts/test-wine11-patches.py b/scripts/test-wine11-patches.py new file mode 100644 index 0000000..e85a514 --- /dev/null +++ b/scripts/test-wine11-patches.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Exercise hash/order checks and real patch application without a Wine build.""" +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + + +class PatchApplicationTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='mgu-patch-test-') + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + (self.root / 'scripts').mkdir() + (self.root / 'runtime/indie-wine11').mkdir(parents=True) + (self.root / 'patches/wine11').mkdir(parents=True) + self.source = self.root / 'source' + self.source.mkdir() + (self.source / 'configure').touch() + (self.source / 'value.txt').write_text('before\n') + self.script = self.root / 'scripts/apply-wine11-patches.py' + shutil.copyfile(Path(__file__).with_name('apply-wine11-patches.py'), self.script) + self.patch = self.root / 'patches/wine11/0001.patch' + self.patch.write_text('--- a/value.txt\n+++ b/value.txt\n@@ -1 +1 @@\n-before\n+after\n') + self.lock = {'indiePatches': ['0001.patch'], + 'indiePatchSHA256': {'0001.patch': hashlib.sha256(self.patch.read_bytes()).hexdigest()}} + + def run_apply(self): + (self.root / 'runtime/indie-wine11/source.lock.json').write_text(json.dumps(self.lock)) + return subprocess.run([sys.executable, str(self.script), str(self.source)], + capture_output=True, text=True) + + def assert_rejected_before_mutation(self): + result = self.run_apply() + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertEqual((self.source / 'value.txt').read_text(), 'before\n') + + def test_real_application_and_reapplication_rejected(self): + result = self.run_apply() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((self.source / 'value.txt').read_text(), 'after\n') + self.assertNotEqual(self.run_apply().returncode, 0) + + def test_changed_hash(self): + self.patch.write_text(self.patch.read_text() + '\n') + self.assert_rejected_before_mutation() + + def test_unlisted_patch(self): + self.patch.with_name('0002.patch').write_text('unreviewed') + self.assert_rejected_before_mutation() + + def test_missing_hash(self): + self.lock['indiePatchSHA256'] = {} + self.assert_rejected_before_mutation() + + def test_duplicate(self): + self.lock['indiePatches'].append('0001.patch') + self.assert_rejected_before_mutation() + + def test_path_traversal(self): + self.lock['indiePatches'] = ['../0001.patch'] + self.assert_rejected_before_mutation() + + def test_order_is_manifest_order(self): + second = self.patch.with_name('0002.patch') + second.write_text('--- a/value.txt\n+++ b/value.txt\n@@ -1 +1 @@\n-after\n+final\n') + self.lock['indiePatches'].append(second.name) + self.lock['indiePatchSHA256'][second.name] = hashlib.sha256(second.read_bytes()).hexdigest() + result = self.run_apply() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((self.source / 'value.txt').read_text(), 'final\n') + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/verify-wine-runtime.py b/scripts/verify-wine-runtime.py new file mode 100644 index 0000000..844b4d0 --- /dev/null +++ b/scripts/verify-wine-runtime.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Audit a packaged macOS Wine runtime without touching a user's prefix. + +Dependency resolution follows the application's DYLD_LIBRARY_PATH (runtime/lib) +and loader-relative paths. This is a packaging gate, not a game compatibility test. +""" +import argparse +import hashlib +import json +import os +import re +from pathlib import Path +import subprocess +import struct +import sys + + +def output(*args): + return subprocess.check_output(args, text=True).strip() + + +def audit(root): + errors = [] + required = [ + "bin/wine", "bin/wineserver", "runtime-version.txt", "source.lock.json", + "lib/wine/x86_64-unix/ntdll.so", "lib/wine/x86_64-unix/winecoreaudio.so", + "lib/wine/x86_64-unix/winebus.so", "lib/libfreetype.6.dylib", + "lib/libgnutls.30.dylib", "lib/libgmp.10.dylib", "lib/libnettle.8.dylib", + "lib/libhogweed.6.dylib", "lib/libinotify.0.dylib", "lib/libSDL2-2.0.0.dylib", + ] + for arch in ("i386", "x86_64"): + required.extend(f"lib/wine/{arch}-windows/{name}" for name in + ("ntdll.dll", "mmdevapi.dll", "winecoreaudio.drv", "winebus.sys", "d3d11.dll", "d3d12.dll")) + for name in required: + if not (root / name).is_file(): + errors.append(f"Missing required file: {name}") + elif "-windows/" in name: + data = (root / name).read_bytes() + offset = struct.unpack_from("= 64 else len(data) + expected = 0x014c if "/i386-windows/" in name else 0x8664 + if (data[:2] != b"MZ" or offset + 6 > len(data) or data[offset:offset + 4] != b"PE\0\0" + or struct.unpack_from("