upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 03:41:48 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 03:41:48 -0500
commit8b771908c3c8d7d233e66f39d535a5a7c63047aa (patch)
treea5aa45227ef725edba1f021f7f2e10fcb898a834 /runtime
parentf9792cc56de10067f1bbdb233eaac23cd5b2074f (diff)
parent237deb64ce2b567283f304b7b89a23152e7b60c0 (diff)
Merge main into feat/gdk-lifecycle-window-hook (#769)feat/gdk-lifecycle-window-hook
scripts/build_runtime.ps1 conflicted in the $files list of the build without CMake: main added shims\silent_audio.cpp there (#1598) after this branch had merged main, and this branch adds shims\lifecycle.cpp. Both entries are kept, lifecycle.cpp where this branch had it. The branch's other change in that file (user32.lib on the link line) merged cleanly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt18
-rw-r--r--runtime/README.md1
-rw-r--r--runtime/shims/com_shim.cpp8
-rw-r--r--runtime/shims/d3d12_com.h3
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp59
-rw-r--r--runtime/shims/d3d12_xs_device.cpp28
-rw-r--r--runtime/shims/d3d12_xs_placed_depth.h10
-rw-r--r--runtime/shims/silent_audio.cpp1308
-rw-r--r--runtime/shims/silent_audio.h61
-rw-r--r--runtime/src/title_page_watch.h25
-rw-r--r--runtime/test/d3d12_placed_depth_test.h23
-rw-r--r--runtime/test/d3d12_title_va_test.cpp125
-rw-r--r--runtime/test/kernel_writes_test.cpp55
-rw-r--r--runtime/test/silent_audio_test.cpp728
14 files changed, 2430 insertions, 22 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 981a3ff68..fe90fcd6c 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -197,6 +197,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
197 shims/process.cpp 197 shims/process.cpp
198 shims/lifecycle.cpp 198 shims/lifecycle.cpp
199 shims/com_shim.cpp 199 shims/com_shim.cpp
200 shims/silent_audio.cpp
200 shims/bcrypt_rng.cpp 201 shims/bcrypt_rng.cpp
201 shims/xapu_chad.cpp 202 shims/xapu_chad.cpp
202 shims/dstorage.cpp 203 shims/dstorage.cpp
@@ -473,6 +474,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
473 add_executable(com_shim_test 474 add_executable(com_shim_test
474 test/com_shim_test.cpp 475 test/com_shim_test.cpp
475 shims/com_shim.cpp 476 shims/com_shim.cpp
477 shims/silent_audio.cpp
476 shims/registry.cpp 478 shims/registry.cpp
477 ) 479 )
478 target_include_directories(com_shim_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) 480 target_include_directories(com_shim_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
@@ -480,6 +482,19 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
480 target_compile_options(com_shim_test PRIVATE /W4 /permissive- /utf-8) 482 target_compile_options(com_shim_test PRIVATE /W4 /permissive- /utf-8)
481 target_link_options(com_shim_test PRIVATE /OPT:NOREF) 483 target_link_options(com_shim_test PRIVATE /OPT:NOREF)
482 484
485 # The silent output endpoint (MMDeviceEnumerator through CoCreateInstance): stand-in hosts, a render stream on
486 # its clock, and the CoCreateInstance hook with LEONIDA_AUDIO=silent. No host audio device is opened.
487 add_executable(silent_audio_test
488 test/silent_audio_test.cpp
489 shims/silent_audio.cpp
490 shims/com_shim.cpp
491 shims/registry.cpp
492 )
493 target_include_directories(silent_audio_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
494 target_compile_definitions(silent_audio_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
495 target_compile_options(silent_audio_test PRIVATE /W4 /permissive- /utf-8)
496 target_link_options(silent_audio_test PRIVATE /OPT:NOREF)
497
483 # BCrypt RNG and algorithm provider shims. 498 # BCrypt RNG and algorithm provider shims.
484 add_executable(bcrypt_rng_test 499 add_executable(bcrypt_rng_test
485 test/bcrypt_rng_test.cpp 500 test/bcrypt_rng_test.cpp
@@ -1520,6 +1535,9 @@ if(BUILD_TESTING)
1520 if(WIN32 AND TARGET com_shim_test) 1535 if(WIN32 AND TARGET com_shim_test)
1521 add_test(NAME com_shim COMMAND com_shim_test) 1536 add_test(NAME com_shim COMMAND com_shim_test)
1522 endif() 1537 endif()
1538 if(WIN32 AND TARGET silent_audio_test)
1539 add_test(NAME silent_audio COMMAND silent_audio_test)
1540 endif()
1523 if(WIN32 AND TARGET bcrypt_rng_test) 1541 if(WIN32 AND TARGET bcrypt_rng_test)
1524 add_test(NAME bcrypt_rng COMMAND bcrypt_rng_test) 1542 add_test(NAME bcrypt_rng COMMAND bcrypt_rng_test)
1525 add_test(NAME bcrypt_rng_seeded COMMAND bcrypt_rng_test --seeded) 1543 add_test(NAME bcrypt_rng_seeded COMMAND bcrypt_rng_test --seeded)
diff --git a/runtime/README.md b/runtime/README.md
index fadaa47ef..aa9b2d308 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -358,6 +358,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
358| `LEONIDA_WINDOW` | unset | `WxH` resizes the title's window when the presenter attaches to it. | 358| `LEONIDA_WINDOW` | unset | `WxH` resizes the title's window when the presenter attaches to it. |
359| `LEONIDA_PRESENT_DUMP` | unset | *Diagnostic.* `DIR` or `DIR,N` writes every Nth presented frame (60 by default) as a PNG into `DIR` (`src/present_dump.h`). The files are pictures of the title: keep them out of commits, issues and pull requests. | 359| `LEONIDA_PRESENT_DUMP` | unset | *Diagnostic.* `DIR` or `DIR,N` writes every Nth presented frame (60 by default) as a PNG into `DIR` (`src/present_dump.h`). The files are pictures of the title: keep them out of commits, issues and pull requests. |
360| `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. | 360| `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. |
361| `LEONIDA_AUDIO` | unset | `silent` (any case) makes the title's `MMDeviceEnumerator` answer every render question with the runtime's silent output endpoint, even on a host that has an output (`shims/silent_audio.cpp`, read at each `CoCreateInstance`): no host audio device is opened and every sample is thrown away, for muted test runs. Unset, or any other value, the host's endpoint answers when there is one and the silent endpoint only when the host has none. Capture keeps the host's answer either way. See [docs/runtime_imports.md](../docs/runtime_imports.md#audio-output-off-the-console-wasapi). |
361 362
362The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the 363The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the
363shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own 364shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own
diff --git a/runtime/shims/com_shim.cpp b/runtime/shims/com_shim.cpp
index 55962e215..8156b1917 100644
--- a/runtime/shims/com_shim.cpp
+++ b/runtime/shims/com_shim.cpp
@@ -1,7 +1,8 @@
1// COM lifecycle and helper shims for api-ms-win-core-com-l1-1-0..3.dll. 1// COM lifecycle and helper shims for api-ms-win-core-com-l1-1-0..3.dll.
2// 2//
3// game_scarlett_master.exe imports CoInitializeEx, CoUninitialize, CoCreateInstance, CoCreateGuid, CoTaskMemFree, 3// game_scarlett_master.exe imports CoInitializeEx, CoUninitialize, CoCreateInstance, CoCreateGuid, CoTaskMemFree,
4// PropVariantClear, and StringFromGUID2 through api-ms-win-core-com-l1-1-0.dll. When the host (or a host library) has 4// PropVariantClear, and StringFromGUID2 through api-ms-win-core-com-l1-1-0.dll. CoCreateInstance of the
5// MMDeviceEnumerator goes to silent_audio.cpp, which serves a silent output endpoint when the host has none. When the host (or a host library) has
5// already initialized a thread as STA, a guest call to CoInitializeEx(nullptr, COINIT_MULTITHREADED) fails with 6// already initialized a thread as STA, a guest call to CoInitializeEx(nullptr, COINIT_MULTITHREADED) fails with
6// RPC_E_CHANGED_MODE (0x80010106) and an unbalanced CoUninitialize can tear down host COM early. 7// RPC_E_CHANGED_MODE (0x80010106) and an unbalanced CoUninitialize can tear down host COM early.
7// 8//
@@ -15,6 +16,7 @@
15#include <new> 16#include <new>
16 17
17#include "shims.h" 18#include "shims.h"
19#include "silent_audio.h"
18 20
19namespace rt::com_shim { 21namespace rt::com_shim {
20namespace { 22namespace {
@@ -128,6 +130,10 @@ void WINAPI co_uninitialize() {
128HRESULT WINAPI co_create_instance(REFCLSID rclsid, LPUNKNOWN outer, DWORD cls_context, REFIID riid, LPVOID* ppv) { 130HRESULT WINAPI co_create_instance(REFCLSID rclsid, LPUNKNOWN outer, DWORD cls_context, REFIID riid, LPVOID* ppv) {
129 if (!ppv) return E_POINTER; 131 if (!ppv) return E_POINTER;
130 *ppv = nullptr; 132 *ppv = nullptr;
133 // The audio device enumerator: the host's when it has an output, else (or with LEONIDA_AUDIO=silent) one that
134 // also answers with the silent output endpoint (silent_audio.h).
135 if (!outer && IsEqualCLSID(rclsid, rt::silent_audio::kClsidMMDeviceEnumerator))
136 return rt::silent_audio::create_enumerator(cls_context, riid, ppv);
131 return ::CoCreateInstance(rclsid, outer, cls_context, riid, ppv); 137 return ::CoCreateInstance(rclsid, outer, cls_context, riid, ppv);
132} 138}
133 139
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index 0d76ae44a..c55229a82 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -274,6 +274,9 @@ VkBuffer vulkan_buffer(ID3D12Resource* resource);
274const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device); 274const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device);
275// True when a slot-133 buffer is a shadow copied from the title's pages, false when they were imported. For tests. 275// True when a slot-133 buffer is a shadow copied from the title's pages, false when they were imported. For tests.
276bool title_shadow_buffer(ID3D12Resource* resource); 276bool title_shadow_buffer(ID3D12Resource* resource);
277// Slot-133 imports (VK_EXT_external_memory_host) whose memory `device` holds: an import declined after its memory
278// was allocated is freed before create_buffer_at_host_address returns. For tests.
279std::uint64_t title_host_imports(ID3D12Device* device);
277// VirtualQuery calls made by the title-buffer shadows in their latest refresh. For tests. 280// VirtualQuery calls made by the title-buffer shadows in their latest refresh. For tests.
278std::uint64_t title_shadow_refresh_queries(ID3D12Device* device); 281std::uint64_t title_shadow_refresh_queries(ID3D12Device* device);
279// The trackers behind the title-buffer shadows and title windows (copies whose pages overlap or touch share one). 282// The trackers behind the title-buffer shadows and title windows (copies whose pages overlap or touch share one).
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 12494d201..4a892c21a 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -1936,6 +1936,8 @@ struct DeviceState {
1936 PFN_vkTransitionImageLayoutEXT transition_image_layout = nullptr; 1936 PFN_vkTransitionImageLayoutEXT transition_image_layout = nullptr;
1937 // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded. 1937 // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded.
1938 PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr; 1938 PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr;
1939 // Slot-133 imports whose memory is allocated (create_host_buffer), for title_host_imports.
1940 std::atomic<std::uint64_t> host_imports{0};
1939 1941
1940 // The live shadow buffers of Xbox device slot 133 (Resource::create_shadow_buffer): title-placed buffers whose 1942 // The live shadow buffers of Xbox device slot 133 (Resource::create_shadow_buffer): title-placed buffers whose
1941 // pages the driver would not import. Each is brought up to date from the title's pages before every submission 1943 // pages the driver would not import. Each is brought up to date from the title's pages before every submission
@@ -2450,6 +2452,7 @@ struct DeviceState {
2450 // import 2452 // import
2451 VkBuffer buffer = VK_NULL_HANDLE; 2453 VkBuffer buffer = VK_NULL_HANDLE;
2452 VkDeviceMemory memory = VK_NULL_HANDLE; 2454 VkDeviceMemory memory = VK_NULL_HANDLE;
2455 std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives
2453 std::size_t scan_at = 0; // the next slot the T# scan reads 2456 std::size_t scan_at = 0; // the next slot the T# scan reads
2454 // copy 2457 // copy
2455 bool identity = false; 2458 bool identity = false;
@@ -2664,6 +2667,7 @@ struct DeviceState {
2664 const auto fail = [&] { 2667 const auto fail = [&] {
2665 if (heap.buffer) vk.vkDestroyBuffer(info.device, heap.buffer, nullptr); 2668 if (heap.buffer) vk.vkDestroyBuffer(info.device, heap.buffer, nullptr);
2666 if (heap.memory) vk.vkFreeMemory(info.device, heap.memory, nullptr); 2669 if (heap.memory) vk.vkFreeMemory(info.device, heap.memory, nullptr);
2670 leonida::kernel_writes::release(std::exchange(heap.pin, 0));
2667 heap.buffer = VK_NULL_HANDLE; 2671 heap.buffer = VK_NULL_HANDLE;
2668 heap.memory = VK_NULL_HANDLE; 2672 heap.memory = VK_NULL_HANDLE;
2669 return false; 2673 return false;
@@ -2681,6 +2685,7 @@ struct DeviceState {
2681 import.pHostPointer = const_cast<char*>(pages); 2685 import.pHostPointer = const_cast<char*>(pages);
2682 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; 2686 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import};
2683 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; 2687 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
2688 heap.pin = leonida::kernel_writes::hold(pages, std::size_t(heap.bytes)); // as create_host_buffer's
2684 for (const VkMemoryPropertyFlags want : 2689 for (const VkMemoryPropertyFlags want :
2685 {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), 2690 {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
2686 VkMemoryPropertyFlags(0)}) { 2691 VkMemoryPropertyFlags(0)}) {
@@ -2803,6 +2808,7 @@ struct DeviceState {
2803 context->wait_retire_ticket(context->submitted_retire_ticket()); 2808 context->wait_retire_ticket(context->submitted_retire_ticket());
2804 context->vk.vkDestroyBuffer(info.device, heap->buffer, nullptr); 2809 context->vk.vkDestroyBuffer(info.device, heap->buffer, nullptr);
2805 context->vk.vkFreeMemory(info.device, heap->memory, nullptr); 2810 context->vk.vkFreeMemory(info.device, heap->memory, nullptr);
2811 leonida::kernel_writes::release(std::exchange(heap->pin, 0));
2806 } else { 2812 } else {
2807 arena_release(heap->shader_va, heap->bytes, arena_descriptor_heap); 2813 arena_release(heap->shader_va, heap->bytes, arena_descriptor_heap);
2808 } 2814 }
@@ -4563,7 +4569,11 @@ public:
4563 device_.context->wait_retire_ticket(device_.context->submitted_retire_ticket()); 4569 device_.context->wait_retire_ticket(device_.context->submitted_retire_ticket());
4564 auto& vk = device_.context->vk; 4570 auto& vk = device_.context->vk;
4565 if (buffer_) vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr); 4571 if (buffer_) vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr);
4566 if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); 4572 if (memory_) {
4573 vk.vkFreeMemory(device_.info.device, memory_, nullptr);
4574 device_.host_imports.fetch_sub(1, std::memory_order_relaxed);
4575 }
4576 leonida::kernel_writes::release(std::exchange(host_pin_, 0));
4567 buffer_ = VK_NULL_HANDLE; 4577 buffer_ = VK_NULL_HANDLE;
4568 memory_ = VK_NULL_HANDLE; 4578 memory_ = VK_NULL_HANDLE;
4569 } 4579 }
@@ -4849,21 +4859,43 @@ public:
4849 if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; 4859 if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
4850 device_.share(info); 4860 device_.share(info);
4851 if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; 4861 if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY;
4862 // An import not used is destroyed here, not left to the destructor's deferred queue: there it outlived the
4863 // next submission while the shadow the caller makes instead over the same pages guarded them, and RADV
4864 // rejects every submission once a page under a live import is read-only (the CS is rejected, then
4865 // VK_ERROR_DEVICE_LOST: found and measured by NateWeav, #14). Nothing was submitted with it: the resource is
4866 // registered only on success.
4867 const auto decline = [&](HRESULT hr) {
4868 if (buffer_) vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr);
4869 if (memory_) {
4870 vk.vkFreeMemory(device_.info.device, memory_, nullptr);
4871 device_.host_imports.fetch_sub(1, std::memory_order_relaxed);
4872 }
4873 leonida::kernel_writes::release(std::exchange(host_pin_, 0));
4874 buffer_ = VK_NULL_HANDLE;
4875 memory_ = VK_NULL_HANDLE;
4876 buffer_va_ = gpu_va_ = 0;
4877 return hr;
4878 };
4852 VkMemoryRequirements requirements{}; 4879 VkMemoryRequirements requirements{};
4853 vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); 4880 vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements);
4854 VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; 4881 VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT};
4855 if (device_.get_host_pointer_properties(device_.info.device, 4882 if (device_.get_host_pointer_properties(device_.info.device,
4856 VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, base_address, 4883 VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, base_address,
4857 &host) != VK_SUCCESS) 4884 &host) != VK_SUCCESS)
4858 return E_NOTIMPL; 4885 return decline(E_NOTIMPL);
4859 const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; 4886 const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits;
4860 // An offset off the buffer's own alignment cannot be bound: the fallback answers. 4887 // An offset off the buffer's own alignment cannot be bound: the fallback answers.
4861 if (!types || (offset % requirements.alignment) || requirements.size > bytes - offset) return E_NOTIMPL; 4888 if (!types || (offset % requirements.alignment) || requirements.size > bytes - offset)
4889 return decline(E_NOTIMPL);
4862 VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; 4890 VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT};
4863 import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; 4891 import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
4864 import.pHostPointer = base_address; 4892 import.pHostPointer = base_address;
4865 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; 4893 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import};
4866 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; 4894 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
4895 // The imported pages are pinned before the import and until its memory is freed, so the shadow trackers
4896 // and the geometry watch never make them read-only meanwhile (leonida::kernel_writes::hold). Taken first,
4897 // so no guard lands between the writability check above and the import.
4898 host_pin_ = leonida::kernel_writes::hold(base_address, std::size_t(bytes));
4867 // Host-visible and coherent first, as the caller's pages are; then any type both the import and the 4899 // Host-visible and coherent first, as the caller's pages are; then any type both the import and the
4868 // buffer take. 4900 // buffer take.
4869 for (const VkMemoryPropertyFlags want : 4901 for (const VkMemoryPropertyFlags want :
@@ -4876,15 +4908,18 @@ public:
4876 allocate.allocationSize = bytes; 4908 allocate.allocationSize = bytes;
4877 allocate.memoryTypeIndex = i; 4909 allocate.memoryTypeIndex = i;
4878 std::lock_guard serial(DeviceState::memory_mutex()); 4910 std::lock_guard serial(DeviceState::memory_mutex());
4879 if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) 4911 if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) {
4880 memory_flags_ = device_.memory.memoryTypes[i].propertyFlags; 4912 memory_flags_ = device_.memory.memoryTypes[i].propertyFlags;
4881 else 4913 device_.host_imports.fetch_add(1, std::memory_order_relaxed);
4914 } else {
4882 memory_ = VK_NULL_HANDLE; 4915 memory_ = VK_NULL_HANDLE;
4916 }
4883 } 4917 }
4884 if (memory_) break; 4918 if (memory_) break;
4885 } 4919 }
4886 if (!memory_) return E_OUTOFMEMORY; 4920 if (!memory_) return decline(E_OUTOFMEMORY);
4887 if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, offset) != VK_SUCCESS) return E_OUTOFMEMORY; 4921 if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, offset) != VK_SUCCESS)
4922 return decline(E_OUTOFMEMORY);
4888 if (need_bda && vk.vkGetBufferDeviceAddress) { 4923 if (need_bda && vk.vkGetBufferDeviceAddress) {
4889 VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; 4924 VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
4890 bda.buffer = buffer_; 4925 bda.buffer = buffer_;
@@ -4910,9 +4945,7 @@ public:
4910 address, static_cast<unsigned long long>(desc_.Width), 4945 address, static_cast<unsigned long long>(desc_.Width),
4911 static_cast<unsigned long long>(buffer_va_), 4946 static_cast<unsigned long long>(buffer_va_),
4912 static_cast<unsigned long long>(device_.arena.address)); 4947 static_cast<unsigned long long>(device_.arena.address));
4913 buffer_va_ = 0; 4948 return decline(E_NOTIMPL);
4914 gpu_va_ = 0;
4915 return E_NOTIMPL;
4916 } 4949 }
4917 mapped_ = address; 4950 mapped_ = address;
4918 host_import_ = true; 4951 host_import_ = true;
@@ -6131,6 +6164,7 @@ private:
6131 std::uint64_t buffer_va_ = 0; 6164 std::uint64_t buffer_va_ = 0;
6132 std::uint64_t gpu_va_ = 0; 6165 std::uint64_t gpu_va_ = 0;
6133 bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred 6166 bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred
6167 std::uint64_t host_pin_ = 0; // create_host_buffer: the pages' leonida::kernel_writes pin while memory_ lives
6134 std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows 6168 std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows
6135 bool aliased_ = false; // va_ is in leonida::title_va_aliases(), reached at title_alias_ 6169 bool aliased_ = false; // va_ is in leonida::title_va_aliases(), reached at title_alias_
6136 std::uint64_t title_alias_ = 0; 6170 std::uint64_t title_alias_ = 0;
@@ -15371,6 +15405,11 @@ std::uint64_t title_shadow_refresh_queries(ID3D12Device* device) {
15371 return queries; 15405 return queries;
15372} 15406}
15373 15407
15408std::uint64_t title_host_imports(ID3D12Device* device) {
15409 auto* d = Device::from<Device>(device);
15410 return d ? d->state().host_imports.load(std::memory_order_relaxed) : 0;
15411}
15412
15374std::uint64_t title_shadow_trackers(ID3D12Device* device) { 15413std::uint64_t title_shadow_trackers(ID3D12Device* device) {
15375 auto* d = Device::from<Device>(device); 15414 auto* d = Device::from<Device>(device);
15376 if (!d) return 0; 15415 if (!d) return 0;
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp
index 3bad45d28..60d7c62f3 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -4275,13 +4275,27 @@ HRESULT create_depth_uav_backing(DeviceProxy* self, const D3D12_HEAP_PROPERTIES*
4275HRESULT proxy_create_placed_depth(DeviceProxy* self, UINT64 address, const D3D12_RESOURCE_DESC& desc, 4275HRESULT proxy_create_placed_depth(DeviceProxy* self, UINT64 address, const D3D12_RESOURCE_DESC& desc,
4276 std::uint32_t layout, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) { 4276 std::uint32_t layout, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) {
4277 const auto native = depth_image_desc(desc); 4277 const auto native = depth_image_desc(desc);
4278 if (!self->validate_depth_placement(native, layout, clear)) return E_INVALIDARG; 4278 const bool valid = self->validate_depth_placement(native, layout, clear);
4279 const auto alloc = self->real->GetResourceAllocationInfo(0, 1, &native); 4279 D3D12_RESOURCE_ALLOCATION_INFO alloc{};
4280 const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; 4280 HRESULT hr = E_INVALIDARG;
4281 return self->placed_depth_textures.create(address, native, alloc, clear, desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN, riid, out, [&](ID3D12Resource** backing) { 4281 if (valid) {
4282 return create_depth_uav_backing(self, &heap, D3D12_HEAP_FLAG_NONE, native, D3D12_RESOURCE_STATE_COMMON, 4282 alloc = self->real->GetResourceAllocationInfo(0, 1, &native);
4283 clear, backing); 4283 const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};
4284 }); 4284 hr = self->placed_depth_textures.create(address, native, alloc, clear, desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN, riid, out, [&](ID3D12Resource** backing) {
4285 return create_depth_uav_backing(self, &heap, D3D12_HEAP_FLAG_NONE, native, D3D12_RESOURCE_STATE_COMMON,
4286 clear, backing);
4287 });
4288 }
4289 // A refusal here reaches no trace line, and the title stops on an int3 right after it: log the first few.
4290 static std::atomic<int> refusals{0};
4291 if (FAILED(hr) && refusals.fetch_add(1, std::memory_order_relaxed) < 8)
4292 std::fprintf(stderr,
4293 "[rt] d3d12_xs: slot 133 depth texture refused (hr=0x%08x, %s): format %d %llux%ux%u, Xbox layout "
4294 "0x%x, layout word 0x%x, PC size %llu\n",
4295 static_cast<unsigned>(hr), valid ? "placement" : "description", int(desc.Format),
4296 static_cast<unsigned long long>(desc.Width), unsigned(desc.Height), unsigned(desc.DepthOrArraySize),
4297 unsigned(desc.Layout), layout, static_cast<unsigned long long>(alloc.SizeInBytes));
4298 return hr;
4285} 4299}
4286 4300
4287HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, 4301HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties,
diff --git a/runtime/shims/d3d12_xs_placed_depth.h b/runtime/shims/d3d12_xs_placed_depth.h
index 73bc28eb7..1476851b2 100644
--- a/runtime/shims/d3d12_xs_placed_depth.h
+++ b/runtime/shims/d3d12_xs_placed_depth.h
@@ -79,11 +79,19 @@ public:
79 // an aliasing barrier and reinitialization. The API promises data inheritance only for 79 // an aliasing barrier and reinitialization. The API promises data inheritance only for
80 // identical descriptions and optimized clears. Keep that matching backing alive even 80 // identical descriptions and optimized clears. Keep that matching backing alive even
81 // when another shape is also registered at this address. 81 // when another shape is also registered at this address.
82 // A range's end is the PC allocation's size, which can run past the title's own footprint (on
83 // RADV a large D16 target is sized above the block the title placed it in, and the title's next
84 // block starts inside it). A placement that starts inside another range therefore shares nothing
85 // with it: between two opaque layouts it gets a backing of its own, since D3D12 leaves an alias's
86 // contents undefined until it is reinitialized. Only a non-opaque layout is refused there.
82 const auto limit = ranges_.lower_bound(end); 87 const auto limit = ranges_.lower_bound(end);
83 for (auto it = ranges_.begin(); it != limit; ++it) { 88 for (auto it = ranges_.begin(); it != limit; ++it) {
84 const auto& range = it->second; 89 const auto& range = it->second;
85 if (range.end <= address) continue; 90 if (range.end <= address) continue;
86 if (it->first != address) return E_NOTIMPL; 91 if (it->first != address) {
92 if (!opaque_layout || !range.opaque_layout) return E_NOTIMPL;
93 continue;
94 }
87 const bool same_shape = compatible(desc, range.desc); 95 const bool same_shape = compatible(desc, range.desc);
88 if (range.end == end && same_shape && range.optimized == optimized) { 96 if (range.end == end && same_shape && range.optimized == optimized) {
89 if (auto live = range.backing.lock()) owner = std::move(live); 97 if (auto live = range.backing.lock()) owner = std::move(live);
diff --git a/runtime/shims/silent_audio.cpp b/runtime/shims/silent_audio.cpp
new file mode 100644
index 000000000..0e02186bb
--- /dev/null
+++ b/runtime/shims/silent_audio.cpp
@@ -0,0 +1,1308 @@
1// The silent output endpoint (silent_audio.h): IMMDeviceEnumerator, IMMDevice, IPropertyStore, IAudioClient3 and its
2// services, and ISpatialAudioClient2 with its object render stream, all in-process. Nothing here opens a host audio device; the samples a title writes go to a scratch buffer.
3//
4// No function-local statics or thread_local here: like com_shim.cpp, this runs on threads the title made.
5#include "silent_audio.h"
6
7#include <windows.h>
8#include <objbase.h>
9#include <mmreg.h>
10#include <mmdeviceapi.h>
11#include <audioclient.h>
12#include <propidl.h>
13#include <propsys.h>
14#include <spatialaudioclient.h>
15
16#include <cstdio>
17#include <cstring>
18#include <cwchar>
19#include <new>
20#include <vector>
21
22namespace rt::silent_audio {
23namespace {
24
25constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND); // 0x80070490
26
27// KSDATAFORMAT_SUBTYPE_IEEE_FLOAT and KSDATAFORMAT_SUBTYPE_PCM.
28constexpr GUID kSubtypeFloat{0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
29constexpr GUID kSubtypePcm{0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
30
31// Property keys (functiondiscoverykeys_devpkey.h, mmdeviceapi.h), spelled out so no INITGUID unit is needed.
32constexpr GUID kDeviceFmtid{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}};
33constexpr GUID kInterfaceFmtid{0x026e516e, 0xb814, 0x414b, {0x83, 0xcd, 0x85, 0x6d, 0x6f, 0xef, 0x48, 0x22}};
34constexpr GUID kEngineFmtid{0xf19f064d, 0x082c, 0x4e27, {0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c}};
35constexpr GUID kOemFmtid{0xe4870e26, 0x3cc5, 0x4cd2, {0xba, 0x46, 0xca, 0x0a, 0x9a, 0x70, 0xed, 0x04}};
36constexpr GUID kEndpointFmtid{0x1da5d803, 0xd492, 0x4edd, {0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e}};
37constexpr PROPERTYKEY kKeyFriendlyName{kDeviceFmtid, 14}; // PKEY_Device_FriendlyName
38constexpr PROPERTYKEY kKeyDeviceDesc{kDeviceFmtid, 2}; // PKEY_Device_DeviceDesc
39constexpr PROPERTYKEY kKeyInterfaceName{kInterfaceFmtid, 2}; // PKEY_DeviceInterface_FriendlyName
40constexpr PROPERTYKEY kKeyDeviceFormat{kEngineFmtid, 0}; // PKEY_AudioEngine_DeviceFormat
41constexpr PROPERTYKEY kKeyOemFormat{kOemFmtid, 3}; // PKEY_AudioEngine_OEMFormat
42constexpr PROPERTYKEY kKeyFormFactor{kEndpointFmtid, 0}; // PKEY_AudioEndpoint_FormFactor
43constexpr PROPERTYKEY kKeyPhysicalSpeakers{kEndpointFmtid, 3}; // PKEY_AudioEndpoint_PhysicalSpeakers
44constexpr PROPERTYKEY kKeyEndpointGuid{kEndpointFmtid, 4}; // PKEY_AudioEndpoint_GUID
45constexpr PROPERTYKEY kKeys[] = {kKeyFriendlyName, kKeyDeviceDesc, kKeyInterfaceName, kKeyDeviceFormat,
46 kKeyOemFormat, kKeyFormFactor, kKeyPhysicalSpeakers, kKeyEndpointGuid};
47constexpr uint32_t kFormFactorSpeakers = 1;
48constexpr wchar_t kEndpointGuid[] = L"{5a4c2a5e-1e0d-4c1b-9a51-6c656f6e6964}";
49
50constexpr uint32_t kMaxChannels = 32;
51
52LONG g_served = 0;
53LONG g_logged = 0;
54SRWLOCK g_iid_lock = SRWLOCK_INIT;
55GUID g_iids_logged[16]{};
56uint32_t g_iid_count = 0;
57
58bool same_key(const PROPERTYKEY& a, const PROPERTYKEY& b) {
59 return a.pid == b.pid && IsEqualGUID(a.fmtid, b.fmtid);
60}
61
62// One [rt] line per interface the silent endpoint does not have.
63void log_missing_iid_once(const char* where, REFIID riid) {
64 AcquireSRWLockExclusive(&g_iid_lock);
65 bool seen = false;
66 for (uint32_t i = 0; i < g_iid_count; ++i) seen = seen || IsEqualGUID(g_iids_logged[i], riid);
67 if (!seen && g_iid_count < 16) g_iids_logged[g_iid_count++] = riid;
68 ReleaseSRWLockExclusive(&g_iid_lock);
69 if (seen) return;
70 wchar_t text[64]{};
71 StringFromGUID2(riid, text, 64);
72 std::fprintf(stderr, "[rt] audio: the silent output endpoint has no %ls (%s); E_NOINTERFACE\n", text, where);
73}
74
75void note_served(const char* reason) {
76 InterlockedIncrement(&g_served);
77 if (InterlockedExchange(&g_logged, 1) == 0) {
78 std::fprintf(stderr,
79 "[rt] audio: serving the silent output endpoint (%s): 48 kHz float 7.1, every sample discarded, "
80 "no host audio device opened\n",
81 reason);
82 }
83}
84
85void mix_format(WAVEFORMATEXTENSIBLE* f) {
86 std::memset(f, 0, sizeof *f);
87 f->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
88 f->Format.nChannels = kChannels;
89 f->Format.nSamplesPerSec = kSampleRate;
90 f->Format.wBitsPerSample = 32;
91 f->Format.nBlockAlign = static_cast<WORD>(kChannels * 4);
92 f->Format.nAvgBytesPerSec = kSampleRate * kChannels * 4;
93 f->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
94 f->Samples.wValidBitsPerSample = 32;
95 f->dwChannelMask = kChannelMask;
96 f->SubFormat = kSubtypeFloat;
97}
98
99WAVEFORMATEX* alloc_mix_format() {
100 auto* f = static_cast<WAVEFORMATEXTENSIBLE*>(CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE)));
101 if (f) mix_format(f);
102 return reinterpret_cast<WAVEFORMATEX*>(f);
103}
104
105bool is_float(const WAVEFORMATEX* f) {
106 if (f->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) return true;
107 return f->wFormatTag == WAVE_FORMAT_EXTENSIBLE && f->cbSize >= 22 &&
108 IsEqualGUID(reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(f)->SubFormat, kSubtypeFloat);
109}
110
111// A format a shared-mode stream could carry: PCM or float, 1..32 channels, 8..384 kHz, a consistent block.
112bool valid_format(const WAVEFORMATEX* f) {
113 if (f->nChannels == 0 || f->nChannels > kMaxChannels) return false;
114 if (f->nSamplesPerSec < 8000 || f->nSamplesPerSec > 384000) return false;
115 if (f->wBitsPerSample == 0 || f->wBitsPerSample % 8 != 0 || f->wBitsPerSample > 64) return false;
116 if (f->nBlockAlign != f->nChannels * (f->wBitsPerSample / 8)) return false;
117 if (f->wFormatTag == WAVE_FORMAT_PCM || f->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) return true;
118 if (f->wFormatTag != WAVE_FORMAT_EXTENSIBLE || f->cbSize < 22) return false;
119 const GUID& sub = reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(f)->SubFormat;
120 return IsEqualGUID(sub, kSubtypeFloat) || IsEqualGUID(sub, kSubtypePcm);
121}
122
123bool is_mix_format(const WAVEFORMATEX* f) {
124 return f->nSamplesPerSec == kSampleRate && f->nChannels == kChannels && f->wBitsPerSample == 32 && is_float(f);
125}
126
127int64_t qpc_now() {
128 LARGE_INTEGER t;
129 QueryPerformanceCounter(&t);
130 return t.QuadPart;
131}
132
133int64_t qpc_frequency() {
134 LARGE_INTEGER f;
135 QueryPerformanceFrequency(&f);
136 return f.QuadPart;
137}
138
139wchar_t* co_task_string(const wchar_t* s) {
140 const size_t n = std::wcslen(s) + 1;
141 auto* out = static_cast<wchar_t*>(CoTaskMemAlloc(n * sizeof(wchar_t)));
142 if (out) std::wmemcpy(out, s, n);
143 return out;
144}
145
146// IUnknown for an object with one interface.
147template <class Iface>
148class Unknown : public Iface {
149public:
150 ULONG STDMETHODCALLTYPE AddRef() override { return static_cast<ULONG>(InterlockedIncrement(&refs_)); }
151 ULONG STDMETHODCALLTYPE Release() override {
152 const LONG n = InterlockedDecrement(&refs_);
153 if (n == 0) delete this;
154 return static_cast<ULONG>(n);
155 }
156 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
157 if (!ppv) return E_POINTER;
158 *ppv = nullptr;
159 if (!IsEqualIID(riid, __uuidof(IUnknown)) && !answers(riid)) return E_NOINTERFACE;
160 *ppv = static_cast<Iface*>(this);
161 AddRef();
162 return S_OK;
163 }
164
165protected:
166 virtual ~Unknown() = default;
167 virtual bool answers(REFIID riid) const { return IsEqualIID(riid, __uuidof(Iface)); }
168
169private:
170 LONG refs_ = 1;
171};
172
173// Calls `tick(context)` every period on its own thread, on a fixed schedule so a late wake-up does not push the
174// next ones back, until stop() (or destruction).
175class PeriodicThread {
176public:
177 using Tick = void (*)(void*);
178 ~PeriodicThread() { stop(); }
179 bool start(int64_t period_hns, Tick tick, void* context) {
180 if (thread_) return true;
181 period_hns_ = period_hns;
182 tick_ = tick;
183 context_ = context;
184 stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
185 thread_ = stop_ ? CreateThread(nullptr, 64 * 1024, &PeriodicThread::run, this, 0, nullptr) : nullptr;
186 return thread_ != nullptr;
187 }
188 void stop() {
189 if (thread_) {
190 SetEvent(stop_);
191 WaitForSingleObject(thread_, INFINITE);
192 CloseHandle(thread_);
193 thread_ = nullptr;
194 }
195 if (stop_) CloseHandle(stop_);
196 stop_ = nullptr;
197 }
198
199private:
200 static DWORD WINAPI run(void* self) {
201 auto* t = static_cast<PeriodicThread*>(self);
202 const DWORD period_ms = static_cast<DWORD>((t->period_hns_ + 9999) / 10000);
203 const int64_t f = qpc_frequency();
204 const int64_t step = t->period_hns_ * f / 10000000;
205 int64_t next = qpc_now() + step;
206 for (;;) {
207 const int64_t now = qpc_now();
208 DWORD wait = 0;
209 if (next > now) {
210 wait = static_cast<DWORD>((next - now) * 1000 / f);
211 if (wait > period_ms) wait = period_ms;
212 }
213 if (WaitForSingleObject(t->stop_, wait) != WAIT_TIMEOUT) break;
214 if (qpc_now() < next) continue;
215 next += step;
216 if (next < qpc_now()) next = qpc_now() + step;
217 t->tick_(t->context_);
218 }
219 return 0;
220 }
221
222 int64_t period_hns_ = kDefaultPeriodHns;
223 Tick tick_ = nullptr;
224 void* context_ = nullptr;
225 HANDLE stop_ = nullptr;
226 HANDLE thread_ = nullptr;
227};
228
229// ---- IAudioClient3 --------------------------------------------------------------------------------------------
230
231class AudioClient final : public Unknown<IAudioClient3> {
232public:
233 // IAudioClient
234 HRESULT STDMETHODCALLTYPE Initialize(AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME buffer_hns,
235 REFERENCE_TIME, const WAVEFORMATEX* format, LPCGUID) override {
236 return init(mode, flags, buffer_hns, 0, format);
237 }
238 HRESULT STDMETHODCALLTYPE GetBufferSize(UINT32* frames) override {
239 if (!frames) return E_POINTER;
240 Lock l(lock_);
241 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
242 *frames = buffer_frames_;
243 return S_OK;
244 }
245 HRESULT STDMETHODCALLTYPE GetStreamLatency(REFERENCE_TIME* latency) override {
246 if (!latency) return E_POINTER;
247 Lock l(lock_);
248 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
249 *latency = kDefaultPeriodHns;
250 return S_OK;
251 }
252 HRESULT STDMETHODCALLTYPE GetCurrentPadding(UINT32* padding) override {
253 if (!padding) return E_POINTER;
254 Lock l(lock_);
255 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
256 advance(qpc_now());
257 *padding = static_cast<UINT32>(written_ - played_);
258 return S_OK;
259 }
260 HRESULT STDMETHODCALLTYPE IsFormatSupported(AUDCLNT_SHAREMODE mode, const WAVEFORMATEX* format,
261 WAVEFORMATEX** closest) override {
262 if (closest) *closest = nullptr;
263 if (!format) return E_POINTER;
264 if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE) return AUDCLNT_E_UNSUPPORTED_FORMAT;
265 if (mode != AUDCLNT_SHAREMODE_SHARED) return E_INVALIDARG;
266 if (!closest) return E_POINTER;
267 if (!valid_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT;
268 if (is_mix_format(format)) return S_OK;
269 *closest = alloc_mix_format();
270 return *closest ? S_FALSE : E_OUTOFMEMORY;
271 }
272 HRESULT STDMETHODCALLTYPE GetMixFormat(WAVEFORMATEX** format) override {
273 if (!format) return E_POINTER;
274 *format = alloc_mix_format();
275 return *format ? S_OK : E_OUTOFMEMORY;
276 }
277 HRESULT STDMETHODCALLTYPE GetDevicePeriod(REFERENCE_TIME* default_period, REFERENCE_TIME* minimum) override {
278 if (!default_period && !minimum) return E_POINTER;
279 if (default_period) *default_period = kDefaultPeriodHns;
280 if (minimum) *minimum = kMinimumPeriodHns;
281 return S_OK;
282 }
283 HRESULT STDMETHODCALLTYPE Start() override {
284 HANDLE signal = nullptr;
285 {
286 Lock l(lock_);
287 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
288 if (running_) return AUDCLNT_E_NOT_STOPPED;
289 if (event_mode_ && !event_) return AUDCLNT_E_EVENTHANDLE_NOT_SET;
290 anchor_qpc_ = qpc_now();
291 played_at_anchor_ = played_;
292 running_ = true;
293 signal = event_;
294 }
295 if (signal) SetEvent(signal);
296 return S_OK;
297 }
298 HRESULT STDMETHODCALLTYPE Stop() override {
299 Lock l(lock_);
300 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
301 if (!running_) return S_FALSE;
302 advance(qpc_now());
303 running_ = false;
304 return S_OK;
305 }
306 HRESULT STDMETHODCALLTYPE Reset() override {
307 Lock l(lock_);
308 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
309 if (running_) return AUDCLNT_E_NOT_STOPPED;
310 if (pending_) return AUDCLNT_E_BUFFER_OPERATION_PENDING;
311 if (written_ == 0 && played_ == 0) return S_FALSE;
312 written_ = played_ = played_at_anchor_ = 0;
313 return S_OK;
314 }
315 HRESULT STDMETHODCALLTYPE SetEventHandle(HANDLE event) override {
316 if (!event || event == INVALID_HANDLE_VALUE) return E_INVALIDARG;
317 Lock l(lock_);
318 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
319 if (!event_mode_) return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
320 event_ = event;
321 return S_OK;
322 }
323 HRESULT STDMETHODCALLTYPE GetService(REFIID riid, void** ppv) override;
324
325 // IAudioClient2
326 HRESULT STDMETHODCALLTYPE IsOffloadCapable(AUDIO_STREAM_CATEGORY, BOOL* capable) override {
327 if (!capable) return E_POINTER;
328 *capable = FALSE;
329 return S_OK;
330 }
331 HRESULT STDMETHODCALLTYPE SetClientProperties(const AudioClientProperties* properties) override {
332 if (!properties) return E_POINTER;
333 Lock l(lock_);
334 return initialized_ ? AUDCLNT_E_ALREADY_INITIALIZED : S_OK;
335 }
336 HRESULT STDMETHODCALLTYPE GetBufferSizeLimits(const WAVEFORMATEX* format, BOOL, REFERENCE_TIME* min_hns,
337 REFERENCE_TIME* max_hns) override {
338 if (!format || !min_hns || !max_hns) return E_POINTER;
339 if (!valid_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT;
340 *min_hns = kDefaultPeriodHns;
341 *max_hns = 20000000; // 2 s
342 return S_OK;
343 }
344
345 // IAudioClient3: one engine period only, 10 ms.
346 HRESULT STDMETHODCALLTYPE GetSharedModeEnginePeriod(const WAVEFORMATEX* format, UINT32* default_frames,
347 UINT32* fundamental, UINT32* min_frames,
348 UINT32* max_frames) override {
349 if (!format || !default_frames || !fundamental || !min_frames || !max_frames) return E_POINTER;
350 if (!valid_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT;
351 const UINT32 period = static_cast<UINT32>(format->nSamplesPerSec / 100);
352 *default_frames = *fundamental = *min_frames = *max_frames = period;
353 return S_OK;
354 }
355 HRESULT STDMETHODCALLTYPE GetCurrentSharedModeEnginePeriod(WAVEFORMATEX** format, UINT32* frames) override {
356 if (!format || !frames) return E_POINTER;
357 *format = alloc_mix_format();
358 if (!*format) return E_OUTOFMEMORY;
359 *frames = kSampleRate / 100;
360 return S_OK;
361 }
362 HRESULT STDMETHODCALLTYPE InitializeSharedAudioStream(DWORD flags, UINT32 period_frames,
363 const WAVEFORMATEX* format, LPCGUID) override {
364 if (!format) return E_POINTER;
365 const REFERENCE_TIME hns = format->nSamplesPerSec
366 ? static_cast<REFERENCE_TIME>(period_frames) * 10000000 / format->nSamplesPerSec
367 : 0;
368 return init(AUDCLNT_SHAREMODE_SHARED, flags, 0, hns, format);
369 }
370
371 // For the services.
372 HRESULT get_buffer(UINT32 frames, BYTE** data) {
373 if (!data) return E_POINTER;
374 *data = nullptr;
375 Lock l(lock_);
376 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
377 if (pending_) return AUDCLNT_E_OUT_OF_ORDER;
378 advance(qpc_now());
379 const uint64_t padding = written_ - played_;
380 if (frames > buffer_frames_ - padding) return AUDCLNT_E_BUFFER_TOO_LARGE;
381 pending_ = true;
382 pending_frames_ = frames;
383 *data = frames ? scratch_.data() : nullptr;
384 return S_OK;
385 }
386 HRESULT release_buffer(UINT32 frames) {
387 Lock l(lock_);
388 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
389 if (!pending_) return frames ? AUDCLNT_E_OUT_OF_ORDER : S_OK;
390 if (frames > pending_frames_) return AUDCLNT_E_INVALID_SIZE;
391 // A write after the stream ran dry plays from now on (advance re-anchors), as a device fed silence in the gap.
392 advance(qpc_now());
393 written_ += frames;
394 pending_ = false;
395 pending_frames_ = 0;
396 return S_OK;
397 }
398 void position(UINT64* frames, UINT64* qpc_hns) {
399 Lock l(lock_);
400 const int64_t now = qpc_now();
401 advance(now);
402 *frames = played_;
403 if (qpc_hns) {
404 const int64_t f = qpc_frequency();
405 *qpc_hns = static_cast<UINT64>((now / f) * 10000000 + (now % f) * 10000000 / f);
406 }
407 }
408 uint32_t rate() const { return rate_; }
409 uint32_t channels() const { return channels_; }
410 float volume(uint32_t i) {
411 Lock l(lock_);
412 return i < kMaxChannels ? channel_volume_[i] : 0.0f;
413 }
414 void set_volume(uint32_t i, float v) {
415 Lock l(lock_);
416 if (i < kMaxChannels) channel_volume_[i] = v;
417 }
418 float master_ = 1.0f;
419 BOOL mute_ = FALSE;
420
421private:
422 struct Lock {
423 explicit Lock(SRWLOCK& s) : s_(s) { AcquireSRWLockExclusive(&s_); }
424 ~Lock() { ReleaseSRWLockExclusive(&s_); }
425 SRWLOCK& s_;
426 };
427
428 ~AudioClient() override { clock_.stop(); }
429
430 bool answers(REFIID riid) const override {
431 return IsEqualIID(riid, __uuidof(IAudioClient)) || IsEqualIID(riid, __uuidof(IAudioClient2)) ||
432 IsEqualIID(riid, __uuidof(IAudioClient3));
433 }
434
435 HRESULT init(AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME buffer_hns, REFERENCE_TIME period_hns,
436 const WAVEFORMATEX* format) {
437 if (!format) return E_POINTER;
438 if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE) return AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED;
439 if (mode != AUDCLNT_SHAREMODE_SHARED) return E_INVALIDARG;
440 if (flags & AUDCLNT_STREAMFLAGS_LOOPBACK) return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
441 // Any PCM or float format is taken, not only the mix format: the samples are thrown away, so there is
442 // nothing to convert, and a title never fails here for asking without AUTOCONVERTPCM.
443 if (!valid_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT;
444 Lock l(lock_);
445 if (initialized_) return AUDCLNT_E_ALREADY_INITIALIZED;
446 rate_ = format->nSamplesPerSec;
447 channels_ = format->nChannels;
448 block_ = format->nBlockAlign;
449 period_hns_ = period_hns > 0 ? period_hns : kDefaultPeriodHns;
450 const REFERENCE_TIME hns = buffer_hns > 2 * period_hns_ ? buffer_hns : 2 * period_hns_;
451 buffer_frames_ = static_cast<uint32_t>((hns * rate_ + 9999999) / 10000000);
452 scratch_.assign(static_cast<size_t>(buffer_frames_) * block_, 0);
453 for (float& v : channel_volume_) v = 1.0f;
454 event_mode_ = (flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) != 0;
455 if (event_mode_ && !clock_.start(period_hns_, &AudioClient::tick, this)) return E_OUTOFMEMORY;
456 initialized_ = true;
457 if (InterlockedExchange(&g_stream_logged, 1) == 0) {
458 std::fprintf(stderr, "[rt] audio: silent stream: %u ch, %u Hz, %u-byte frames, %u-frame buffer, %s\n",
459 channels_, rate_, block_, buffer_frames_, event_mode_ ? "event-driven" : "polled");
460 }
461 return S_OK;
462 }
463
464 // Frames the device has consumed since Start, at the stream's rate, clamped to what was written.
465 void advance(int64_t now) {
466 if (!running_) return;
467 const int64_t f = qpc_frequency();
468 const int64_t elapsed = now > anchor_qpc_ ? now - anchor_qpc_ : 0;
469 const uint64_t frames = static_cast<uint64_t>((elapsed / f) * rate_ + (elapsed % f) * rate_ / f);
470 const uint64_t candidate = played_at_anchor_ + frames;
471 if (candidate >= written_) {
472 // Ran dry: the device plays silence until more is written.
473 played_ = written_;
474 anchor_qpc_ = now;
475 played_at_anchor_ = written_;
476 } else {
477 played_ = candidate;
478 }
479 }
480
481 static void tick(void* self) {
482 auto* c = static_cast<AudioClient*>(self);
483 HANDLE signal = nullptr;
484 {
485 Lock l(c->lock_);
486 if (!c->running_) return;
487 c->advance(qpc_now());
488 signal = c->event_;
489 }
490 if (signal) SetEvent(signal);
491 }
492
493 static inline LONG g_stream_logged = 0;
494
495 SRWLOCK lock_ = SRWLOCK_INIT;
496 bool initialized_ = false;
497 bool event_mode_ = false;
498 bool running_ = false;
499 bool pending_ = false;
500 uint32_t pending_frames_ = 0;
501 uint32_t rate_ = kSampleRate;
502 uint32_t channels_ = kChannels;
503 uint32_t block_ = kChannels * 4;
504 uint32_t buffer_frames_ = 0;
505 REFERENCE_TIME period_hns_ = kDefaultPeriodHns;
506 std::vector<BYTE> scratch_;
507 HANDLE event_ = nullptr; // the title's; not owned
508 PeriodicThread clock_;
509 uint64_t written_ = 0;
510 uint64_t played_ = 0;
511 uint64_t played_at_anchor_ = 0;
512 int64_t anchor_qpc_ = 0;
513 float channel_volume_[kMaxChannels]{};
514};
515
516// The services hold their client.
517template <class Iface>
518class Service : public Unknown<Iface> {
519public:
520 explicit Service(AudioClient* client) : client_(client) { client_->AddRef(); }
521
522protected:
523 ~Service() override { client_->Release(); }
524 AudioClient* client_;
525};
526
527class RenderClient final : public Service<IAudioRenderClient> {
528public:
529 using Service::Service;
530 HRESULT STDMETHODCALLTYPE GetBuffer(UINT32 frames, BYTE** data) override { return client_->get_buffer(frames, data); }
531 HRESULT STDMETHODCALLTYPE ReleaseBuffer(UINT32 frames, DWORD) override { return client_->release_buffer(frames); }
532};
533
534class Clock final : public Service<IAudioClock> {
535public:
536 using Service::Service;
537 HRESULT STDMETHODCALLTYPE GetFrequency(UINT64* frequency) override {
538 if (!frequency) return E_POINTER;
539 *frequency = client_->rate(); // the position counts frames
540 return S_OK;
541 }
542 HRESULT STDMETHODCALLTYPE GetPosition(UINT64* position, UINT64* qpc_hns) override {
543 if (!position) return E_POINTER;
544 client_->position(position, qpc_hns);
545 return S_OK;
546 }
547 HRESULT STDMETHODCALLTYPE GetCharacteristics(DWORD* characteristics) override {
548 if (!characteristics) return E_POINTER;
549 *characteristics = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
550 return S_OK;
551 }
552};
553
554class SimpleVolume final : public Service<ISimpleAudioVolume> {
555public:
556 using Service::Service;
557 HRESULT STDMETHODCALLTYPE SetMasterVolume(float level, LPCGUID) override {
558 if (level < 0.0f || level > 1.0f) return E_INVALIDARG;
559 client_->master_ = level;
560 return S_OK;
561 }
562 HRESULT STDMETHODCALLTYPE GetMasterVolume(float* level) override {
563 if (!level) return E_POINTER;
564 *level = client_->master_;
565 return S_OK;
566 }
567 HRESULT STDMETHODCALLTYPE SetMute(BOOL mute, LPCGUID) override {
568 client_->mute_ = mute;
569 return S_OK;
570 }
571 HRESULT STDMETHODCALLTYPE GetMute(BOOL* mute) override {
572 if (!mute) return E_POINTER;
573 *mute = client_->mute_;
574 return S_OK;
575 }
576};
577
578class StreamVolume final : public Service<IAudioStreamVolume> {
579public:
580 using Service::Service;
581 HRESULT STDMETHODCALLTYPE GetChannelCount(UINT32* count) override {
582 if (!count) return E_POINTER;
583 *count = client_->channels();
584 return S_OK;
585 }
586 HRESULT STDMETHODCALLTYPE SetChannelVolume(UINT32 index, const float level) override {
587 if (index >= client_->channels() || level < 0.0f || level > 1.0f) return E_INVALIDARG;
588 client_->set_volume(index, level);
589 return S_OK;
590 }
591 HRESULT STDMETHODCALLTYPE GetChannelVolume(UINT32 index, float* level) override {
592 if (!level) return E_POINTER;
593 if (index >= client_->channels()) return E_INVALIDARG;
594 *level = client_->volume(index);
595 return S_OK;
596 }
597 HRESULT STDMETHODCALLTYPE SetAllVolumes(UINT32 count, const float* levels) override {
598 if (!levels) return E_POINTER;
599 if (count != client_->channels()) return E_INVALIDARG;
600 for (UINT32 i = 0; i < count; ++i) {
601 if (levels[i] < 0.0f || levels[i] > 1.0f) return E_INVALIDARG;
602 }
603 for (UINT32 i = 0; i < count; ++i) client_->set_volume(i, levels[i]);
604 return S_OK;
605 }
606 HRESULT STDMETHODCALLTYPE GetAllVolumes(UINT32 count, float* levels) override {
607 if (!levels) return E_POINTER;
608 if (count != client_->channels()) return E_INVALIDARG;
609 for (UINT32 i = 0; i < count; ++i) levels[i] = client_->volume(i);
610 return S_OK;
611 }
612};
613
614HRESULT AudioClient::GetService(REFIID riid, void** ppv) {
615 if (!ppv) return E_POINTER;
616 *ppv = nullptr;
617 {
618 Lock l(lock_);
619 if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED;
620 }
621 IUnknown* made = nullptr;
622 if (IsEqualIID(riid, __uuidof(IAudioRenderClient))) made = new (std::nothrow) RenderClient(this);
623 else if (IsEqualIID(riid, __uuidof(IAudioClock))) made = new (std::nothrow) Clock(this);
624 else if (IsEqualIID(riid, __uuidof(ISimpleAudioVolume))) made = new (std::nothrow) SimpleVolume(this);
625 else if (IsEqualIID(riid, __uuidof(IAudioStreamVolume))) made = new (std::nothrow) StreamVolume(this);
626 else {
627 log_missing_iid_once("IAudioClient::GetService", riid);
628 return E_NOINTERFACE;
629 }
630 if (!made) return E_OUTOFMEMORY;
631 const HRESULT hr = made->QueryInterface(riid, ppv);
632 made->Release();
633 return hr;
634}
635
636// ---- ISpatialAudioClient2 -------------------------------------------------------------------------------------
637//
638// A spatial endpoint with a 7.1 bed (the static objects of the mix format) and no dynamic objects, as an endpoint
639// with no spatial sound format (Windows Sonic, Dolby Atmos) turned on. Objects are mono 48 kHz float; one pass is
640// 10 ms (480 frames), and the stream's event is signalled every pass while it runs.
641
642constexpr uint32_t kBedMask = AudioObjectType_FrontLeft | AudioObjectType_FrontRight | AudioObjectType_FrontCenter |
643 AudioObjectType_LowFrequency | AudioObjectType_SideLeft | AudioObjectType_SideRight |
644 AudioObjectType_BackLeft | AudioObjectType_BackRight;
645constexpr uint32_t kStaticTypes = 0xFFFFE; // FrontLeft .. StereoRight
646constexpr uint32_t kObjectFrames = kSampleRate / 100;
647
648void object_format(WAVEFORMATEX* f) {
649 *f = WAVEFORMATEX{WAVE_FORMAT_IEEE_FLOAT, 1, kSampleRate, kSampleRate * 4, 4, 32, 0};
650}
651
652bool is_object_format(const WAVEFORMATEX* f) {
653 return f && f->nChannels == 1 && f->nSamplesPerSec == kSampleRate && f->wBitsPerSample == 32 &&
654 f->nBlockAlign == 4 && is_float(f);
655}
656
657bool one_type(uint32_t t) { return t != 0 && (t & (t - 1)) == 0; }
658
659class FormatEnumerator final : public Unknown<IAudioFormatEnumerator> {
660public:
661 FormatEnumerator() { object_format(&format_); }
662 HRESULT STDMETHODCALLTYPE GetCount(UINT32* count) override {
663 if (!count) return E_POINTER;
664 *count = 1;
665 return S_OK;
666 }
667 HRESULT STDMETHODCALLTYPE GetFormat(UINT32 index, WAVEFORMATEX** format) override {
668 if (!format) return E_POINTER;
669 *format = nullptr;
670 if (index != 0) return E_INVALIDARG;
671 *format = &format_; // owned by the enumerator, as the system's is
672 return S_OK;
673 }
674
675private:
676 WAVEFORMATEX format_{};
677};
678
679class SpatialStream;
680
681class SpatialObject final : public Unknown<ISpatialAudioObject> {
682public:
683 SpatialObject(SpatialStream* stream, uint32_t type);
684 HRESULT STDMETHODCALLTYPE GetBuffer(BYTE** buffer, UINT32* length) override;
685 HRESULT STDMETHODCALLTYPE SetEndOfStream(UINT32 frames) override;
686 HRESULT STDMETHODCALLTYPE IsActive(BOOL* active) override {
687 if (!active) return E_POINTER;
688 *active = InterlockedCompareExchange(&active_, 0, 0) ? TRUE : FALSE;
689 return S_OK;
690 }
691 HRESULT STDMETHODCALLTYPE GetAudioObjectType(AudioObjectType* type) override {
692 if (!type) return E_POINTER;
693 *type = static_cast<AudioObjectType>(type_);
694 return S_OK;
695 }
696 HRESULT STDMETHODCALLTYPE SetPosition(float, float, float) override { return S_OK; } // nothing is rendered
697 HRESULT STDMETHODCALLTYPE SetVolume(float volume) override {
698 return volume >= 0.0f && volume <= 1.0f ? S_OK : E_INVALIDARG;
699 }
700 // The stream ends the object at the end of the pass it called SetEndOfStream in.
701 void make_inactive() { InterlockedExchange(&active_, 0); }
702 // True once: whoever takes the type frees it in the stream.
703 bool take_type() { return InterlockedExchange(&type_held_, 0) != 0; }
704 uint32_t type() const { return type_; }
705
706private:
707 ~SpatialObject() override;
708 SpatialStream* stream_;
709 uint32_t type_;
710 LONG active_ = 1;
711 LONG type_held_ = 1;
712 LONG ending_ = 0;
713};
714
715class SpatialStream final : public Unknown<ISpatialAudioObjectRenderStream> {
716public:
717 SpatialStream(HANDLE event, uint32_t mask) : event_(event), mask_(mask) {
718 scratch_.assign(static_cast<size_t>(kObjectFrames) * 4, 0);
719 }
720 bool start_clock() { return clock_.start(kDefaultPeriodHns, &SpatialStream::tick, this); }
721
722 HRESULT STDMETHODCALLTYPE GetAvailableDynamicObjectCount(UINT32* value) override {
723 if (!value) return E_POINTER;
724 *value = 0;
725 return S_OK;
726 }
727 HRESULT STDMETHODCALLTYPE GetService(REFIID riid, void** service) override {
728 if (!service) return E_POINTER;
729 *service = nullptr;
730 log_missing_iid_once("ISpatialAudioObjectRenderStream::GetService", riid);
731 return E_NOINTERFACE;
732 }
733 HRESULT STDMETHODCALLTYPE Start() override {
734 {
735 Lock l(lock_);
736 if (running_) return S_OK;
737 running_ = true;
738 }
739 SetEvent(event_);
740 return S_OK;
741 }
742 HRESULT STDMETHODCALLTYPE Stop() override {
743 Lock l(lock_);
744 running_ = false;
745 return S_OK;
746 }
747 HRESULT STDMETHODCALLTYPE Reset() override {
748 Lock l(lock_);
749 return running_ ? SPTLAUDCLNT_E_STREAM_NOT_STOPPED : S_OK;
750 }
751 HRESULT STDMETHODCALLTYPE BeginUpdatingAudioObjects(UINT32* available, UINT32* frames) override {
752 if (!available || !frames) return E_POINTER;
753 Lock l(lock_);
754 if (updating_) return SPTLAUDCLNT_E_OUT_OF_ORDER;
755 updating_ = true;
756 *available = 0;
757 *frames = kObjectFrames;
758 return S_OK;
759 }
760 HRESULT STDMETHODCALLTYPE EndUpdatingAudioObjects() override {
761 std::vector<SpatialObject*> ended;
762 {
763 Lock l(lock_);
764 if (!updating_) return SPTLAUDCLNT_E_OUT_OF_ORDER;
765 updating_ = false;
766 ended.swap(ending_);
767 for (SpatialObject* o : ended) {
768 o->make_inactive();
769 if (o->take_type()) active_types_ &= ~o->type();
770 }
771 }
772 for (SpatialObject* o : ended) o->Release();
773 return S_OK;
774 }
775 HRESULT STDMETHODCALLTYPE ActivateSpatialAudioObject(AudioObjectType type, ISpatialAudioObject** object) override {
776 if (!object) return E_POINTER;
777 *object = nullptr;
778 const uint32_t t = static_cast<uint32_t>(type);
779 if (t == AudioObjectType_Dynamic) return SPTLAUDCLNT_E_NO_MORE_OBJECTS;
780 if (!one_type(t) || (t & ~kStaticTypes)) return E_INVALIDARG;
781 {
782 Lock l(lock_);
783 if (!(mask_ & t)) return SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE;
784 if (active_types_ & t) return SPTLAUDCLNT_E_OBJECT_ALREADY_ACTIVE;
785 active_types_ |= t;
786 }
787 auto* o = new (std::nothrow) SpatialObject(this, t);
788 if (!o) {
789 release_type(t);
790 return E_OUTOFMEMORY;
791 }
792 *object = o;
793 return S_OK;
794 }
795
796 // For the objects.
797 HRESULT buffer(BYTE** data, UINT32* length) {
798 Lock l(lock_);
799 if (!updating_) return SPTLAUDCLNT_E_OUT_OF_ORDER;
800 *data = scratch_.data();
801 *length = static_cast<UINT32>(scratch_.size());
802 return S_OK;
803 }
804 HRESULT end_of_stream(SpatialObject* o) {
805 Lock l(lock_);
806 if (!updating_) return SPTLAUDCLNT_E_OUT_OF_ORDER;
807 o->AddRef();
808 ending_.push_back(o);
809 return S_OK;
810 }
811 void release_type(uint32_t t) {
812 Lock l(lock_);
813 active_types_ &= ~t;
814 }
815
816private:
817 struct Lock {
818 explicit Lock(SRWLOCK& s) : s_(s) { AcquireSRWLockExclusive(&s_); }
819 ~Lock() { ReleaseSRWLockExclusive(&s_); }
820 SRWLOCK& s_;
821 };
822 ~SpatialStream() override { clock_.stop(); } // ending_ is empty: each entry holds the stream
823 static void tick(void* self) {
824 auto* s = static_cast<SpatialStream*>(self);
825 bool running = false;
826 {
827 Lock l(s->lock_);
828 running = s->running_;
829 }
830 if (running) SetEvent(s->event_);
831 }
832
833 SRWLOCK lock_ = SRWLOCK_INIT;
834 HANDLE event_; // the title's; not owned
835 uint32_t mask_;
836 uint32_t active_types_ = 0;
837 bool running_ = false;
838 bool updating_ = false;
839 std::vector<BYTE> scratch_;
840 std::vector<SpatialObject*> ending_;
841 PeriodicThread clock_;
842};
843
844SpatialObject::SpatialObject(SpatialStream* stream, uint32_t type) : stream_(stream), type_(type) {
845 stream_->AddRef();
846}
847SpatialObject::~SpatialObject() {
848 if (take_type()) stream_->release_type(type_);
849 stream_->Release();
850}
851HRESULT SpatialObject::GetBuffer(BYTE** buffer, UINT32* length) {
852 if (!buffer || !length) return E_POINTER;
853 *buffer = nullptr;
854 *length = 0;
855 if (!InterlockedCompareExchange(&active_, 0, 0)) return SPTLAUDCLNT_E_RESOURCES_INVALIDATED;
856 return stream_->buffer(buffer, length);
857}
858HRESULT SpatialObject::SetEndOfStream(UINT32) {
859 if (!InterlockedCompareExchange(&active_, 0, 0)) return SPTLAUDCLNT_E_RESOURCES_INVALIDATED;
860 if (InterlockedCompareExchange(&ending_, 1, 0) != 0) return S_OK;
861 const HRESULT hr = stream_->end_of_stream(this);
862 if (FAILED(hr)) InterlockedExchange(&ending_, 0);
863 return hr;
864}
865
866class SpatialClient final : public Unknown<ISpatialAudioClient2> {
867public:
868 HRESULT STDMETHODCALLTYPE GetStaticObjectPosition(AudioObjectType type, float* x, float* y, float* z) override {
869 if (!x || !y || !z) return E_POINTER;
870 // Unit directions: x right, y up, z back (the listener faces -z).
871 const float d = 0.70710678f;
872 float p[3]{};
873 switch (static_cast<uint32_t>(type)) {
874 case AudioObjectType_FrontLeft: p[0] = -d, p[2] = -d; break;
875 case AudioObjectType_FrontRight: p[0] = d, p[2] = -d; break;
876 case AudioObjectType_FrontCenter: p[2] = -1; break;
877 case AudioObjectType_LowFrequency: break;
878 case AudioObjectType_SideLeft: p[0] = -1; break;
879 case AudioObjectType_SideRight: p[0] = 1; break;
880 case AudioObjectType_BackLeft: p[0] = -d, p[2] = d; break;
881 case AudioObjectType_BackRight: p[0] = d, p[2] = d; break;
882 default: return E_INVALIDARG;
883 }
884 *x = p[0];
885 *y = p[1];
886 *z = p[2];
887 return S_OK;
888 }
889 HRESULT STDMETHODCALLTYPE GetNativeStaticObjectTypeMask(AudioObjectType* mask) override {
890 if (!mask) return E_POINTER;
891 *mask = static_cast<AudioObjectType>(kBedMask);
892 return S_OK;
893 }
894 HRESULT STDMETHODCALLTYPE GetMaxDynamicObjectCount(UINT32* value) override {
895 if (!value) return E_POINTER;
896 *value = 0;
897 return S_OK;
898 }
899 HRESULT STDMETHODCALLTYPE GetSupportedAudioObjectFormatEnumerator(IAudioFormatEnumerator** e) override {
900 if (!e) return E_POINTER;
901 *e = new (std::nothrow) FormatEnumerator();
902 return *e ? S_OK : E_OUTOFMEMORY;
903 }
904 HRESULT STDMETHODCALLTYPE GetMaxFrameCount(const WAVEFORMATEX* format, UINT32* frames) override {
905 if (!format || !frames) return E_POINTER;
906 if (!is_object_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT;
907 *frames = kObjectFrames;
908 return S_OK;
909 }
910 HRESULT STDMETHODCALLTYPE IsAudioObjectFormatSupported(const WAVEFORMATEX* format) override {
911 if (!format) return E_POINTER;
912 return is_object_format(format) ? S_OK : AUDCLNT_E_UNSUPPORTED_FORMAT;
913 }
914 HRESULT STDMETHODCALLTYPE IsSpatialAudioStreamAvailable(REFIID stream, const PROPVARIANT*) override {
915 return IsEqualIID(stream, __uuidof(ISpatialAudioObjectRenderStream)) ? S_OK
916 : SPTLAUDCLNT_E_STREAM_NOT_AVAILABLE;
917 }
918 HRESULT STDMETHODCALLTYPE ActivateSpatialAudioStream(const PROPVARIANT* params, REFIID riid, void** out) override {
919 if (!out) return E_POINTER;
920 *out = nullptr;
921 if (!params) return E_INVALIDARG;
922 if (!IsEqualIID(riid, __uuidof(ISpatialAudioObjectRenderStream))) {
923 log_missing_iid_once("ISpatialAudioClient::ActivateSpatialAudioStream", riid);
924 return E_NOINTERFACE;
925 }
926 if (params->vt != VT_BLOB || !params->blob.pBlobData ||
927 params->blob.cbSize < sizeof(SpatialAudioObjectRenderStreamActivationParams)) {
928 return E_INVALIDARG;
929 }
930 SpatialAudioObjectRenderStreamActivationParams p{};
931 std::memcpy(&p, params->blob.pBlobData, sizeof p);
932 if (!p.ObjectFormat || !p.EventHandle) return E_INVALIDARG;
933 if (!is_object_format(p.ObjectFormat)) return AUDCLNT_E_UNSUPPORTED_FORMAT;
934 const uint32_t mask = static_cast<uint32_t>(p.StaticObjectTypeMask);
935 if (mask & ~kStaticTypes) return E_INVALIDARG; // AudioObjectType_Dynamic is not a static type
936 if (p.MinDynamicObjectCount > p.MaxDynamicObjectCount) return E_INVALIDARG;
937 // Dynamic objects asked for are granted as none available (GetAvailableDynamicObjectCount is 0), so a
938 // minimum above 0 is accepted rather than refused.
939 auto* s = new (std::nothrow) SpatialStream(p.EventHandle, mask);
940 if (!s) return E_OUTOFMEMORY;
941 if (!s->start_clock()) {
942 s->Release();
943 return E_OUTOFMEMORY;
944 }
945 if (InterlockedExchange(&g_spatial_logged, 1) == 0) {
946 std::fprintf(stderr,
947 "[rt] audio: silent spatial stream: static objects 0x%x, dynamic objects %u..%u asked "
948 "(0 available), %u frames a pass\n",
949 mask, p.MinDynamicObjectCount, p.MaxDynamicObjectCount, kObjectFrames);
950 }
951 const HRESULT hr = s->QueryInterface(riid, out);
952 s->Release();
953 return hr;
954 }
955 // ISpatialAudioClient2
956 HRESULT STDMETHODCALLTYPE IsOffloadCapable(AUDIO_STREAM_CATEGORY, BOOL* capable) override {
957 if (!capable) return E_POINTER;
958 *capable = FALSE;
959 return S_OK;
960 }
961 HRESULT STDMETHODCALLTYPE GetMaxFrameCountForCategory(AUDIO_STREAM_CATEGORY, BOOL, const WAVEFORMATEX* format,
962 UINT32* frames) override {
963 return GetMaxFrameCount(format, frames);
964 }
965
966private:
967 bool answers(REFIID riid) const override {
968 return IsEqualIID(riid, __uuidof(ISpatialAudioClient)) || IsEqualIID(riid, __uuidof(ISpatialAudioClient2));
969 }
970 static inline LONG g_spatial_logged = 0;
971};
972
973// ---- IPropertyStore -------------------------------------------------------------------------------------------
974
975class PropertyStore final : public Unknown<IPropertyStore> {
976public:
977 HRESULT STDMETHODCALLTYPE GetCount(DWORD* count) override {
978 if (!count) return E_POINTER;
979 *count = static_cast<DWORD>(sizeof kKeys / sizeof kKeys[0]);
980 return S_OK;
981 }
982 HRESULT STDMETHODCALLTYPE GetAt(DWORD index, PROPERTYKEY* key) override {
983 if (!key) return E_POINTER;
984 if (index >= sizeof kKeys / sizeof kKeys[0]) return E_INVALIDARG;
985 *key = kKeys[index];
986 return S_OK;
987 }
988 HRESULT STDMETHODCALLTYPE GetValue(REFPROPERTYKEY key, PROPVARIANT* value) override {
989 if (!value) return E_POINTER;
990 PropVariantInit(value);
991 if (same_key(key, kKeyFriendlyName) || same_key(key, kKeyDeviceDesc) || same_key(key, kKeyInterfaceName) ||
992 same_key(key, kKeyEndpointGuid)) {
993 value->pwszVal = co_task_string(same_key(key, kKeyEndpointGuid) ? kEndpointGuid : kFriendlyName);
994 if (!value->pwszVal) return E_OUTOFMEMORY;
995 value->vt = VT_LPWSTR;
996 } else if (same_key(key, kKeyDeviceFormat) || same_key(key, kKeyOemFormat)) {
997 value->blob.pBlobData = reinterpret_cast<BYTE*>(alloc_mix_format());
998 if (!value->blob.pBlobData) return E_OUTOFMEMORY;
999 value->blob.cbSize = sizeof(WAVEFORMATEXTENSIBLE);
1000 value->vt = VT_BLOB;
1001 } else if (same_key(key, kKeyFormFactor) || same_key(key, kKeyPhysicalSpeakers)) {
1002 value->ulVal = same_key(key, kKeyFormFactor) ? kFormFactorSpeakers : kChannelMask;
1003 value->vt = VT_UI4;
1004 }
1005 return S_OK; // any other key: VT_EMPTY, as a host store answers a key it does not hold
1006 }
1007 HRESULT STDMETHODCALLTYPE SetValue(REFPROPERTYKEY, REFPROPVARIANT) override { return STG_E_ACCESSDENIED; }
1008 HRESULT STDMETHODCALLTYPE Commit() override { return STG_E_ACCESSDENIED; }
1009};
1010
1011// ---- IMMDevice ------------------------------------------------------------------------------------------------
1012
1013class Device final : public IMMDevice, public IMMEndpoint {
1014public:
1015 ULONG STDMETHODCALLTYPE AddRef() override { return static_cast<ULONG>(InterlockedIncrement(&refs_)); }
1016 ULONG STDMETHODCALLTYPE Release() override {
1017 const LONG n = InterlockedDecrement(&refs_);
1018 if (n == 0) delete this;
1019 return static_cast<ULONG>(n);
1020 }
1021 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
1022 if (!ppv) return E_POINTER;
1023 *ppv = nullptr;
1024 if (IsEqualIID(riid, __uuidof(IUnknown)) || IsEqualIID(riid, __uuidof(IMMDevice))) {
1025 *ppv = static_cast<IMMDevice*>(this);
1026 } else if (IsEqualIID(riid, __uuidof(IMMEndpoint))) {
1027 *ppv = static_cast<IMMEndpoint*>(this);
1028 } else {
1029 return E_NOINTERFACE;
1030 }
1031 AddRef();
1032 return S_OK;
1033 }
1034
1035 // IMMDevice
1036 HRESULT STDMETHODCALLTYPE Activate(REFIID riid, DWORD, PROPVARIANT*, void** ppv) override {
1037 if (!ppv) return E_POINTER;
1038 *ppv = nullptr;
1039 if (IsEqualIID(riid, __uuidof(ISpatialAudioClient)) || IsEqualIID(riid, __uuidof(ISpatialAudioClient2))) {
1040 auto* spatial = new (std::nothrow) SpatialClient();
1041 if (!spatial) return E_OUTOFMEMORY;
1042 const HRESULT hr = spatial->QueryInterface(riid, ppv);
1043 spatial->Release();
1044 return hr;
1045 }
1046 if (!IsEqualIID(riid, __uuidof(IAudioClient)) && !IsEqualIID(riid, __uuidof(IAudioClient2)) &&
1047 !IsEqualIID(riid, __uuidof(IAudioClient3))) {
1048 log_missing_iid_once("IMMDevice::Activate", riid);
1049 return E_NOINTERFACE;
1050 }
1051 auto* client = new (std::nothrow) AudioClient();
1052 if (!client) return E_OUTOFMEMORY;
1053 const HRESULT hr = client->QueryInterface(riid, ppv);
1054 client->Release();
1055 return hr;
1056 }
1057 HRESULT STDMETHODCALLTYPE OpenPropertyStore(DWORD access, IPropertyStore** store) override {
1058 if (!store) return E_POINTER;
1059 *store = nullptr;
1060 if (access != STGM_READ && access != STGM_WRITE && access != STGM_READWRITE) return E_INVALIDARG;
1061 if (access != STGM_READ) return E_ACCESSDENIED;
1062 *store = new (std::nothrow) PropertyStore();
1063 return *store ? S_OK : E_OUTOFMEMORY;
1064 }
1065 HRESULT STDMETHODCALLTYPE GetId(LPWSTR* id) override {
1066 if (!id) return E_POINTER;
1067 *id = co_task_string(kDeviceId);
1068 return *id ? S_OK : E_OUTOFMEMORY;
1069 }
1070 HRESULT STDMETHODCALLTYPE GetState(DWORD* state) override {
1071 if (!state) return E_POINTER;
1072 *state = DEVICE_STATE_ACTIVE;
1073 return S_OK;
1074 }
1075
1076 // IMMEndpoint
1077 HRESULT STDMETHODCALLTYPE GetDataFlow(EDataFlow* flow) override {
1078 if (!flow) return E_POINTER;
1079 *flow = eRender;
1080 return S_OK;
1081 }
1082
1083private:
1084 ~Device() = default;
1085 LONG refs_ = 1;
1086};
1087
1088IMMDevice* make_device(const char* reason) {
1089 auto* d = new (std::nothrow) Device();
1090 if (d) note_served(reason);
1091 return d;
1092}
1093
1094// ---- IMMDeviceCollection --------------------------------------------------------------------------------------
1095
1096class Collection final : public Unknown<IMMDeviceCollection> {
1097public:
1098 void add(IMMDevice* device) { devices_.push_back(device); } // takes the reference
1099 HRESULT STDMETHODCALLTYPE GetCount(UINT* count) override {
1100 if (!count) return E_POINTER;
1101 *count = static_cast<UINT>(devices_.size());
1102 return S_OK;
1103 }
1104 HRESULT STDMETHODCALLTYPE Item(UINT index, IMMDevice** device) override {
1105 if (!device) return E_POINTER;
1106 *device = nullptr;
1107 if (index >= devices_.size()) return E_INVALIDARG;
1108 *device = devices_[index];
1109 (*device)->AddRef();
1110 return S_OK;
1111 }
1112
1113private:
1114 ~Collection() override {
1115 for (IMMDevice* d : devices_) d->Release();
1116 }
1117 std::vector<IMMDevice*> devices_;
1118};
1119
1120// Appends the host's devices of one flow; returns the result of the host's call.
1121HRESULT append_host(IMMDeviceEnumerator* host, EDataFlow flow, DWORD mask, Collection* out) {
1122 IMMDeviceCollection* c = nullptr;
1123 const HRESULT hr = host->EnumAudioEndpoints(flow, mask, &c);
1124 if (FAILED(hr) || !c) return hr;
1125 UINT n = 0;
1126 c->GetCount(&n);
1127 for (UINT i = 0; i < n; ++i) {
1128 IMMDevice* d = nullptr;
1129 if (SUCCEEDED(c->Item(i, &d)) && d) out->add(d);
1130 }
1131 c->Release();
1132 return hr;
1133}
1134
1135// ---- IMMDeviceEnumerator --------------------------------------------------------------------------------------
1136
1137class Enumerator final : public Unknown<IMMDeviceEnumerator> {
1138public:
1139 Enumerator(IMMDeviceEnumerator* host, HRESULT host_hr, Mode mode, HostFactory factory)
1140 : host_(host), host_hr_(host_hr), mode_(mode), factory_(factory) {
1141 if (host_) host_->AddRef();
1142 }
1143
1144 HRESULT STDMETHODCALLTYPE EnumAudioEndpoints(EDataFlow flow, DWORD mask, IMMDeviceCollection** out) override {
1145 if (!out) return E_POINTER;
1146 *out = nullptr;
1147 if (flow != eRender && flow != eCapture && flow != eAll) return E_INVALIDARG;
1148 if (mask & ~DEVICE_STATEMASK_ALL) return E_INVALIDARG;
1149 auto* c = new (std::nothrow) Collection();
1150 if (!c) return E_OUTOFMEMORY;
1151 if (flow == eRender || flow == eAll) {
1152 char reason[96];
1153 if (!host_render(reason, sizeof reason)) {
1154 if (mask & DEVICE_STATE_ACTIVE) {
1155 if (IMMDevice* d = make_device(reason)) c->add(d);
1156 }
1157 } else {
1158 append_host(host_, eRender, mask, c);
1159 }
1160 }
1161 if (flow == eCapture || flow == eAll) {
1162 if (IMMDeviceEnumerator* h = host()) append_host(h, eCapture, mask, c);
1163 }
1164 *out = c;
1165 return S_OK;
1166 }
1167 HRESULT STDMETHODCALLTYPE GetDefaultAudioEndpoint(EDataFlow flow, ERole role, IMMDevice** out) override {
1168 if (!out) return E_POINTER;
1169 *out = nullptr;
1170 if (role != eConsole && role != eMultimedia && role != eCommunications) return E_INVALIDARG;
1171 if (flow == eCapture) {
1172 IMMDeviceEnumerator* h = host();
1173 return h ? h->GetDefaultAudioEndpoint(flow, role, out) : kNotFound;
1174 }
1175 if (flow != eRender) return E_INVALIDARG;
1176 char reason[96];
1177 if (mode_ == Mode::Auto && host_) {
1178 const HRESULT hr = host_->GetDefaultAudioEndpoint(eRender, role, out);
1179 if (SUCCEEDED(hr) && *out) return hr;
1180 if (*out) (*out)->Release();
1181 *out = nullptr;
1182 std::snprintf(reason, sizeof reason, "no host render endpoint: GetDefaultAudioEndpoint 0x%08lx",
1183 static_cast<unsigned long>(hr));
1184 } else {
1185 why_silent(reason, sizeof reason);
1186 }
1187 *out = make_device(reason);
1188 return *out ? S_OK : E_OUTOFMEMORY;
1189 }
1190 HRESULT STDMETHODCALLTYPE GetDevice(LPCWSTR id, IMMDevice** out) override {
1191 if (!id || !out) return E_POINTER;
1192 *out = nullptr;
1193 if (std::wcscmp(id, kDeviceId) == 0) {
1194 char reason[96];
1195 why_silent(reason, sizeof reason);
1196 *out = make_device(reason);
1197 return *out ? S_OK : E_OUTOFMEMORY;
1198 }
1199 IMMDeviceEnumerator* h = host();
1200 return h ? h->GetDevice(id, out) : kNotFound;
1201 }
1202 // Accepted and never called: the silent endpoint never changes, and no host notification is forwarded.
1203 HRESULT STDMETHODCALLTYPE RegisterEndpointNotificationCallback(IMMNotificationClient* client) override {
1204 return client ? S_OK : E_POINTER;
1205 }
1206 HRESULT STDMETHODCALLTYPE UnregisterEndpointNotificationCallback(IMMNotificationClient* client) override {
1207 return client ? S_OK : E_POINTER;
1208 }
1209
1210private:
1211 ~Enumerator() override {
1212 if (host_) host_->Release();
1213 }
1214
1215 // The host's enumerator for capture questions: made on first use in Mode::Silent.
1216 IMMDeviceEnumerator* host() {
1217 AcquireSRWLockExclusive(&lock_);
1218 if (!host_ && factory_ && !factory_tried_) {
1219 factory_tried_ = true;
1220 host_ = factory_();
1221 }
1222 IMMDeviceEnumerator* h = host_;
1223 ReleaseSRWLockExclusive(&lock_);
1224 return h;
1225 }
1226
1227 void why_silent(char* reason, size_t size) const {
1228 if (mode_ == Mode::Silent) std::snprintf(reason, size, "LEONIDA_AUDIO=silent");
1229 else if (!host_) std::snprintf(reason, size, "no host device enumerator: 0x%08lx",
1230 static_cast<unsigned long>(host_hr_));
1231 else std::snprintf(reason, size, "no host render endpoint");
1232 }
1233
1234 // True when render questions go to the host: Mode::Auto and a host with a default render endpoint.
1235 bool host_render(char* reason, size_t size) {
1236 if (mode_ == Mode::Auto && host_) {
1237 IMMDevice* d = nullptr;
1238 const HRESULT hr = host_->GetDefaultAudioEndpoint(eRender, eConsole, &d);
1239 if (d) d->Release();
1240 if (SUCCEEDED(hr) && d) return true;
1241 std::snprintf(reason, size, "no host render endpoint: GetDefaultAudioEndpoint 0x%08lx",
1242 static_cast<unsigned long>(hr));
1243 return false;
1244 }
1245 why_silent(reason, size);
1246 return false;
1247 }
1248
1249 SRWLOCK lock_ = SRWLOCK_INIT;
1250 IMMDeviceEnumerator* host_;
1251 HRESULT host_hr_;
1252 Mode mode_;
1253 HostFactory factory_;
1254 bool factory_tried_ = false;
1255};
1256
1257IMMDeviceEnumerator* make_host_enumerator() {
1258 IMMDeviceEnumerator* e = nullptr;
1259 if (FAILED(::CoCreateInstance(kClsidMMDeviceEnumerator, nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
1260 reinterpret_cast<void**>(&e)))) {
1261 return nullptr;
1262 }
1263 return e;
1264}
1265
1266} // namespace
1267
1268Mode mode_from_env() {
1269 char v[16]{};
1270 const DWORD n = GetEnvironmentVariableA("LEONIDA_AUDIO", v, sizeof v);
1271 if (n == 0 || n >= sizeof v) return Mode::Auto;
1272 return _stricmp(v, "silent") == 0 ? Mode::Silent : Mode::Auto;
1273}
1274
1275HRESULT serve_enumerator(IMMDeviceEnumerator* host, HRESULT host_hr, Mode mode, HostFactory factory, REFIID riid,
1276 void** ppv) {
1277 if (!ppv) return E_POINTER;
1278 *ppv = nullptr;
1279 if (mode == Mode::Auto && host) {
1280 IMMDevice* d = nullptr;
1281 const HRESULT hr = host->GetDefaultAudioEndpoint(eRender, eConsole, &d);
1282 if (d) d->Release();
1283 if (SUCCEEDED(hr) && d) return host->QueryInterface(riid, ppv); // the host has an output: unchanged
1284 }
1285 auto* e = new (std::nothrow) Enumerator(host, host ? S_OK : host_hr, mode, factory);
1286 if (!e) return E_OUTOFMEMORY;
1287 const HRESULT hr = e->QueryInterface(riid, ppv);
1288 e->Release();
1289 return hr;
1290}
1291
1292HRESULT create_enumerator(DWORD cls_context, REFIID riid, void** ppv) {
1293 if (!ppv) return E_POINTER;
1294 *ppv = nullptr;
1295 const Mode mode = mode_from_env();
1296 if (mode == Mode::Silent) return serve_enumerator(nullptr, S_OK, mode, &make_host_enumerator, riid, ppv);
1297 IMMDeviceEnumerator* host = nullptr;
1298 const HRESULT hr = ::CoCreateInstance(kClsidMMDeviceEnumerator, nullptr, cls_context,
1299 __uuidof(IMMDeviceEnumerator), reinterpret_cast<void**>(&host));
1300 if (FAILED(hr)) host = nullptr;
1301 const HRESULT served = serve_enumerator(host, hr, mode, nullptr, riid, ppv);
1302 if (host) host->Release();
1303 return served;
1304}
1305
1306uint32_t devices_served() { return static_cast<uint32_t>(InterlockedCompareExchange(&g_served, 0, 0)); }
1307
1308} // namespace rt::silent_audio
diff --git a/runtime/shims/silent_audio.h b/runtime/shims/silent_audio.h
new file mode 100644
index 000000000..779aa5011
--- /dev/null
+++ b/runtime/shims/silent_audio.h
@@ -0,0 +1,61 @@
1// The silent output endpoint: an in-process WASAPI render device that throws every sample away.
2//
3// The title creates its MMDeviceEnumerator through CoCreateInstance (com_shim.cpp). When the host has no render
4// endpoint, GetDefaultAudioEndpoint(eRender, ...) fails with 0x80070490 (ERROR_NOT_FOUND); the title's device start
5// then leaks its own output-device lock and its audio engine never mixes, so the boot stops. A console always has an
6// output, so the title only meets that path off-console. The enumerator served here answers render questions with a
7// device of its own when the host has none (or always, with LEONIDA_AUDIO=silent): an ISpatialAudioClient (what the
8// title activates) and an IAudioClient, whose streams consume frames in real time and signal their event every
9// period. It never opens a host audio device.
10// Capture questions keep the host's answer.
11#pragma once
12
13#include <windows.h>
14#include <objbase.h>
15#include <mmdeviceapi.h>
16
17#include <cstdint>
18
19namespace rt::silent_audio {
20
21// {BCDE0395-E52F-467C-8E3D-C4579291692E}
22inline constexpr CLSID kClsidMMDeviceEnumerator{
23 0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}};
24
25// The endpoint ID GetId returns (the form of a host render endpoint ID).
26inline constexpr wchar_t kDeviceId[] = L"{0.0.0.00000000}.{5a4c2a5e-1e0d-4c1b-9a51-6c656f6e6964}";
27inline constexpr wchar_t kFriendlyName[] = L"Leonida silent output";
28
29// The mix format: 48 kHz, 32-bit float, 7.1 (eight channels, KSAUDIO_SPEAKER_7POINT1_SURROUND).
30inline constexpr uint32_t kSampleRate = 48000;
31inline constexpr uint16_t kChannels = 8;
32inline constexpr uint32_t kChannelMask = 0x63F;
33// The engine period: 10 ms (default), 3 ms (minimum), in 100 ns units.
34inline constexpr int64_t kDefaultPeriodHns = 100000;
35inline constexpr int64_t kMinimumPeriodHns = 30000;
36
37enum class Mode {
38 Auto, // the host's render endpoint when it has one, the silent one when it has none
39 Silent, // LEONIDA_AUDIO=silent: the silent endpoint even when the host has one
40};
41
42// LEONIDA_AUDIO, read on every call: "silent" (any case) is Mode::Silent, anything else Mode::Auto.
43Mode mode_from_env();
44
45// Makes the host's enumerator on demand (Mode::Silent creates none until a capture question needs one); may be null.
46using HostFactory = IMMDeviceEnumerator* (*)();
47
48// What CoCreateInstance(CLSID_MMDeviceEnumerator) returns. `host` is the host's enumerator or null, with `host_hr`
49// the result of creating it; it is not consumed (what is kept is AddRef'd). In Mode::Auto, a host that answers
50// GetDefaultAudioEndpoint(eRender, eConsole) is returned itself, unchanged; otherwise the wrapper answers.
51HRESULT serve_enumerator(IMMDeviceEnumerator* host, HRESULT host_hr, Mode mode, HostFactory factory, REFIID riid,
52 void** ppv);
53
54// The CoCreateInstance hook: the mode from the environment, the host's enumerator (not made in Mode::Silent), then
55// serve_enumerator.
56HRESULT create_enumerator(DWORD cls_context, REFIID riid, void** ppv);
57
58// For tests: how many silent devices have been handed out.
59uint32_t devices_served();
60
61} // namespace rt::silent_audio
diff --git a/runtime/src/title_page_watch.h b/runtime/src/title_page_watch.h
index b83e71b7b..580edf622 100644
--- a/runtime/src/title_page_watch.h
+++ b/runtime/src/title_page_watch.h
@@ -636,6 +636,31 @@ inline void end_write(std::uint64_t id, bool pending) {
636 s.count.store(s.pins.size(), std::memory_order_release); 636 s.count.store(s.pins.size(), std::memory_order_release);
637} 637}
638 638
639// For as long as the GPU may use [buffer, buffer + bytes) as host memory (the D3D12 layer's VK_EXT_external_memory_host
640// imports): pins the range until release() and opens it. Unlike begin_write it records the pin before any tracker
641// exists, so a tracker made later passes over the pages too. RADV checks an import's pages again at every submission,
642// and once one of them is read-only the kernel rejects that submission and every later one ("The CS has been
643// rejected", then VK_ERROR_DEVICE_LOST; found and measured by NateWeav, #14), so no guard may land on them. Returns
644// the pin's id, 0 for an empty range.
645inline std::uint64_t hold(const void* buffer, std::size_t bytes) {
646 if (!buffer || !bytes) return 0;
647 State& s = state();
648 const auto begin = reinterpret_cast<std::uintptr_t>(buffer);
649 std::uint64_t id = 0;
650 {
651 std::lock_guard lock(s.mutex);
652 id = s.next_id++;
653 s.pins.push_back({begin, begin + bytes, nullptr, id});
654 s.count.store(s.pins.size(), std::memory_order_release);
655 }
656 // After the pin: a guard a refresh made before it is lifted, and no refresh from here on makes one.
657 if (const Opener opener = s.opener.load(std::memory_order_acquire)) opener(begin, begin + bytes);
658 return id;
659}
660
661// The import is freed: its pin ends.
662inline void release(std::uint64_t id) { end_write(id, false); }
663
639// Readies [buffer, buffer + bytes) for a retry after ERROR_NOACCESS: commits xmem's pages that wait for their first 664// Readies [buffer, buffer + bytes) for a retry after ERROR_NOACCESS: commits xmem's pages that wait for their first
640// touch (the kernel's write does not fault them in) and opens watched pages again. false: neither side is set. 665// touch (the kernel's write does not fault them in) and opens watched pages again. false: neither side is set.
641inline bool reopen(const void* buffer, std::size_t bytes) { 666inline bool reopen(const void* buffer, std::size_t bytes) {
diff --git a/runtime/test/d3d12_placed_depth_test.h b/runtime/test/d3d12_placed_depth_test.h
index 95d32772b..5ef9f88a9 100644
--- a/runtime/test/d3d12_placed_depth_test.h
+++ b/runtime/test/d3d12_placed_depth_test.h
@@ -1,6 +1,7 @@
1// Slot-133 aliases share GPU contents and retain individual COM identities. 1// Slot-133 aliases share GPU contents and retain individual COM identities.
2#pragma once 2#pragma once
3#include "d3d12_copy_compare.h" 3#include "d3d12_copy_compare.h"
4#include "../shims/d3d12_xs_device.h"
4 5
5namespace placeddepthtest { 6namespace placeddepthtest {
6 7
@@ -54,8 +55,28 @@ inline bool check_alias_lifetime(ID3D12Device* device, ID3D12Device* xbox, bool
54 optimized.DepthStencil = {1.0f, 0}; 55 optimized.DepthStencil = {1.0f, 0};
55 if (place(address, xbox_desc, invalid, &optimized) != E_NOTIMPL || invalid.p) return false; 56 if (place(address, xbox_desc, invalid, &optimized) != E_NOTIMPL || invalid.p) return false;
56 if ((!opaque && (place(address, smaller, invalid) != E_NOTIMPL || invalid.p)) || 57 if ((!opaque && (place(address, smaller, invalid) != E_NOTIMPL || invalid.p)) ||
57 place(address + allocation.Alignment, xbox_desc, invalid) != E_NOTIMPL || invalid.p ||
58 place(address + 1, xbox_desc, invalid) != E_INVALIDARG || invalid.p) return false; 58 place(address + 1, xbox_desc, invalid) != E_INVALIDARG || invalid.p) return false;
59 // A placement that starts inside another one's PC allocation: the title's own blocks can be smaller than the
60 // PC sizes them (a D16 target on RADV), so the next block starts inside the range. Opaque layouts get a backing
61 // of their own there; a layout whose bytes would have to be shared is still refused.
62 if (!opaque) {
63 if (place(address + allocation.Alignment, xbox_desc, invalid) != E_NOTIMPL || invalid.p) return false;
64 } else {
65 Ptr<ID3D12Resource> inside;
66 if (FAILED(place(address + allocation.Alignment, xbox_desc, inside)) ||
67 inside->GetGPUVirtualAddress() != address + allocation.Alignment ||
68 rt::d3d12_xs::texture_backing(inside.p) == rt::d3d12_xs::texture_backing(first.p)) {
69 std::fprintf(stderr, "slot-133 alias: a placement inside another range was refused or shared\n");
70 return false;
71 }
72 // Placing the first shape again still finds its own backing, with the inner range registered.
73 Ptr<ID3D12Resource> again;
74 if (FAILED(place(address, xbox_desc, again)) ||
75 rt::d3d12_xs::texture_backing(again.p) != rt::d3d12_xs::texture_backing(first.p)) {
76 std::fprintf(stderr, "slot-133 alias: the outer range lost its backing to the inner one\n");
77 return false;
78 }
79 }
59 80
60 Ptr<ID3D12DescriptorHeap> heap; 81 Ptr<ID3D12DescriptorHeap> heap;
61 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2}; 82 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2};
diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp
index 0adb72d25..2aac6c680 100644
--- a/runtime/test/d3d12_title_va_test.cpp
+++ b/runtime/test/d3d12_title_va_test.cpp
@@ -298,6 +298,129 @@ int check_kind(Context& c, const char* kind, DWORD protect, int& checks) {
298 return 0; 298 return 0;
299} 299}
300 300
301// With imports on: a slot-133 buffer the layer does not import holds no import memory once
302// create_buffer_at_host_address has returned, whichever step declined it. The memory an import declined after its
303// allocation (one the driver put below the arena) used to wait in the deferred queue past the next submission, while
304// the shadow made instead over the same pages made them read-only: RADV then rejects every submission (found and
305// measured by NateWeav, #14). Two placements: at a page start (imported where the driver takes it) and 4 bytes into
306// a page (declined after the buffer exists wherever the buffer's alignment is above 4). Then a submission over the
307// shadow's pages, which must still succeed.
308int check_declined_imports(Context& c) {
309 const std::uint64_t before = rt::d3d12::title_host_imports(c.inner);
310 void* pages = VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
311 EXPECT(pages);
312 const D3D12_RESOURCE_DESC desc = buffer_desc(kPages / 2);
313 int shadows = 0;
314 for (const std::size_t at : {std::size_t(0), std::size_t(4)}) {
315 Ref<ID3D12Resource> buffer;
316 EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, static_cast<std::uint8_t*>(pages) + at,
317 desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p))));
318 const bool shadow = rt::d3d12::title_shadow_buffer(buffer.p);
319 shadows += shadow;
320 const std::uint64_t live = rt::d3d12::title_host_imports(c.inner);
321 std::printf("slot-133 buffer at page offset %zu: %s, %llu import(s) live\n", at,
322 shadow ? "declined (shadow)" : "imported", static_cast<unsigned long long>(live - before));
323 EXPECT(live == before + (shadow ? 0 : 1));
324 // A submission with the buffer alive: the shadow's tracker guards its pages here.
325 Ref<ID3D12CommandAllocator> allocator;
326 Ref<ID3D12GraphicsCommandList> list;
327 EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
328 IID_PPV_ARGS(&allocator.p))));
329 EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
330 IID_PPV_ARGS(&list.p))));
331 EXPECT(list->Close() == S_OK);
332 ID3D12CommandList* lists[] = {list.p};
333 c.queue->ExecuteCommandLists(1, lists);
334 EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success);
335 EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value)));
336 EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr)));
337 buffer.reset();
338 EXPECT(rt::d3d12::title_host_imports(c.inner) == before);
339 }
340 VirtualFree(pages, 0, MEM_RELEASE);
341 std::printf("declined imports: %d of 2 placements took the shadow, none left import memory behind\n", shadows);
342 return 0;
343}
344
345// With imports on: a page a shadow tracker watches and a live import shares stays writable across submissions. RADV
346// rejects every submission once a page under a live import is read-only (found and measured by NateWeav, #14), so an
347// import pins its pages (leonida::kernel_writes::hold) and the tracker passes over them. The shadow comes first: its
348// pages are read-only when the buffer is made, so the layer does not import them. Made writable again, the tracker
349// guards them at the next submission (the control); written, they are open again; then an import over the same pages,
350// and two submissions that must leave them writable.
351int check_import_over_shadow(Context& c) {
352 auto* pages = static_cast<std::uint8_t*>(
353 VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
354 EXPECT(pages);
355 const auto protection = [&] {
356 MEMORY_BASIC_INFORMATION region{};
357 return VirtualQuery(pages, &region, sizeof(region)) ? region.Protect & 0xFF : 0;
358 };
359 const auto submit = [&]() -> int {
360 Ref<ID3D12CommandAllocator> allocator;
361 Ref<ID3D12GraphicsCommandList> list;
362 EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
363 IID_PPV_ARGS(&allocator.p))));
364 EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
365 IID_PPV_ARGS(&list.p))));
366 EXPECT(list->Close() == S_OK);
367 ID3D12CommandList* lists[] = {list.p};
368 c.queue->ExecuteCommandLists(1, lists);
369 EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success);
370 EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value)));
371 EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr)));
372 return 0;
373 };
374 const D3D12_RESOURCE_DESC desc = buffer_desc(kPages);
375 DWORD old = 0;
376 EXPECT(VirtualProtect(pages, kPages, PAGE_READONLY, &old));
377 Ref<ID3D12Resource> shadow, import;
378 EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu,
379 IID_PPV_ARGS(&shadow.p))));
380 EXPECT(rt::d3d12::title_shadow_buffer(shadow.p));
381 EXPECT(VirtualProtect(pages, kPages, PAGE_READWRITE, &old));
382 if (submit()) return 1;
383 const bool guarded = protection() == PAGE_READONLY;
384 pages[0] = 1; // the tracker's fault handler opens the page again
385 EXPECT(protection() == PAGE_READWRITE);
386 const std::uint64_t imports = rt::d3d12::title_host_imports(c.inner);
387 EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu,
388 IID_PPV_ARGS(&import.p))));
389 const bool imported = !rt::d3d12::title_shadow_buffer(import.p);
390 std::size_t pinned = 0;
391 const auto begin = reinterpret_cast<std::uintptr_t>(pages);
392 leonida::kernel_writes::for_each_pin(begin, begin + kPages,
393 [&](std::uintptr_t from, std::uintptr_t to) { pinned += to - from; });
394 std::printf("import over a shadow's pages: the tracker %s them alone; the second buffer %s, %zu KiB pinned\n",
395 guarded ? "guarded" : "did not guard", imported ? "imported" : "declined (shadow)", pinned >> 10);
396 EXPECT(guarded); // the control: without a pin the tracker makes these pages read-only
397 if (!imported) {
398 EXPECT(pinned == 0 && rt::d3d12::title_host_imports(c.inner) == imports);
399 import.reset();
400 shadow.reset();
401 VirtualFree(pages, 0, MEM_RELEASE);
402 return 0;
403 }
404 EXPECT(pinned >= kPages && rt::d3d12::title_host_imports(c.inner) == imports + 1);
405 pages[1] = 2; // written again: the tracker would guard these pages at the next refresh
406 for (int i = 0; i < 2; ++i) {
407 if (submit()) return 1;
408 EXPECT(protection() == PAGE_READWRITE);
409 }
410 import.reset();
411 pinned = 0;
412 leonida::kernel_writes::for_each_pin(begin, begin + kPages,
413 [&](std::uintptr_t from, std::uintptr_t to) { pinned += to - from; });
414 EXPECT(pinned == 0); // the import's memory is freed: its pin ended
415 pages[2] = 3;
416 if (submit()) return 1;
417 EXPECT(protection() == PAGE_READONLY); // and the tracker guards the pages again
418 shadow.reset();
419 EXPECT(protection() == PAGE_READWRITE);
420 VirtualFree(pages, 0, MEM_RELEASE);
421 return 0;
422}
423
301// The title's own memory outside any slot-133 buffer: a VirtualAlloc range standing for its per-frame constant ring 424// The title's own memory outside any slot-133 buffer: a VirtualAlloc range standing for its per-frame constant ring
302// (#8862 section 3.5). Three ways a shader is given an address in it, each read back through an arena buffer: 425// (#8862 section 3.5). Three ways a shader is given an address in it, each read back through an arena buffer:
303// - a buffer V# the CPU writes into a shader-visible heap itself, as the title does (rewritten before the submission); 426// - a buffer V# the CPU writes into a shader-visible heap itself, as the title does (rewritten before the submission);
@@ -794,6 +917,8 @@ int main(int argc, char** argv) {
794 EXPECT(d.validation_errors() == 0); 917 EXPECT(d.validation_errors() == 0);
795 return 0; 918 return 0;
796 } 919 }
920 if (geometry && check_declined_imports(c)) return 1;
921 if (geometry && check_import_over_shadow(c)) return 1;
797 if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; 922 if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1;
798 if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1; 923 if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1;
799 if (check_title_memory(c, checks, geometry)) return 1; 924 if (check_title_memory(c, checks, geometry)) return 1;
diff --git a/runtime/test/kernel_writes_test.cpp b/runtime/test/kernel_writes_test.cpp
index 20b347748..070ae3488 100644
--- a/runtime/test/kernel_writes_test.cpp
+++ b/runtime/test/kernel_writes_test.cpp
@@ -1,7 +1,8 @@
1// leonida::kernel_writes::read_file (runtime/src/title_page_watch.h) into memory that is reserved until its first 1// leonida::kernel_writes::read_file (runtime/src/title_page_watch.h) into memory that is reserved until its first
2// touch, as xmem maps the title's physical pages (SEC_RESERVE section views committed by a fault handler): the kernel's 2// touch, as xmem maps the title's physical pages (SEC_RESERVE section views committed by a fault handler): the kernel's
3// write does not fault such a page in, so the read fails with ERROR_NOACCESS unless the committer runs first. No game 3// write does not fault such a page in, so the read fails with ERROR_NOACCESS unless the committer runs first. Then
4// data. 4// kernel_writes::hold, the pin a host import keeps over its pages: recorded with no opener set (no tracker yet), seen
5// by for_each_pin until release(), untouched by a file read's pin ending over the same pages. No game data.
5#include <windows.h> 6#include <windows.h>
6 7
7#include <cstdint> 8#include <cstdint>
@@ -27,6 +28,55 @@ constexpr DWORD kFileBytes = 256 * 1024;
27 28
28std::uint8_t* g_view = nullptr; 29std::uint8_t* g_view = nullptr;
29int g_commits = 0; 30int g_commits = 0;
31int g_opens = 0;
32std::uintptr_t g_opened_begin = 0, g_opened_end = 0;
33
34void count_open(std::uintptr_t begin, std::uintptr_t end) {
35 ++g_opens;
36 g_opened_begin = begin;
37 g_opened_end = end;
38}
39
40// The bytes of [begin, end) the pins cover.
41std::size_t pinned_bytes(std::uintptr_t begin, std::uintptr_t end) {
42 std::size_t bytes = 0;
43 leonida::kernel_writes::for_each_pin(begin, end, [&](std::uintptr_t from, std::uintptr_t to) { bytes += to - from; });
44 return bytes;
45}
46
47void check_holds() {
48 namespace kw = leonida::kernel_writes;
49 static std::uint8_t pages[3 * 4096];
50 const auto begin = reinterpret_cast<std::uintptr_t>(pages);
51 kw::set_opener(nullptr);
52 check(pinned_bytes(begin, begin + sizeof(pages)) == 0, "no pin before the hold");
53 check(kw::hold(pages, 0) == 0 && kw::hold(nullptr, 4096) == 0, "an empty hold pins nothing");
54 // No opener: begin_write records nothing, a hold does (a tracker made later must still pass over the pages).
55 check(kw::begin_write(pages, 4096, nullptr) == 0, "begin_write records nothing without an opener");
56 const std::uint64_t first = kw::hold(pages, 2 * 4096);
57 check(first != 0 && pinned_bytes(begin, begin + sizeof(pages)) == 2 * 4096,
58 "a hold without an opener pins its range");
59 check(pinned_bytes(begin + 2 * 4096, begin + sizeof(pages)) == 0, "and nothing past it");
60 // With an opener: the range is opened once the pin is in.
61 kw::set_opener(&count_open);
62 const std::uint64_t second = kw::hold(pages + 4096, 2 * 4096);
63 check(second != 0 && second != first && g_opens == 1 && g_opened_begin == begin + 4096 &&
64 g_opened_end == begin + 3 * 4096,
65 "a hold with an opener opens exactly its range");
66 // A file read's pin over the same pages ends without ending the holds.
67 const std::uint64_t read = kw::begin_write(pages, sizeof(pages), nullptr);
68 check(read != 0 && pinned_bytes(begin, begin + sizeof(pages)) == 2 * 4096 + 2 * 4096 + sizeof(pages),
69 "a file read's pin adds to the holds");
70 kw::end_write(read, false);
71 check(pinned_bytes(begin, begin + sizeof(pages)) == 4 * 4096, "its end leaves the holds");
72 kw::end_write(first, true); // as a pending overlapped read would: a hold has no OVERLAPPED, so it ends too
73 check(pinned_bytes(begin, begin + 4096) == 0 && pinned_bytes(begin + 4096, begin + sizeof(pages)) == 2 * 4096,
74 "ending one hold leaves the other");
75 kw::release(second);
76 kw::release(0);
77 check(pinned_bytes(begin, begin + sizeof(pages)) == 0, "released, no pin is left");
78 kw::set_opener(nullptr);
79}
30 80
31// Stands in for rt::xmem::commit_physical_range: commits the part of the test view the range covers. 81// Stands in for rt::xmem::commit_physical_range: commits the part of the test view the range covers.
32bool commit_view(const void* address, std::size_t bytes) { 82bool commit_view(const void* address, std::size_t bytes) {
@@ -80,6 +130,7 @@ int main() {
80 "a read into committed memory does not call the committer"); 130 "a read into committed memory does not call the committer");
81 131
82 leonida::kernel_writes::set_committer(nullptr); 132 leonida::kernel_writes::set_committer(nullptr);
133 check_holds();
83 UnmapViewOfFile(g_view); 134 UnmapViewOfFile(g_view);
84 CloseHandle(section); 135 CloseHandle(section);
85 CloseHandle(file); 136 CloseHandle(file);
diff --git a/runtime/test/silent_audio_test.cpp b/runtime/test/silent_audio_test.cpp
new file mode 100644
index 000000000..eac3121b9
--- /dev/null
+++ b/runtime/test/silent_audio_test.cpp
@@ -0,0 +1,728 @@
1// Tests for runtime/shims/silent_audio.cpp: the silent output endpoint behind CoCreateInstance(MMDeviceEnumerator).
2//
3// The host is a stand-in enumerator (with no endpoints, or with one), so no host audio device or sound server is ever
4// touched. The last case goes through the com_shim CoCreateInstance with LEONIDA_AUDIO=silent, which makes no host
5// enumerator for render questions.
6#include <windows.h>
7#include <objbase.h>
8#include <mmreg.h>
9#include <mmdeviceapi.h>
10#include <audioclient.h>
11#include <propsys.h>
12#include <spatialaudioclient.h>
13
14#include <cstdio>
15#include <cstring>
16#include <cwchar>
17
18#include "shims.h"
19#include "silent_audio.h"
20
21namespace {
22
23namespace sa = rt::silent_audio;
24
25int g_checks = 0;
26int g_failures = 0;
27
28void check(bool condition, const char* what) {
29 ++g_checks;
30 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
31 if (!condition) ++g_failures;
32}
33
34constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
35constexpr GUID kSubtypeFloat{0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
36constexpr PROPERTYKEY kKeyFriendlyName{{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}},
37 14};
38constexpr PROPERTYKEY kKeyDeviceFormat{{0xf19f064d, 0x082c, 0x4e27, {0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c}},
39 0};
40
41// ---- stand-in host -------------------------------------------------------------------------------------------
42
43class HostDevice final : public IMMDevice {
44public:
45 ULONG STDMETHODCALLTYPE AddRef() override { return static_cast<ULONG>(InterlockedIncrement(&refs_)); }
46 ULONG STDMETHODCALLTYPE Release() override {
47 const LONG n = InterlockedDecrement(&refs_);
48 if (n == 0) delete this;
49 return static_cast<ULONG>(n);
50 }
51 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
52 if (!ppv) return E_POINTER;
53 *ppv = nullptr;
54 if (!IsEqualIID(riid, __uuidof(IUnknown)) && !IsEqualIID(riid, __uuidof(IMMDevice))) return E_NOINTERFACE;
55 *ppv = this;
56 AddRef();
57 return S_OK;
58 }
59 HRESULT STDMETHODCALLTYPE Activate(REFIID, DWORD, PROPVARIANT*, void**) override { return E_NOTIMPL; }
60 HRESULT STDMETHODCALLTYPE OpenPropertyStore(DWORD, IPropertyStore**) override { return E_NOTIMPL; }
61 HRESULT STDMETHODCALLTYPE GetId(LPWSTR* id) override {
62 const wchar_t text[] = L"host-device";
63 *id = static_cast<wchar_t*>(CoTaskMemAlloc(sizeof text));
64 std::memcpy(*id, text, sizeof text);
65 return S_OK;
66 }
67 HRESULT STDMETHODCALLTYPE GetState(DWORD* state) override {
68 *state = DEVICE_STATE_ACTIVE;
69 return S_OK;
70 }
71
72private:
73 LONG refs_ = 1;
74};
75
76class HostCollection final : public IMMDeviceCollection {
77public:
78 explicit HostCollection(bool one) : one_(one) {}
79 ULONG STDMETHODCALLTYPE AddRef() override { return static_cast<ULONG>(InterlockedIncrement(&refs_)); }
80 ULONG STDMETHODCALLTYPE Release() override {
81 const LONG n = InterlockedDecrement(&refs_);
82 if (n == 0) delete this;
83 return static_cast<ULONG>(n);
84 }
85 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) override { return E_NOINTERFACE; }
86 HRESULT STDMETHODCALLTYPE GetCount(UINT* n) override {
87 *n = one_ ? 1 : 0;
88 return S_OK;
89 }
90 HRESULT STDMETHODCALLTYPE Item(UINT i, IMMDevice** d) override {
91 *d = nullptr;
92 if (!one_ || i != 0) return E_INVALIDARG;
93 *d = new HostDevice();
94 return S_OK;
95 }
96
97private:
98 LONG refs_ = 1;
99 bool one_;
100};
101
102// A host enumerator: with no endpoints at all (as a machine without an output), or with one render endpoint. It
103// counts what it was asked, per flow.
104class HostEnumerator final : public IMMDeviceEnumerator {
105public:
106 explicit HostEnumerator(bool has_render) : has_render_(has_render) {}
107 ULONG STDMETHODCALLTYPE AddRef() override { return static_cast<ULONG>(InterlockedIncrement(&refs_)); }
108 ULONG STDMETHODCALLTYPE Release() override {
109 const LONG n = InterlockedDecrement(&refs_);
110 if (n == 0) delete this;
111 return static_cast<ULONG>(n);
112 }
113 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
114 if (!ppv) return E_POINTER;
115 *ppv = nullptr;
116 if (!IsEqualIID(riid, __uuidof(IUnknown)) && !IsEqualIID(riid, __uuidof(IMMDeviceEnumerator)))
117 return E_NOINTERFACE;
118 *ppv = this;
119 AddRef();
120 return S_OK;
121 }
122 HRESULT STDMETHODCALLTYPE EnumAudioEndpoints(EDataFlow flow, DWORD, IMMDeviceCollection** out) override {
123 ++(flow == eCapture ? capture_calls : render_calls);
124 *out = new HostCollection(flow == eRender && has_render_);
125 return S_OK;
126 }
127 HRESULT STDMETHODCALLTYPE GetDefaultAudioEndpoint(EDataFlow flow, ERole, IMMDevice** out) override {
128 ++(flow == eCapture ? capture_calls : render_calls);
129 *out = nullptr;
130 if (flow != eRender || !has_render_) return kNotFound;
131 *out = new HostDevice();
132 return S_OK;
133 }
134 HRESULT STDMETHODCALLTYPE GetDevice(LPCWSTR, IMMDevice** out) override {
135 ++other_calls;
136 *out = nullptr;
137 return kNotFound;
138 }
139 HRESULT STDMETHODCALLTYPE RegisterEndpointNotificationCallback(IMMNotificationClient*) override {
140 ++other_calls;
141 return S_OK;
142 }
143 HRESULT STDMETHODCALLTYPE UnregisterEndpointNotificationCallback(IMMNotificationClient*) override {
144 ++other_calls;
145 return S_OK;
146 }
147 LONG refs() const { return refs_; }
148
149 int render_calls = 0;
150 int capture_calls = 0;
151 int other_calls = 0;
152
153private:
154 LONG refs_ = 1;
155 bool has_render_;
156};
157
158HostEnumerator* g_lazy_host = nullptr;
159int g_lazy_made = 0;
160IMMDeviceEnumerator* lazy_factory() {
161 ++g_lazy_made;
162 g_lazy_host->AddRef();
163 return g_lazy_host;
164}
165
166class Notifications final : public IMMNotificationClient {
167public:
168 ULONG STDMETHODCALLTYPE AddRef() override { return 2; }
169 ULONG STDMETHODCALLTYPE Release() override { return 1; }
170 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) override { return E_NOINTERFACE; }
171 HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR, DWORD) override { return ++calls, S_OK; }
172 HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR) override { return ++calls, S_OK; }
173 HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR) override { return ++calls, S_OK; }
174 HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow, ERole, LPCWSTR) override { return ++calls, S_OK; }
175 HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR, const PROPERTYKEY) override { return ++calls, S_OK; }
176 int calls = 0;
177};
178
179// ---- helpers --------------------------------------------------------------------------------------------------
180
181bool is_silent_device(IMMDevice* d) {
182 if (!d) return false;
183 LPWSTR id = nullptr;
184 const bool ok = SUCCEEDED(d->GetId(&id)) && id && std::wcscmp(id, sa::kDeviceId) == 0;
185 CoTaskMemFree(id);
186 return ok;
187}
188
189IMMDeviceEnumerator* serve(IMMDeviceEnumerator* host, HRESULT host_hr, sa::Mode mode, sa::HostFactory factory) {
190 IMMDeviceEnumerator* e = nullptr;
191 const HRESULT hr =
192 sa::serve_enumerator(host, host_hr, mode, factory, __uuidof(IMMDeviceEnumerator), reinterpret_cast<void**>(&e));
193 return SUCCEEDED(hr) ? e : nullptr;
194}
195
196UINT collection_count(IMMDeviceEnumerator* e, EDataFlow flow, DWORD mask, bool* silent_first = nullptr) {
197 IMMDeviceCollection* c = nullptr;
198 if (FAILED(e->EnumAudioEndpoints(flow, mask, &c)) || !c) return 0xFFFFFFFF;
199 UINT n = 0;
200 c->GetCount(&n);
201 if (silent_first) {
202 IMMDevice* d = nullptr;
203 *silent_first = n > 0 && SUCCEEDED(c->Item(0, &d)) && is_silent_device(d);
204 if (d) d->Release();
205 }
206 c->Release();
207 return n;
208}
209
210// ---- the enumerator -------------------------------------------------------------------------------------------
211
212void test_host_without_endpoints() {
213 auto* host = new HostEnumerator(false);
214 IMMDeviceEnumerator* e = serve(host, S_OK, sa::Mode::Auto, nullptr);
215 check(e != nullptr && e != host, "no host render endpoint: the wrapper answers, not the host");
216 if (!e) return;
217 const uint32_t served_before = sa::devices_served();
218
219 IMMDevice* d = nullptr;
220 check(e->GetDefaultAudioEndpoint(eRender, eConsole, &d) == S_OK && is_silent_device(d),
221 "GetDefaultAudioEndpoint(eRender, eConsole) is the silent device");
222 check(host->render_calls >= 1, "the host was asked first");
223 check(sa::devices_served() == served_before + 1, "one silent device handed out");
224 if (d) {
225 DWORD state = 0;
226 check(d->GetState(&state) == S_OK && state == DEVICE_STATE_ACTIVE, "the silent device is active");
227 IMMEndpoint* ep = nullptr;
228 EDataFlow flow = eCapture;
229 check(SUCCEEDED(d->QueryInterface(__uuidof(IMMEndpoint), reinterpret_cast<void**>(&ep))) &&
230 ep->GetDataFlow(&flow) == S_OK && flow == eRender,
231 "IMMEndpoint says eRender");
232 if (ep) ep->Release();
233
234 IPropertyStore* store = nullptr;
235 check(d->OpenPropertyStore(STGM_READWRITE, &store) == E_ACCESSDENIED && !store,
236 "the property store is read-only");
237 check(d->OpenPropertyStore(STGM_READ, &store) == S_OK && store, "OpenPropertyStore(STGM_READ)");
238 if (store) {
239 PROPVARIANT v;
240 PropVariantInit(&v);
241 check(store->GetValue(kKeyFriendlyName, &v) == S_OK && v.vt == VT_LPWSTR &&
242 std::wcscmp(v.pwszVal, sa::kFriendlyName) == 0,
243 "PKEY_Device_FriendlyName");
244 PropVariantClear(&v);
245 check(store->GetValue(kKeyDeviceFormat, &v) == S_OK && v.vt == VT_BLOB &&
246 v.blob.cbSize == sizeof(WAVEFORMATEXTENSIBLE),
247 "PKEY_AudioEngine_DeviceFormat is a WAVEFORMATEXTENSIBLE blob");
248 if (v.vt == VT_BLOB) {
249 const auto* f = reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(v.blob.pBlobData);
250 check(f->Format.nChannels == 8 && f->Format.nSamplesPerSec == 48000 && f->Format.wBitsPerSample == 32 &&
251 f->dwChannelMask == 0x63F && IsEqualGUID(f->SubFormat, kSubtypeFloat),
252 "device format: 48 kHz float 7.1");
253 }
254 PropVariantClear(&v);
255 DWORD n = 0;
256 check(store->GetCount(&n) == S_OK && n >= 2, "the store lists its keys");
257 store->Release();
258 }
259 d->Release();
260 }
261
262 bool silent_first = false;
263 check(collection_count(e, eRender, DEVICE_STATE_ACTIVE, &silent_first) == 1 && silent_first,
264 "EnumAudioEndpoints(eRender, ACTIVE) lists the silent device");
265 check(collection_count(e, eRender, DEVICE_STATE_DISABLED) == 0,
266 "EnumAudioEndpoints(eRender, DISABLED) lists nothing");
267 const int capture_before = host->capture_calls;
268 check(collection_count(e, eCapture, DEVICE_STATEMASK_ALL) == 0 && host->capture_calls == capture_before + 1,
269 "EnumAudioEndpoints(eCapture) is the host's answer");
270 check(collection_count(e, eAll, DEVICE_STATE_ACTIVE) == 1, "EnumAudioEndpoints(eAll) has the silent device");
271 check(e->GetDefaultAudioEndpoint(eCapture, eConsole, &d) == kNotFound && !d,
272 "GetDefaultAudioEndpoint(eCapture) is the host's answer");
273 check(e->GetDefaultAudioEndpoint(eAll, eConsole, &d) == E_INVALIDARG, "GetDefaultAudioEndpoint(eAll) is refused");
274 check(e->GetDevice(sa::kDeviceId, &d) == S_OK && is_silent_device(d), "GetDevice(silent id)");
275 if (d) d->Release();
276 d = nullptr;
277 check(e->GetDevice(L"host-device", &d) == kNotFound && host->other_calls == 1, "GetDevice(other id) goes to the host");
278
279 Notifications n;
280 check(e->RegisterEndpointNotificationCallback(&n) == S_OK, "RegisterEndpointNotificationCallback accepted");
281 check(e->UnregisterEndpointNotificationCallback(&n) == S_OK && n.calls == 0,
282 "UnregisterEndpointNotificationCallback; the callback never fired");
283 check(e->RegisterEndpointNotificationCallback(nullptr) == E_POINTER, "a null callback is E_POINTER");
284
285 e->Release();
286 check(host->refs() == 1, "the wrapper released the host");
287 host->Release();
288}
289
290void test_host_with_endpoint() {
291 auto* host = new HostEnumerator(true);
292 IMMDeviceEnumerator* e = serve(host, S_OK, sa::Mode::Auto, nullptr);
293 check(e == host, "a host with a render endpoint is returned unchanged");
294 if (e) e->Release();
295
296 const int render_before = host->render_calls;
297 e = serve(host, S_OK, sa::Mode::Silent, nullptr);
298 check(e != nullptr && e != host && host->render_calls == render_before,
299 "LEONIDA_AUDIO=silent: the wrapper answers without asking the host");
300 if (e) {
301 IMMDevice* d = nullptr;
302 check(e->GetDefaultAudioEndpoint(eRender, eMultimedia, &d) == S_OK && is_silent_device(d) &&
303 host->render_calls == render_before,
304 "forced: GetDefaultAudioEndpoint(eRender) is silent, the host's endpoint is not used");
305 if (d) d->Release();
306 bool silent_first = false;
307 check(collection_count(e, eRender, DEVICE_STATE_ACTIVE, &silent_first) == 1 && silent_first &&
308 host->render_calls == render_before,
309 "forced: EnumAudioEndpoints(eRender) lists only the silent device");
310 e->Release();
311 }
312 host->Release();
313}
314
315void test_no_host_enumerator() {
316 IMMDeviceEnumerator* e = serve(nullptr, REGDB_E_CLASSNOTREG, sa::Mode::Auto, nullptr);
317 check(e != nullptr, "no host enumerator: the wrapper still serves");
318 if (!e) return;
319 IMMDevice* d = nullptr;
320 check(e->GetDefaultAudioEndpoint(eRender, eConsole, &d) == S_OK && is_silent_device(d),
321 "no host enumerator: render is the silent device");
322 if (d) d->Release();
323 d = nullptr;
324 check(e->GetDefaultAudioEndpoint(eCapture, eConsole, &d) == kNotFound && !d,
325 "no host enumerator: capture is ERROR_NOT_FOUND");
326 check(collection_count(e, eCapture, DEVICE_STATE_ACTIVE) == 0, "no host enumerator: no capture devices");
327 e->Release();
328
329 // Forced, the host is made only when a capture question comes.
330 g_lazy_host = new HostEnumerator(true);
331 e = serve(nullptr, S_OK, sa::Mode::Silent, &lazy_factory);
332 if (e) {
333 check(e->GetDefaultAudioEndpoint(eRender, eConsole, &d) == S_OK && is_silent_device(d) && g_lazy_made == 0,
334 "forced: render makes no host enumerator");
335 if (d) d->Release();
336 d = nullptr;
337 e->GetDefaultAudioEndpoint(eCapture, eConsole, &d);
338 check(g_lazy_made == 1 && g_lazy_host->capture_calls == 1, "forced: a capture question makes the host's");
339 if (d) d->Release();
340 e->Release();
341 }
342 check(g_lazy_host->refs() == 1, "forced: the lazily made host is released");
343 g_lazy_host->Release();
344}
345
346// ---- the stream -----------------------------------------------------------------------------------------------
347
348IAudioClient* activate(IMMDevice* d, REFIID riid) {
349 void* out = nullptr;
350 return SUCCEEDED(d->Activate(riid, CLSCTX_ALL, nullptr, &out)) ? static_cast<IAudioClient*>(out) : nullptr;
351}
352
353void test_render_stream() {
354 IMMDeviceEnumerator* e = serve(nullptr, REGDB_E_CLASSNOTREG, sa::Mode::Auto, nullptr);
355 IMMDevice* d = nullptr;
356 if (!e || FAILED(e->GetDefaultAudioEndpoint(eRender, eConsole, &d)) || !d) {
357 check(false, "silent device for the stream tests");
358 return;
359 }
360 e->Release();
361
362 for (const IID& iid : {__uuidof(IAudioClient), __uuidof(IAudioClient2), __uuidof(IAudioClient3)}) {
363 IAudioClient* c = activate(d, iid);
364 check(c != nullptr, "Activate(IAudioClient / 2 / 3)");
365 if (c) c->Release();
366 }
367 void* other = reinterpret_cast<void*>(1);
368 check(d->Activate(__uuidof(IMMDeviceEnumerator), CLSCTX_ALL, nullptr, &other) == E_NOINTERFACE && !other,
369 "Activate(another interface) is E_NOINTERFACE");
370
371 IAudioClient3* c = nullptr;
372 d->Activate(__uuidof(IAudioClient3), CLSCTX_ALL, nullptr, reinterpret_cast<void**>(&c));
373 d->Release();
374 if (!c) return;
375
376 UINT32 frames = 0;
377 check(c->GetBufferSize(&frames) == AUDCLNT_E_NOT_INITIALIZED, "GetBufferSize before Initialize");
378 check(c->Start() == AUDCLNT_E_NOT_INITIALIZED, "Start before Initialize");
379
380 WAVEFORMATEX* mix = nullptr;
381 check(c->GetMixFormat(&mix) == S_OK && mix && mix->wFormatTag == WAVE_FORMAT_EXTENSIBLE && mix->nChannels == 8 &&
382 mix->nSamplesPerSec == 48000 && mix->wBitsPerSample == 32 && mix->nBlockAlign == 32,
383 "GetMixFormat: 48 kHz float, 8 channels");
384 if (!mix) return;
385 WAVEFORMATEX* closest = reinterpret_cast<WAVEFORMATEX*>(1);
386 check(c->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, mix, &closest) == S_OK && !closest,
387 "IsFormatSupported(mix format) is S_OK");
388 WAVEFORMATEX stereo{WAVE_FORMAT_PCM, 2, 44100, 44100 * 4, 4, 16, 0};
389 check(c->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &stereo, &closest) == S_FALSE && closest &&
390 closest->nChannels == 8,
391 "IsFormatSupported(stereo 44.1 kHz) is S_FALSE with the mix format");
392 CoTaskMemFree(closest);
393 check(c->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mix, nullptr) == AUDCLNT_E_UNSUPPORTED_FORMAT,
394 "no exclusive mode");
395 REFERENCE_TIME def = 0, minimum = 0;
396 check(c->GetDevicePeriod(&def, &minimum) == S_OK && def == 100000 && minimum > 0 && minimum <= def,
397 "GetDevicePeriod: 10 ms");
398
399 check(c->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, mix, nullptr) == S_OK,
400 "Initialize(shared, event callback, mix format)");
401 check(c->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, 0, 0, mix, nullptr) == AUDCLNT_E_ALREADY_INITIALIZED,
402 "a second Initialize is refused");
403 CoTaskMemFree(mix);
404 check(c->GetBufferSize(&frames) == S_OK && frames >= 960, "GetBufferSize: at least two periods");
405 REFERENCE_TIME latency = 0;
406 check(c->GetStreamLatency(&latency) == S_OK && latency > 0, "GetStreamLatency");
407 check(c->Start() == AUDCLNT_E_EVENTHANDLE_NOT_SET, "Start without an event handle is refused");
408
409 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
410 check(c->SetEventHandle(event) == S_OK, "SetEventHandle");
411
412 IAudioRenderClient* render = nullptr;
413 IAudioClock* clock = nullptr;
414 ISimpleAudioVolume* simple = nullptr;
415 IAudioStreamVolume* stream = nullptr;
416 check(c->GetService(__uuidof(IAudioRenderClient), reinterpret_cast<void**>(&render)) == S_OK && render,
417 "GetService(IAudioRenderClient)");
418 check(c->GetService(__uuidof(IAudioClock), reinterpret_cast<void**>(&clock)) == S_OK && clock,
419 "GetService(IAudioClock)");
420 check(c->GetService(__uuidof(ISimpleAudioVolume), reinterpret_cast<void**>(&simple)) == S_OK && simple,
421 "GetService(ISimpleAudioVolume)");
422 check(c->GetService(__uuidof(IAudioStreamVolume), reinterpret_cast<void**>(&stream)) == S_OK && stream,
423 "GetService(IAudioStreamVolume)");
424 if (!render || !clock || !simple || !stream) return;
425 UINT32 channels = 0;
426 float level = 0.0f;
427 check(stream->GetChannelCount(&channels) == S_OK && channels == 8 && stream->SetChannelVolume(7, 0.5f) == S_OK &&
428 stream->GetChannelVolume(7, &level) == S_OK && level == 0.5f,
429 "IAudioStreamVolume keeps a channel volume");
430 check(simple->SetMasterVolume(0.25f, nullptr) == S_OK && simple->GetMasterVolume(&level) == S_OK && level == 0.25f,
431 "ISimpleAudioVolume keeps the master volume");
432 UINT64 freq = 0;
433 check(clock->GetFrequency(&freq) == S_OK && freq == 48000, "IAudioClock counts frames at 48 kHz");
434
435 // Fill the whole buffer before Start, as a title primes its stream.
436 BYTE* data = nullptr;
437 check(render->ReleaseBuffer(1, 0) == AUDCLNT_E_OUT_OF_ORDER, "ReleaseBuffer without GetBuffer");
438 check(render->GetBuffer(frames + 1, &data) == AUDCLNT_E_BUFFER_TOO_LARGE, "GetBuffer larger than the buffer");
439 check(render->GetBuffer(frames, &data) == S_OK && data, "GetBuffer(whole buffer)");
440 if (data) std::memset(data, 0x7f, static_cast<size_t>(frames) * 32);
441 check(render->GetBuffer(1, &data) == AUDCLNT_E_OUT_OF_ORDER, "a second GetBuffer before ReleaseBuffer");
442 check(render->ReleaseBuffer(frames + 1, 0) == AUDCLNT_E_INVALID_SIZE, "ReleaseBuffer of more than was got");
443 check(render->ReleaseBuffer(frames, 0) == S_OK, "ReleaseBuffer(whole buffer)");
444 UINT32 padding = 0;
445 check(c->GetCurrentPadding(&padding) == S_OK && padding == frames, "padding is the whole buffer before Start");
446 Sleep(30);
447 check(c->GetCurrentPadding(&padding) == S_OK && padding == frames, "nothing drains before Start");
448 check(render->GetBuffer(1, &data) == AUDCLNT_E_BUFFER_TOO_LARGE, "a full buffer takes no more");
449
450 // Run for a few periods, refilling on every event, as an event-driven title does.
451 LARGE_INTEGER f, t0, t1;
452 QueryPerformanceFrequency(&f);
453 check(c->Start() == S_OK, "Start");
454 check(c->Start() == AUDCLNT_E_NOT_STOPPED, "a second Start is refused");
455 QueryPerformanceCounter(&t0);
456 int signals = 0;
457 UINT32 lowest = frames;
458 UINT64 written = frames;
459 for (int i = 0; i < 12; ++i) {
460 if (WaitForSingleObject(event, 500) != WAIT_OBJECT_0) break;
461 ++signals;
462 if (FAILED(c->GetCurrentPadding(&padding))) break;
463 if (padding < lowest) lowest = padding;
464 const UINT32 room = frames - padding;
465 if (room && SUCCEEDED(render->GetBuffer(room, &data))) {
466 std::memset(data, 0, static_cast<size_t>(room) * 32);
467 if (SUCCEEDED(render->ReleaseBuffer(room, 0))) written += room;
468 }
469 }
470 QueryPerformanceCounter(&t1);
471 const double seconds = static_cast<double>(t1.QuadPart - t0.QuadPart) / static_cast<double>(f.QuadPart);
472 std::printf(" 12 waits: %d signals in %.1f ms, lowest padding %u of %u, %llu frames written\n", signals,
473 seconds * 1000.0, lowest, frames, static_cast<unsigned long long>(written));
474 check(signals == 12, "the event is signalled every period while running");
475 check(seconds > 0.05 && seconds < 2.0, "the periods come at about real time (12 waits in 50 ms .. 2 s)");
476 check(lowest < frames, "the padding drains while running");
477 check(written > frames, "the drained room was refilled");
478 UINT64 pos = 0, qpc = 0;
479 check(clock->GetPosition(&pos, &qpc) == S_OK && pos > 0 && pos <= written && qpc > 0,
480 "IAudioClock position advances, never past what was written");
481 // The clock runs at the stream's rate: frames played track the time since Start (within the buffer).
482 const double expected = seconds * 48000.0;
483 check(static_cast<double>(pos) > expected * 0.5 && static_cast<double>(pos) <= expected * 1.5 + frames,
484 "the position follows real time at 48 kHz");
485
486 check(c->Stop() == S_OK, "Stop");
487 UINT32 stopped = 0, later = 0;
488 c->GetCurrentPadding(&stopped);
489 Sleep(30);
490 c->GetCurrentPadding(&later);
491 check(stopped == later, "nothing drains after Stop");
492 while (WaitForSingleObject(event, 0) == WAIT_OBJECT_0) {
493 }
494 check(WaitForSingleObject(event, 60) == WAIT_TIMEOUT, "no event after Stop");
495 check(c->Stop() == S_FALSE, "a second Stop is S_FALSE");
496 check(c->Reset() == S_OK && c->GetCurrentPadding(&padding) == S_OK && padding == 0, "Reset empties the buffer");
497 check(clock->GetPosition(&pos, nullptr) == S_OK && pos == 0, "Reset rewinds the clock");
498
499 stream->Release();
500 simple->Release();
501 clock->Release();
502 render->Release();
503 check(c->Release() == 0, "the client is released last");
504 CloseHandle(event);
505}
506
507void test_polled_stream_drains() {
508 IMMDeviceEnumerator* e = serve(nullptr, REGDB_E_CLASSNOTREG, sa::Mode::Auto, nullptr);
509 IMMDevice* d = nullptr;
510 if (!e || FAILED(e->GetDefaultAudioEndpoint(eRender, eConsole, &d)) || !d) return;
511 e->Release();
512 IAudioClient* c = activate(d, __uuidof(IAudioClient));
513 d->Release();
514 if (!c) return;
515 WAVEFORMATEX stereo{WAVE_FORMAT_IEEE_FLOAT, 2, 48000, 48000 * 8, 8, 32, 0};
516 check(c->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, 1000000, 0, &stereo, nullptr) == S_OK,
517 "Initialize(shared, polled, stereo float, 100 ms)");
518 HANDLE unexpected = CreateEventW(nullptr, FALSE, FALSE, nullptr);
519 check(c->SetEventHandle(unexpected) == AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED,
520 "SetEventHandle on a polled stream is refused");
521 CloseHandle(unexpected);
522 UINT32 frames = 0;
523 c->GetBufferSize(&frames);
524 check(frames >= 4800, "a 100 ms buffer holds 4800 frames");
525 IAudioRenderClient* render = nullptr;
526 c->GetService(__uuidof(IAudioRenderClient), reinterpret_cast<void**>(&render));
527 BYTE* data = nullptr;
528 if (render && SUCCEEDED(render->GetBuffer(frames, &data))) render->ReleaseBuffer(frames, AUDCLNT_BUFFERFLAGS_SILENT);
529 c->Start();
530 Sleep(50);
531 UINT32 padding = frames;
532 c->GetCurrentPadding(&padding);
533 check(padding < frames, "a polled stream drains on its clock");
534 Sleep(150);
535 c->GetCurrentPadding(&padding);
536 check(padding == 0, "a polled stream runs dry when nothing more is written");
537 c->Stop();
538 if (render) render->Release();
539 c->Release();
540}
541
542// ---- the spatial stream ---------------------------------------------------------------------------------------
543
544void test_spatial_stream() {
545 IMMDeviceEnumerator* e = serve(nullptr, REGDB_E_CLASSNOTREG, sa::Mode::Auto, nullptr);
546 IMMDevice* d = nullptr;
547 if (!e || FAILED(e->GetDefaultAudioEndpoint(eRender, eConsole, &d)) || !d) {
548 check(false, "silent device for the spatial tests");
549 return;
550 }
551 e->Release();
552 ISpatialAudioClient2* c2 = nullptr;
553 check(d->Activate(__uuidof(ISpatialAudioClient2), CLSCTX_ALL, nullptr, reinterpret_cast<void**>(&c2)) == S_OK && c2,
554 "Activate(ISpatialAudioClient2)");
555 if (c2) c2->Release();
556 ISpatialAudioClient* c = nullptr;
557 check(d->Activate(__uuidof(ISpatialAudioClient), CLSCTX_ALL, nullptr, reinterpret_cast<void**>(&c)) == S_OK && c,
558 "Activate(ISpatialAudioClient)");
559 d->Release();
560 if (!c) return;
561
562 AudioObjectType mask = AudioObjectType_None;
563 UINT32 dynamic = 99;
564 check(c->GetNativeStaticObjectTypeMask(&mask) == S_OK && static_cast<uint32_t>(mask) == 0x1FE,
565 "the native static objects are the 7.1 bed");
566 check(c->GetMaxDynamicObjectCount(&dynamic) == S_OK && dynamic == 0, "no dynamic objects");
567 float x = 0, y = 0, z = 0;
568 check(c->GetStaticObjectPosition(AudioObjectType_FrontLeft, &x, &y, &z) == S_OK && x < 0 && z < 0,
569 "front left is to the left and in front");
570 IAudioFormatEnumerator* formats = nullptr;
571 WAVEFORMATEX* format = nullptr;
572 UINT32 count = 0;
573 check(c->GetSupportedAudioObjectFormatEnumerator(&formats) == S_OK && formats &&
574 formats->GetCount(&count) == S_OK && count == 1 && formats->GetFormat(0, &format) == S_OK && format &&
575 format->nChannels == 1 && format->nSamplesPerSec == 48000 && format->wBitsPerSample == 32 &&
576 format->wFormatTag == WAVE_FORMAT_IEEE_FLOAT,
577 "one object format: mono 48 kHz float");
578 if (!format) return;
579 check(c->IsAudioObjectFormatSupported(format) == S_OK, "IsAudioObjectFormatSupported(its format)");
580 WAVEFORMATEX stereo{WAVE_FORMAT_IEEE_FLOAT, 2, 48000, 48000 * 8, 8, 32, 0};
581 check(c->IsAudioObjectFormatSupported(&stereo) == AUDCLNT_E_UNSUPPORTED_FORMAT, "a stereo object is refused");
582 UINT32 frames = 0;
583 check(c->GetMaxFrameCount(format, &frames) == S_OK && frames == 480, "GetMaxFrameCount: 480 (10 ms)");
584 check(c->IsSpatialAudioStreamAvailable(__uuidof(ISpatialAudioObjectRenderStream), nullptr) == S_OK,
585 "the object render stream is available");
586
587 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
588 SpatialAudioObjectRenderStreamActivationParams params{};
589 params.ObjectFormat = format;
590 params.StaticObjectTypeMask =
591 static_cast<AudioObjectType>(AudioObjectType_FrontLeft | AudioObjectType_FrontRight | AudioObjectType_LowFrequency);
592 params.Category = AudioCategory_GameEffects;
593 params.EventHandle = event;
594 PROPVARIANT pv;
595 PropVariantInit(&pv);
596 pv.vt = VT_BLOB;
597 pv.blob.cbSize = sizeof params;
598 pv.blob.pBlobData = reinterpret_cast<BYTE*>(&params);
599 ISpatialAudioObjectRenderStream* stream = nullptr;
600 params.EventHandle = nullptr;
601 check(c->ActivateSpatialAudioStream(&pv, __uuidof(ISpatialAudioObjectRenderStream),
602 reinterpret_cast<void**>(&stream)) == E_INVALIDARG && !stream,
603 "a stream without an event handle is refused");
604 params.EventHandle = event;
605 check(c->ActivateSpatialAudioStream(&pv, __uuidof(ISpatialAudioObjectRenderStream),
606 reinterpret_cast<void**>(&stream)) == S_OK && stream,
607 "ActivateSpatialAudioStream(FL | FR | LFE, event)");
608 formats->Release();
609 c->Release();
610 if (!stream) return;
611
612 UINT32 available = 99;
613 check(stream->BeginUpdatingAudioObjects(&available, &frames) == S_OK && available == 0 && frames == 480,
614 "BeginUpdatingAudioObjects: 480 frames, no dynamic objects");
615 check(stream->BeginUpdatingAudioObjects(&available, &frames) == SPTLAUDCLNT_E_OUT_OF_ORDER,
616 "a second Begin is out of order");
617 ISpatialAudioObject* fl = nullptr;
618 ISpatialAudioObject* fr = nullptr;
619 ISpatialAudioObject* other = nullptr;
620 check(stream->ActivateSpatialAudioObject(AudioObjectType_FrontLeft, &fl) == S_OK && fl, "activate front left");
621 check(stream->ActivateSpatialAudioObject(AudioObjectType_FrontRight, &fr) == S_OK && fr, "activate front right");
622 check(stream->ActivateSpatialAudioObject(AudioObjectType_FrontLeft, &other) == SPTLAUDCLNT_E_OBJECT_ALREADY_ACTIVE,
623 "front left twice is refused");
624 check(stream->ActivateSpatialAudioObject(AudioObjectType_BackLeft, &other) ==
625 SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE,
626 "a type outside the stream's mask is refused");
627 check(stream->ActivateSpatialAudioObject(AudioObjectType_Dynamic, &other) == SPTLAUDCLNT_E_NO_MORE_OBJECTS,
628 "no dynamic object");
629 check(stream->EndUpdatingAudioObjects() == S_OK, "EndUpdatingAudioObjects");
630 check(stream->EndUpdatingAudioObjects() == SPTLAUDCLNT_E_OUT_OF_ORDER, "a second End is out of order");
631 if (!fl || !fr) return;
632 BYTE* buffer = nullptr;
633 UINT32 length = 0;
634 check(fl->GetBuffer(&buffer, &length) == SPTLAUDCLNT_E_OUT_OF_ORDER, "GetBuffer outside an update");
635
636 check(stream->Start() == S_OK, "Start");
637 LARGE_INTEGER f, t0, t1;
638 QueryPerformanceFrequency(&f);
639 QueryPerformanceCounter(&t0);
640 int passes = 0;
641 bool buffers_ok = true;
642 for (int i = 0; i < 10; ++i) {
643 if (WaitForSingleObject(event, 500) != WAIT_OBJECT_0) break;
644 if (FAILED(stream->BeginUpdatingAudioObjects(&available, &frames))) break;
645 for (ISpatialAudioObject* o : {fl, fr}) {
646 buffer = nullptr;
647 length = 0;
648 if (FAILED(o->GetBuffer(&buffer, &length)) || !buffer || length != frames * 4) buffers_ok = false;
649 else std::memset(buffer, 0, length);
650 o->SetVolume(0.5f);
651 o->SetPosition(0.0f, 0.0f, -1.0f);
652 }
653 if (i == 9) fr->SetEndOfStream(0);
654 if (SUCCEEDED(stream->EndUpdatingAudioObjects())) ++passes;
655 }
656 QueryPerformanceCounter(&t1);
657 const double seconds = static_cast<double>(t1.QuadPart - t0.QuadPart) / static_cast<double>(f.QuadPart);
658 std::printf(" spatial: %d passes in %.1f ms\n", passes, seconds * 1000.0);
659 check(passes == 10, "the spatial event is signalled every pass while running");
660 check(seconds > 0.04 && seconds < 2.0, "the passes come at about real time (10 in 40 ms .. 2 s)");
661 check(buffers_ok, "every object gets a 480-frame mono float buffer in each pass");
662 BOOL active = TRUE;
663 check(fr->IsActive(&active) == S_OK && !active, "an object is inactive after the pass it ended in");
664 check(fl->IsActive(&active) == S_OK && active, "the other object stays active");
665 check(stream->Reset() == SPTLAUDCLNT_E_STREAM_NOT_STOPPED, "Reset while running is refused");
666 check(stream->Stop() == S_OK, "Stop");
667 while (WaitForSingleObject(event, 0) == WAIT_OBJECT_0) {
668 }
669 check(WaitForSingleObject(event, 60) == WAIT_TIMEOUT, "no spatial event after Stop");
670 check(stream->Reset() == S_OK, "Reset");
671 fr->Release();
672 if (SUCCEEDED(stream->BeginUpdatingAudioObjects(&available, &frames))) {
673 check(stream->ActivateSpatialAudioObject(AudioObjectType_FrontRight, &other) == S_OK && other,
674 "an ended type can be activated again");
675 if (other) other->Release();
676 stream->EndUpdatingAudioObjects();
677 }
678 fl->Release();
679 check(stream->Release() == 0, "the stream is released last");
680 CloseHandle(event);
681}
682
683// ---- through CoCreateInstance ---------------------------------------------------------------------------------
684
685using CoCreateInstFn = HRESULT(WINAPI*)(REFCLSID, LPUNKNOWN, DWORD, REFIID, LPVOID*);
686
687void test_co_create_instance_forced() {
688 auto create = reinterpret_cast<CoCreateInstFn>(rt::shims::find("api-ms-win-core-com-l1-1-0.dll", "CoCreateInstance"));
689 check(create != nullptr, "CoCreateInstance resolves");
690 if (!create) return;
691 const HRESULT init = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
692 // Forced: no host enumerator is made for a render question, so this touches no host audio at all.
693 SetEnvironmentVariableA("LEONIDA_AUDIO", "Silent");
694 check(sa::mode_from_env() == sa::Mode::Silent, "LEONIDA_AUDIO=Silent is the silent mode (any case)");
695 IMMDeviceEnumerator* e = nullptr;
696 const HRESULT hr = create(sa::kClsidMMDeviceEnumerator, nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
697 reinterpret_cast<void**>(&e));
698 check(SUCCEEDED(hr) && e, "CoCreateInstance(MMDeviceEnumerator) with LEONIDA_AUDIO=silent");
699 if (e) {
700 IMMDevice* d = nullptr;
701 check(e->GetDefaultAudioEndpoint(eRender, eConsole, &d) == S_OK && is_silent_device(d),
702 "LEONIDA_AUDIO=silent: the default render endpoint is the silent one");
703 IAudioClient* c = d ? activate(d, __uuidof(IAudioClient)) : nullptr;
704 check(c != nullptr, "and it activates an IAudioClient");
705 if (c) c->Release();
706 if (d) d->Release();
707 e->Release();
708 }
709 SetEnvironmentVariableA("LEONIDA_AUDIO", "host");
710 check(sa::mode_from_env() == sa::Mode::Auto, "any other LEONIDA_AUDIO value is the default");
711 SetEnvironmentVariableA("LEONIDA_AUDIO", nullptr);
712 check(sa::mode_from_env() == sa::Mode::Auto, "unset LEONIDA_AUDIO is the default");
713 if (SUCCEEDED(init)) CoUninitialize();
714}
715
716} // namespace
717
718int main() {
719 test_host_without_endpoints();
720 test_host_with_endpoint();
721 test_no_host_enumerator();
722 test_render_stream();
723 test_polled_stream_drains();
724 test_spatial_stream();
725 test_co_create_instance_forced();
726 std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures);
727 return g_failures ? 1 : 0;
728}