feat(videoOut): add tiled buffer presentation and flip lifecycle handling

This commit is contained in:
boykopovar
2026-09-14 12:38:16 +03:00
parent b9cc7ffd85
commit fd5e236aad
16 changed files with 504 additions and 77 deletions
@@ -1,4 +1,5 @@
add_library(libSceAgcDriver SHARED EXCLUDE_FROM_ALL
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/DisplayBuffer.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/GuestMemory.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Pm4.cpp
@@ -0,0 +1,26 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DISPLAYBUFFER_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DISPLAYBUFFER_HPP
#include <cstddef>
#include <cstdint>
#include <span>
#include <vector>
namespace AgcDriver {
struct DisplayBuffer {
std::uint64_t address;
std::uint64_t pixelFormat;
std::uint32_t width;
std::uint32_t height;
};
std::size_t DisplayBufferSize(const DisplayBuffer& buffer);
std::vector<std::byte> DecodeDisplayBuffer(const DisplayBuffer& buffer, std::span<const std::byte> source);
std::vector<std::byte> ReadDisplayBuffer(const DisplayBuffer& buffer);
}
extern "C" std::size_t AgcDriverDisplayBufferSize_nid_postfix(const AgcDriver::DisplayBuffer& buffer);
#endif
@@ -13,4 +13,6 @@ void Write(std::uint64_t address, std::span<const std::byte> source, std::size_t
}
extern "C" void AgcDriverCheckGuestMemory_nid_postfix(const void* pointer, std::size_t bytes, std::size_t alignment, bool writable = false);
#endif
@@ -6,6 +6,7 @@
#include <cstdint>
#include <exception>
#include <span>
#include "prx/libSceAgcDriver/Execution/include/DisplayBuffer.hpp"
namespace AgcDriver {
@@ -20,6 +21,7 @@ struct PresentationWindow {
}
extern "C" void AgcDriverPresentClear_nid_postfix(const AgcDriver::PresentationWindow& window, bool opaque, void (*gpuReady)(void*), void* context);
extern "C" void AgcDriverPresentBuffer_nid_postfix(const AgcDriver::PresentationWindow& window, const AgcDriver::DisplayBuffer& buffer, void (*gpuReady)(void*), void* context);
extern "C" void AgcDriverReleaseWindow_nid_postfix(void* window);
extern "C" void AgcDriverReportFailure_nid_postfix(std::exception_ptr error);
@@ -18,11 +18,14 @@ public:
ShaderRecompiler::SpirvTarget Target() const;
void WaitIdle();
void* Window() const;
void Resize(std::uint32_t width, std::uint32_t height);
std::uint64_t PresentClear(std::uint32_t width, std::uint32_t height, bool opaque);
std::uint64_t PresentPixels(std::uint32_t width, std::uint32_t height, std::span<const std::byte> pixels);
void WaitPresented(std::uint64_t id);
void Dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z);
private:
std::uint64_t present(std::uint32_t width, std::uint32_t height, bool opaque, std::span<const std::byte> pixels);
struct State;
std::unique_ptr<State> state;
};
@@ -0,0 +1,58 @@
#include "prx/libSceAgcDriver/Execution/include/DisplayBuffer.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include <cstring>
#include <limits>
#include <stdexcept>
namespace AgcDriver {
namespace {
void require(bool condition, const char* reason) {
if (!condition) throw std::runtime_error(reason);
}
std::uint32_t tileOffset(std::uint32_t x, std::uint32_t y) {
return ((y << 4u) & 0x0070u) ^ ((y << 5u) & 0x0f00u) ^ ((y << 9u) & 0x1000u) ^ ((y << 8u) & 0x4000u) ^ ((x << 2u) & 0x000cu) ^ ((x << 5u) & 0x0380u) ^ ((x << 4u) & 0x0400u) ^ ((x << 6u) & 0x0800u) ^ ((x << 9u) & 0xa000u);
}
}
std::size_t DisplayBufferSize(const DisplayBuffer& buffer) {
require(buffer.width != 0 && buffer.height != 0 && buffer.width <= 16384 && buffer.height <= 16384, "VideoOut: invalid display buffer dimensions");
require(buffer.pixelFormat == 0x8000000000000000ull || buffer.pixelFormat == 0x8000000022000000ull, "VideoOut: unsupported display pixel format");
require(buffer.address != 0 && (buffer.address & 65535u) == 0, "VideoOut: display buffer requires 64 KiB alignment");
const auto size = static_cast<std::uint64_t>((buffer.width + 127u) / 128u) * ((buffer.height + 127u) / 128u) * 65536u;
require(size <= std::numeric_limits<std::size_t>::max() && size <= std::numeric_limits<std::uintptr_t>::max() - buffer.address, "VideoOut: display buffer range overflow");
return static_cast<std::size_t>(size);
}
std::vector<std::byte> DecodeDisplayBuffer(const DisplayBuffer& buffer, std::span<const std::byte> source) {
require(source.size() == DisplayBufferSize(buffer), "VideoOut: invalid tiled display buffer size");
std::vector<std::byte> pixels(static_cast<std::size_t>(buffer.width) * buffer.height * 4);
const auto blocksPerRow = (buffer.width + 127u) / 128u;
const bool rgba = buffer.pixelFormat == 0x8000000022000000ull;
for (std::uint32_t y = 0; y < buffer.height; ++y) {
for (std::uint32_t x = 0; x < buffer.width; ++x) {
const auto tiled = (static_cast<std::size_t>(y / 128u) * blocksPerRow + x / 128u) * 65536u + tileOffset(x, y);
const auto linear = (static_cast<std::size_t>(y) * buffer.width + x) * 4;
pixels[linear] = source[tiled + (rgba ? 2 : 0)];
pixels[linear + 1] = source[tiled + 1];
pixels[linear + 2] = source[tiled + (rgba ? 0 : 2)];
pixels[linear + 3] = source[tiled + 3];
}
}
return pixels;
}
std::vector<std::byte> ReadDisplayBuffer(const DisplayBuffer& buffer) {
const auto size = DisplayBufferSize(buffer);
GuestMemory::CheckRange(reinterpret_cast<const void*>(buffer.address), size, 65536);
const auto* source = reinterpret_cast<const std::byte*>(buffer.address);
return DecodeDisplayBuffer(buffer, {source, size});
}
}
extern "C" std::size_t AgcDriverDisplayBufferSize_nid_postfix(const AgcDriver::DisplayBuffer& buffer) {
return AgcDriver::DisplayBufferSize(buffer);
}
@@ -189,7 +189,7 @@ public:
changed.notify_all();
}
void PresentClear(const PresentationWindow& window, bool opaque, void (*gpuReady)(void*), void* context) {
void Present(const PresentationWindow& window, const DisplayBuffer* buffer, bool opaque, void (*gpuReady)(void*), void* context) {
CheckFailure();
require(gpuReady != nullptr && context != nullptr, "missing GPU completion callback");
std::shared_ptr<VulkanDevice> presenting;
@@ -203,7 +203,15 @@ public:
}
require(device->Window() == window.context, "presentation window does not match device surface");
presenting = device;
id = presenting->PresentClear(window.width, window.height, opaque);
presenting->Resize(window.width, window.height);
if (buffer != nullptr) {
require(buffer->width == window.width && buffer->height == window.height, "display buffer extent differs from output");
presenting->WaitIdle();
const auto pixels = ReadDisplayBuffer(*buffer);
id = presenting->PresentPixels(window.width, window.height, pixels);
} else {
id = presenting->PresentClear(window.width, window.height, opaque);
}
}
gpuReady(context);
presenting->WaitPresented(id);
@@ -474,7 +482,11 @@ void UnregisterVideoOutput(std::uint32_t handle, const std::shared_ptr<IVideoOut
}
void PresentClear(const PresentationWindow& window, bool opaque, void (*gpuReady)(void*), void* context) {
Driver::Get().PresentClear(window, opaque, gpuReady, context);
Driver::Get().Present(window, nullptr, opaque, gpuReady, context);
}
void PresentBuffer(const PresentationWindow& window, const DisplayBuffer& buffer, void (*gpuReady)(void*), void* context) {
Driver::Get().Present(window, &buffer, true, gpuReady, context);
}
void ReleaseWindow(void* window) {
@@ -511,6 +523,10 @@ extern "C" void AgcDriverPresentClear_nid_postfix(const AgcDriver::PresentationW
AgcDriver::PresentClear(window, opaque, gpuReady, context);
}
extern "C" void AgcDriverPresentBuffer_nid_postfix(const AgcDriver::PresentationWindow& window, const AgcDriver::DisplayBuffer& buffer, void (*gpuReady)(void*), void* context) {
AgcDriver::PresentBuffer(window, buffer, gpuReady, context);
}
extern "C" void AgcDriverReleaseWindow_nid_postfix(void* window) {
AgcDriver::ReleaseWindow(window);
}
@@ -75,3 +75,7 @@ void Write(std::uint64_t address, std::span<const std::byte> source, std::size_t
}
}
extern "C" void AgcDriverCheckGuestMemory_nid_postfix(const void* pointer, std::size_t bytes, std::size_t alignment, bool writable) {
AgcDriver::GuestMemory::CheckRange(pointer, bytes, alignment, writable);
}
@@ -30,6 +30,7 @@ struct VulkanDevice::State {
PFN_vkGetDeviceProcAddr deviceProc = nullptr;
VkInstance instance = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkPhysicalDevice physical = VK_NULL_HANDLE;
VkQueue queue = VK_NULL_HANDLE;
VkCommandPool pool = VK_NULL_HANDLE;
void* window = nullptr;
@@ -44,6 +45,11 @@ struct VulkanDevice::State {
VkCommandBuffer clearCommands = VK_NULL_HANDLE;
std::uint64_t presentId = 0;
bool presentQueued = false;
VkPhysicalDeviceMemoryProperties memoryProperties{};
VkBuffer uploadBuffer = VK_NULL_HANDLE;
VkDeviceMemory uploadMemory = VK_NULL_HANDLE;
void* uploadMapping = nullptr;
VkDeviceSize uploadSize = 0;
VkPhysicalDeviceProperties properties{};
VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES};
std::array<std::uint32_t, 1> capabilities{1};
@@ -66,6 +72,42 @@ struct VulkanDevice::State {
return function;
}
void Upload(std::span<const std::byte> pixels) {
if (uploadSize < pixels.size()) {
if (uploadMapping) DeviceFunction<PFN_vkUnmapMemory>("vkUnmapMemory")(device, uploadMemory);
uploadMapping = nullptr;
if (uploadBuffer) DeviceFunction<PFN_vkDestroyBuffer>("vkDestroyBuffer")(device, uploadBuffer, nullptr);
uploadBuffer = VK_NULL_HANDLE;
if (uploadMemory) DeviceFunction<PFN_vkFreeMemory>("vkFreeMemory")(device, uploadMemory, nullptr);
uploadMemory = VK_NULL_HANDLE;
uploadSize = 0;
VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
buffer.size = pixels.size();
buffer.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
buffer.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
check(DeviceFunction<PFN_vkCreateBuffer>("vkCreateBuffer")(device, &buffer, nullptr, &uploadBuffer), "vkCreateBuffer display upload");
VkMemoryRequirements requirements{};
DeviceFunction<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(device, uploadBuffer, &requirements);
std::uint32_t memoryType = memoryProperties.memoryTypeCount;
const auto flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
for (std::uint32_t i = 0; i < memoryProperties.memoryTypeCount; ++i) {
if ((requirements.memoryTypeBits & (1u << i)) != 0 && (memoryProperties.memoryTypes[i].propertyFlags & flags) == flags) {
memoryType = i;
break;
}
}
require(memoryType < memoryProperties.memoryTypeCount, "coherent host upload memory is unavailable");
VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocation.allocationSize = requirements.size;
allocation.memoryTypeIndex = memoryType;
check(DeviceFunction<PFN_vkAllocateMemory>("vkAllocateMemory")(device, &allocation, nullptr, &uploadMemory), "vkAllocateMemory display upload");
check(DeviceFunction<PFN_vkBindBufferMemory>("vkBindBufferMemory")(device, uploadBuffer, uploadMemory, 0), "vkBindBufferMemory display upload");
check(DeviceFunction<PFN_vkMapMemory>("vkMapMemory")(device, uploadMemory, 0, pixels.size(), 0, &uploadMapping), "vkMapMemory display upload");
uploadSize = pixels.size();
}
std::memcpy(uploadMapping, pixels.data(), pixels.size());
}
~State() {
if (device != VK_NULL_HANDLE) {
const auto idle = reinterpret_cast<PFN_vkDeviceWaitIdle>(deviceProc(device, "vkDeviceWaitIdle"))(device);
@@ -79,6 +121,9 @@ struct VulkanDevice::State {
if (renderFence) destroyFence(device, renderFence, nullptr);
if (presentFence) destroyFence(device, presentFence, nullptr);
if (rendered) reinterpret_cast<PFN_vkDestroySemaphore>(deviceProc(device, "vkDestroySemaphore"))(device, rendered, nullptr);
if (uploadMapping) reinterpret_cast<PFN_vkUnmapMemory>(deviceProc(device, "vkUnmapMemory"))(device, uploadMemory);
if (uploadBuffer) reinterpret_cast<PFN_vkDestroyBuffer>(deviceProc(device, "vkDestroyBuffer"))(device, uploadBuffer, nullptr);
if (uploadMemory) reinterpret_cast<PFN_vkFreeMemory>(deviceProc(device, "vkFreeMemory"))(device, uploadMemory, nullptr);
if (swapchain) reinterpret_cast<PFN_vkDestroySwapchainKHR>(deviceProc(device, "vkDestroySwapchainKHR"))(device, swapchain, nullptr);
const auto destroyPool = reinterpret_cast<PFN_vkDestroyCommandPool>(deviceProc(device, "vkDestroyCommandPool"));
const auto destroyDevice = reinterpret_cast<PFN_vkDestroyDevice>(deviceProc(device, "vkDestroyDevice"));
@@ -205,6 +250,8 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window) : state(std::make_u
properties.pNext = &state->subgroup;
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(selected, &properties);
state->properties = properties.properties;
state->physical = selected;
state->InstanceFunction<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(selected, &state->memoryProperties);
const float priority = 1.0f;
VkDeviceQueueCreateInfo queueInfo{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
queueInfo.queueFamilyIndex = family;
@@ -287,11 +334,56 @@ void* VulkanDevice::Window() const {
return state->window;
}
void VulkanDevice::Resize(std::uint32_t width, std::uint32_t height) {
require(state->swapchain != VK_NULL_HANDLE && !state->presentQueued, "cannot resize an unavailable or pending swapchain");
if (state->extent.width == width && state->extent.height == height) return;
WaitIdle();
VkSurfaceCapabilitiesKHR surface{};
check(state->InstanceFunction<PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR>("vkGetPhysicalDeviceSurfaceCapabilitiesKHR")(state->physical, state->surface, &surface), "vkGetPhysicalDeviceSurfaceCapabilitiesKHR resize");
require(surface.currentExtent.width == std::numeric_limits<std::uint32_t>::max() || (surface.currentExtent.width == width && surface.currentExtent.height == height), "resized surface extent differs from output");
require(width >= surface.minImageExtent.width && width <= surface.maxImageExtent.width && height >= surface.minImageExtent.height && height <= surface.maxImageExtent.height, "unsupported resized output extent");
require((surface.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) != 0 && (surface.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) != 0 && (surface.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) != 0, "resized surface capabilities are unsupported");
VkSwapchainCreateInfoKHR create{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR};
create.surface = state->surface;
create.minImageCount = surface.minImageCount;
create.imageFormat = VK_FORMAT_B8G8R8A8_UNORM;
create.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
create.imageExtent = {width, height};
create.imageArrayLayers = 1;
create.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
create.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
create.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
create.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
create.presentMode = VK_PRESENT_MODE_FIFO_KHR;
create.oldSwapchain = state->swapchain;
VkSwapchainKHR replacement = VK_NULL_HANDLE;
check(state->DeviceFunction<PFN_vkCreateSwapchainKHR>("vkCreateSwapchainKHR")(state->device, &create, nullptr, &replacement), "vkCreateSwapchainKHR resize");
state->DeviceFunction<PFN_vkDestroySwapchainKHR>("vkDestroySwapchainKHR")(state->device, state->swapchain, nullptr);
state->swapchain = replacement;
state->extent = create.imageExtent;
auto getImages = state->DeviceFunction<PFN_vkGetSwapchainImagesKHR>("vkGetSwapchainImagesKHR");
std::uint32_t count = 0;
check(getImages(state->device, replacement, &count, nullptr), "vkGetSwapchainImagesKHR resize");
state->images.resize(count);
check(getImages(state->device, replacement, &count, state->images.data()), "vkGetSwapchainImagesKHR resize");
}
std::uint64_t VulkanDevice::PresentClear(std::uint32_t width, std::uint32_t height, bool opaque) {
return present(width, height, opaque, {});
}
std::uint64_t VulkanDevice::PresentPixels(std::uint32_t width, std::uint32_t height, std::span<const std::byte> pixels) {
require(width != 0 && height != 0 && width <= 16384 && height <= 16384, "invalid display image extent");
require(pixels.size() == static_cast<std::uint64_t>(width) * height * 4, "invalid display pixel buffer size");
return present(width, height, true, pixels);
}
std::uint64_t VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaque, std::span<const std::byte> pixels) {
require(state->swapchain != VK_NULL_HANDLE, "device has no swapchain");
require(width == state->extent.width && height == state->extent.height, "output resize is not implemented");
require(!state->presentQueued, "previous presentation has not completed");
require(state->presentId != std::numeric_limits<std::uint64_t>::max(), "presentation ID overflow");
if (!pixels.empty()) state->Upload(pixels);
auto wait = state->DeviceFunction<PFN_vkWaitForFences>("vkWaitForFences");
auto reset = state->DeviceFunction<PFN_vkResetFences>("vkResetFences");
const std::array<VkFence, 3> fences{state->acquireFence, state->renderFence, state->presentFence};
@@ -315,9 +407,16 @@ std::uint64_t VulkanDevice::PresentClear(std::uint32_t width, std::uint32_t heig
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
auto pipelineBarrier = state->DeviceFunction<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
pipelineBarrier(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
VkClearColorValue clear{};
clear.float32[3] = opaque ? 1.0f : 0.0f;
state->DeviceFunction<PFN_vkCmdClearColorImage>("vkCmdClearColorImage")(commands, barrier.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clear, 1, &barrier.subresourceRange);
if (pixels.empty()) {
VkClearColorValue clear{};
clear.float32[3] = opaque ? 1.0f : 0.0f;
state->DeviceFunction<PFN_vkCmdClearColorImage>("vkCmdClearColorImage")(commands, barrier.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clear, 1, &barrier.subresourceRange);
} else {
VkBufferImageCopy copy{};
copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
copy.imageExtent = {width, height, 1};
state->DeviceFunction<PFN_vkCmdCopyBufferToImage>("vkCmdCopyBufferToImage")(commands, state->uploadBuffer, barrier.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy);
}
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = 0;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
+2 -1
View File
@@ -11,6 +11,7 @@ target_include_directories(libSceVideoOut PRIVATE
${CMAKE_SOURCE_DIR}/3rdparty/Vulkan-Headers/include
)
target_link_libraries(libSceVideoOut PRIVATE libSceAgcDriver libc libkernel SDL2-static)
set_target_properties(libSceVideoOut PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(libSceVideoOut)
foreach(runtimeLinkFlag IN ITEMS -static-libgcc -static-libstdc++ -static)
@@ -18,6 +19,6 @@ foreach(runtimeLinkFlag IN ITEMS -static-libgcc -static-libstdc++ -static)
endforeach()
add_executable(video_out_flip_tests EXCLUDE_FROM_ALL tests/Flip.cpp)
target_include_directories(video_out_flip_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/3rdparty/SDL2/include)
target_link_libraries(video_out_flip_tests PRIVATE libSceVideoOut libSceAgcDriver libc)
target_link_libraries(video_out_flip_tests PRIVATE libSceVideoOut libSceAgcDriver libkernel libc)
set_target_properties(video_out_flip_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(video_out_flip_tests)
@@ -1,5 +1,5 @@
#ifndef CORE_LIBS_PRX_LIBSCEVIDEOUOUT_INCLUDE_VIDEOOUTDRIVER_HPP
#define CORE_LIBS_PRX_LIBSCEVIDEOUOUT_INCLUDE_VIDEOOUTDRIVER_HPP
#ifndef CORE_LIBS_PRX_LIBSCEVIDEOOUT_INCLUDE_VIDEOOUTDRIVER_HPP
#define CORE_LIBS_PRX_LIBSCEVIDEOOUT_INCLUDE_VIDEOOUTDRIVER_HPP
#include <array>
#include <condition_variable>
@@ -13,6 +13,7 @@
#include <memory>
#include <stdexcept>
#include "prx/libSceAgcDriver/Execution/include/VideoOutput.hpp"
#include "prx/libSceAgcDriver/Execution/include/DisplayBuffer.hpp"
#include "SDL.h"
#include "SceTypes.hpp"
@@ -74,6 +75,8 @@ struct BufferAttributeGroup {
bool occupied = false;
};
AgcDriver::DisplayBuffer DescribeVideoOutBuffer(const VideoOutBuffer& buffer, const BufferAttributeGroup& group);
struct EventRegistration {
KernelEqueue eq = 0;
uint64_t generation = 0;
@@ -95,6 +98,7 @@ struct VideoOutConfig {
bool closing = false;
std::exception_ptr failure;
int flipRate = 0;
uint64_t lastFlipVblank = 0;
uint64_t outputMode = VIDEO_OUT_OUTPUT_MODE_DEFAULT;
float gamma = 1.0f;
@@ -103,6 +107,7 @@ struct VideoOutConfig {
VideoOutVblankStatus preVblankStatus{};
std::array<VideoOutBuffer, VIDEO_OUT_BUFFER_NUM_MAX> buffers{};
std::array<uint32_t, VIDEO_OUT_BUFFER_NUM_MAX> bufferPending{};
std::array<BufferAttributeGroup, VIDEO_OUT_BUFFER_ATTRIBUTE_NUM_MAX> groups{};
void Check() const {
@@ -119,6 +124,7 @@ struct FlipRequest final : AgcDriver::IFlipRequest, std::enable_shared_from_this
uint64_t generation = 0;
int index = 0;
int flipMode = 0;
int flipRate = 0;
int64_t flipArg = 0;
uint32_t width = 0;
uint32_t height = 0;
@@ -164,7 +170,7 @@ public:
private:
bool close(int handle);
void presentLoop(std::stop_token token);
void vblankBegin();
void vblankLoop(std::stop_token token);
void vblankEnd();
void processFlip(FlipRequest& req);
void triggerEvents(VideoOutConfig& cfg, int eventKind, void* triggerData);
@@ -179,6 +185,7 @@ private:
SDL_Window* window = nullptr;
std::jthread presentThread;
std::jthread vblankThread;
};
#endif
+34 -6
View File
@@ -5,6 +5,17 @@
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libSceVideoOut/include/VideoOutDriver.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
AgcDriver::DisplayBuffer DescribeVideoOutBuffer(const VideoOutBuffer& buffer, const BufferAttributeGroup& group) {
const auto& attribute = group.attribute;
if (attribute.reserved0 != 0 || attribute.pad0 != 0 || attribute.reserved1[0] != 0 || attribute.reserved1[1] != 0 || attribute.reserved1[2] != 0) throw std::runtime_error("VideoOut: reserved buffer attribute bits are set");
if (attribute.tiling_mode != 0 || attribute.pitch_in_pixel != 0 || attribute.aspect_ratio != 0 || attribute.option != 0) throw std::runtime_error("VideoOut: unsupported tiling, pitch, aspect ratio or buffer option");
if (group.category != VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_UNCOMPRESSED || buffer.metadataAddress != 0 || attribute.dcc_control != 0 || attribute.dcc_cb_register_clear_color != 0) throw std::runtime_error("VideoOut: DCC presentation is not implemented");
const AgcDriver::DisplayBuffer result{buffer.dataAddress, attribute.pixel_format, attribute.width, attribute.height};
static_cast<void>(AgcDriverDisplayBufferSize_nid_postfix(result));
return result;
}
extern "C" {
@@ -44,6 +55,8 @@ int APS5_VABI sceVideoOutRegisterBuffers2(int handle, int setIndex, int bufferIn
if (category != VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_UNCOMPRESSED && category != VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_COMPRESSED) {
throw std::runtime_error(std::string(__func__) + ": VIDEO_OUT_ERROR_INVALID_CATEGORY");
}
AgcDriverCheckGuestMemory_nid_postfix(attribute, sizeof(*attribute), alignof(VideoOutBufferAttribute2));
AgcDriverCheckGuestMemory_nid_postfix(buffers, static_cast<std::size_t>(bufferNum) * sizeof(*buffers), alignof(VideoOutBuffers));
std::unique_lock lock(cfg->mutex);
cfg->Check();
if (cfg->closing) {
@@ -61,15 +74,18 @@ int APS5_VABI sceVideoOutRegisterBuffers2(int handle, int setIndex, int bufferIn
group.attribute = *attribute;
group.category = category;
group.occupied = true;
std::array<VideoOutBuffer, VIDEO_OUT_BUFFER_NUM_MAX> registered{};
for (int i = 0; i < bufferNum; ++i) {
if (buffers[i].reserved[0] != nullptr || buffers[i].reserved[1] != nullptr) throw std::runtime_error("VideoOut: reserved buffer pointers are set");
registered[i] = {setIndex, reinterpret_cast<uint64_t>(buffers[i].data), reinterpret_cast<uint64_t>(buffers[i].metadata)};
const auto display = DescribeVideoOutBuffer(registered[i], group);
AgcDriverCheckGuestMemory_nid_postfix(buffers[i].data, AgcDriverDisplayBufferSize_nid_postfix(display), 65536);
}
cfg->groups[setIndex] = group;
cfg->width = attribute->width;
cfg->height = attribute->height;
for (int i = 0; i < bufferNum; i++) {
VideoOutBuffer buf{};
buf.groupIndex = setIndex;
buf.dataAddress = reinterpret_cast<uint64_t>(buffers[i].data);
buf.metadataAddress = reinterpret_cast<uint64_t>(buffers[i].metadata);
cfg->buffers[bufferIndexStart + i] = buf;
cfg->buffers[bufferIndexStart + i] = registered[i];
}
return 0;
}
@@ -93,7 +109,16 @@ int APS5_VABI sceVideoOutSubmitChangeBufferAttribute2(int handle, int setIndex,
if (cfg->closing || !cfg->groups[setIndex].occupied) {
throw std::runtime_error(std::string(__func__) + ": VIDEO_OUT_ERROR_INVALID_INDEX");
}
cfg->groups[setIndex].attribute = *attribute;
AgcDriverCheckGuestMemory_nid_postfix(attribute, sizeof(*attribute), alignof(VideoOutBufferAttribute2));
auto group = cfg->groups[setIndex];
group.attribute = *attribute;
for (int i = 0; i < VIDEO_OUT_BUFFER_NUM_MAX; ++i) {
if (cfg->buffers[i].groupIndex != setIndex) continue;
if (cfg->bufferPending[i] != 0) throw std::runtime_error("VideoOut: buffer attributes are in use by a pending flip");
const auto display = DescribeVideoOutBuffer(cfg->buffers[i], group);
AgcDriverCheckGuestMemory_nid_postfix(reinterpret_cast<const void*>(display.address), AgcDriverDisplayBufferSize_nid_postfix(display), 65536);
}
cfg->groups[setIndex] = group;
return 0;
}
@@ -113,6 +138,9 @@ int APS5_VABI sceVideoOutUnregisterBuffers(int handle, int setIndex) {
if (!cfg->groups[setIndex].occupied) {
throw std::runtime_error(std::string(__func__) + ": VIDEO_OUT_ERROR_INVALID_INDEX");
}
for (int i = 0; i < VIDEO_OUT_BUFFER_NUM_MAX; ++i) {
if (cfg->buffers[i].groupIndex == setIndex && cfg->bufferPending[i] != 0) throw std::runtime_error("VideoOut: cannot unregister a buffer with a pending flip");
}
cfg->groups[setIndex] = BufferAttributeGroup{};
for (auto& buf : cfg->buffers) {
if (buf.groupIndex == setIndex) {
+14 -7
View File
@@ -27,17 +27,21 @@ static int registerVideoOutEvent(int handle, KernelEqueue eq, int16_t eventKind,
if (!EqueuePin_nid_postfix(eq)) {
throw std::runtime_error(std::string(__func__) + ": VIDEO_OUT_ERROR_INVALID_EVENT_QUEUE");
}
std::unique_lock lock(cfg->mutex);
cfg->Check();
auto* registrations = getEventList(*cfg, eventKind);
const auto existing = std::find_if(registrations->begin(), registrations->end(), [eq](const auto& item) { return item.eq == eq; });
const bool replace = existing != registrations->end();
if (!replace) registrations->reserve(registrations->size() + 1);
KernelEqueueEvent event{};
event.event.ident = static_cast<uintptr_t>(eventKind);
event.event.filter = EVFILT_VIDEO_OUT;
event.event.flags = EV_ADD;
event.event.udata = udata;
if (eventKind == VIDEO_OUT_EVENT_SET_MODE) {
std::unique_lock lock(cfg->mutex);
cfg->Check();
event.triggered = true;
event.event.fflags = 1;
event.event.data = static_cast<intptr_t>(cfg->outputMode);
event.event.data = static_cast<intptr_t>((cfg->outputMode << 16u) | (1u << 12u));
}
event.filter.triggerFunc = [](KernelEqueueEvent* e, void* data) {
const uint64_t old = static_cast<uint64_t>(e->event.data);
@@ -71,12 +75,12 @@ static int registerVideoOutEvent(int handle, KernelEqueue eq, int16_t eventKind,
if (result == EQUEUE_ERROR_EBADF) {
throw std::runtime_error(std::string(__func__) + ": VIDEO_OUT_ERROR_INVALID_EVENT_QUEUE");
}
std::unique_lock lock(cfg->mutex);
cfg->Check();
if (result != EQUEUE_OK) throw std::runtime_error("VideoOut: event registration failed");
EventRegistration reg;
reg.eq = eq;
reg.generation = cfg->generation;
getEventList(*cfg, eventKind)->push_back(reg);
if (replace) *existing = reg;
else registrations->push_back(reg);
return result;
}
@@ -112,7 +116,10 @@ int APS5_VABI sceVideoOutAddVblankEvent(KernelEqueue eq, int handle, void* udata
}
int APS5_VABI sceVideoOutAddPreVblankStartEvent(KernelEqueue eq, int handle, void* udata) {
return registerVideoOutEvent(handle, eq, VIDEO_OUT_EVENT_PRE_VBLANK_START, udata);
static_cast<void>(eq);
static_cast<void>(udata);
VideoOutDriver::Get().GetConfig(handle);
throw std::runtime_error("VideoOut: physical pre-vblank timing is not implemented");
}
int APS5_VABI sceVideoOutAddOutputModeEvent(KernelEqueue eq, int handle, void* udata) {
+6 -2
View File
@@ -1,6 +1,7 @@
#include <cstring>
#include <mutex>
#include <stdexcept>
#include <cmath>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
@@ -60,7 +61,10 @@ int APS5_VABI sceVideoOutSetFlipRate(int handle, int rate) {
if (rate < 0 || rate > 2) {
throw std::runtime_error(std::string(__func__) + ": VIDEO_OUT_ERROR_INVALID_VALUE");
}
throw std::runtime_error(std::string(__func__) + " not implemented");
std::lock_guard lock(cfg->mutex);
cfg->Check();
cfg->flipRate = rate;
return 0;
}
int APS5_VABI sceVideoOutGetFlipStatus(int handle, VideoOutFlipStatus* status) {
@@ -199,7 +203,7 @@ int APS5_VABI sceVideoOutColorSettingsSetGamma(VideoOutColorSettings* settings,
if (settings == nullptr) {
throw std::runtime_error(std::string(__func__) + ": VIDEO_OUT_ERROR_INVALID_ADDRESS");
}
if (gamma < 0.1f || gamma > 2.0f) {
if (!std::isfinite(gamma) || gamma < 0.1f || gamma > 2.0f) {
throw std::runtime_error(std::string(__func__) + ": VIDEO_OUT_ERROR_INVALID_VALUE");
}
settings->gamma = gamma;
@@ -49,12 +49,18 @@ public:
request->group = cfg->groups[request->buffer.groupIndex];
require(request->group.occupied, "buffer group is not registered");
require(request->buffer.dataAddress != 0, "null registered buffer address");
static_cast<void>(DescribeVideoOutBuffer(request->buffer, request->group));
request->width = request->group.attribute.width;
request->height = request->group.attribute.height;
} else {
request->width = cfg->width;
request->height = cfg->height;
}
request->generation = cfg->generation;
request->width = cfg->width;
request->height = cfg->height;
request->flipRate = cfg->flipRate;
++queue->reservations;
++cfg->flipStatus.flipPendingNum;
if (info.index >= 0) ++cfg->bufferPending[info.index];
request->reserved = true;
return request;
}
@@ -86,6 +92,7 @@ FlipRequest::~FlipRequest() {
if (!terminal) {
--cfg->flipStatus.flipPendingNum;
--queue->reservations;
if (index >= 0) --cfg->bufferPending[index];
cfg->vblankCond.notify_all();
}
}
@@ -115,6 +122,7 @@ void FlipRequest::Fail(std::exception_ptr error) noexcept {
if (reserved && !terminal) {
--cfg->flipStatus.flipPendingNum;
--queue->reservations;
if (index >= 0) --cfg->bufferPending[index];
terminal = true;
}
cfg->vblankCond.notify_all();
@@ -133,8 +141,14 @@ VideoOutDriver::VideoOutDriver() {
try {
AgcDriverWaitIdle_nid_postfix();
presentThread = std::jthread([this](std::stop_token token) { presentLoop(token); });
vblankThread = std::jthread([this](std::stop_token token) { vblankLoop(token); });
LibcRegisterShutdown_nid_postfix([] { VideoOutDriver::Get().Shutdown(); });
} catch (...) {
if (vblankThread.joinable()) {
vblankThread.request_stop();
flipQueue->changed.notify_all();
vblankThread.join();
}
if (presentThread.joinable()) {
presentThread.request_stop();
flipQueue->changed.notify_all();
@@ -164,8 +178,10 @@ void VideoOutDriver::Shutdown() {
}
}
presentThread.request_stop();
vblankThread.request_stop();
flipQueue->changed.notify_all();
presentThread.join();
vblankThread.join();
if (window != nullptr) {
AgcDriverReleaseWindow_nid_postfix(window);
SDL_DestroyWindow(window);
@@ -218,6 +234,16 @@ bool VideoOutDriver::close(int handle) {
std::lock_guard cfgLock(cfg->mutex);
cfg->opened = false;
cfg->closing = true;
const auto removeEvents = [](const auto& events, int kind) {
for (const auto& event : events) {
const auto result = EqueueDeleteEvent_nid_postfix(event.eq, static_cast<uintptr_t>(kind), EVFILT_VIDEO_OUT);
require(result == EQUEUE_OK || result == EQUEUE_ERROR_EBADF || result == EQUEUE_ERROR_ENOENT, "event removal during close failed");
}
};
removeEvents(cfg->flipEvents, VIDEO_OUT_EVENT_FLIP);
removeEvents(cfg->vblankEvents, VIDEO_OUT_EVENT_VBLANK);
removeEvents(cfg->preVblankEvents, VIDEO_OUT_EVENT_PRE_VBLANK_START);
removeEvents(cfg->outputModeEvents, VIDEO_OUT_EVENT_SET_MODE);
cfg->flipEvents.clear();
cfg->vblankEvents.clear();
cfg->preVblankEvents.clear();
@@ -259,22 +285,14 @@ void VideoOutDriver::triggerEvents(VideoOutConfig& cfg, int eventKind, void* tri
else if (eventKind == VIDEO_OUT_EVENT_PRE_VBLANK_START) events = &cfg.preVblankEvents;
else if (eventKind == VIDEO_OUT_EVENT_SET_MODE) events = &cfg.outputModeEvents;
else throw std::runtime_error("VideoOut: unknown event kind");
for (const auto& reg : *events) {
require(reg.generation == cfg.generation, "stale event registration");
EqueueTriggerEvent_nid_postfix(reg.eq, static_cast<uintptr_t>(eventKind), EVFILT_VIDEO_OUT, triggerData);
}
}
void VideoOutDriver::vblankBegin() {
std::lock_guard lock(mutex);
for (const auto& cfg : contexts) {
if (!cfg) continue;
std::lock_guard cfgLock(cfg->mutex);
if (!cfg->opened || cfg->failure) continue;
++cfg->preVblankStatus.count;
cfg->preVblankStatus.processTime = sceKernelGetProcessTime();
cfg->preVblankStatus.processTimeCounter = sceKernelGetProcessTimeCounter();
triggerEvents(*cfg, VIDEO_OUT_EVENT_PRE_VBLANK_START, reinterpret_cast<void*>(cfg->preVblankStatus.count));
for (auto it = events->begin(); it != events->end();) {
require(it->generation == cfg.generation, "stale event registration");
const auto result = EqueueTriggerEvent_nid_postfix(it->eq, static_cast<uintptr_t>(eventKind), EVFILT_VIDEO_OUT, triggerData);
if (result == EQUEUE_ERROR_EBADF || result == EQUEUE_ERROR_ENOENT) it = events->erase(it);
else {
require(result == EQUEUE_OK, "event delivery failed");
++it;
}
}
}
@@ -284,6 +302,7 @@ void VideoOutDriver::vblankEnd() {
if (!cfg) continue;
std::lock_guard cfgLock(cfg->mutex);
if (!cfg->opened || cfg->failure) continue;
require(cfg->vblankStatus.count != std::numeric_limits<uint64_t>::max(), "vblank counter overflow");
++cfg->vblankStatus.count;
cfg->vblankStatus.processTime = sceKernelGetProcessTime();
cfg->vblankStatus.processTimeCounter = sceKernelGetProcessTimeCounter();
@@ -294,21 +313,24 @@ void VideoOutDriver::vblankEnd() {
void VideoOutDriver::processFlip(FlipRequest& req) {
{
std::lock_guard lock(req.cfg->mutex);
std::unique_lock lock(req.cfg->mutex);
checkConfig(*req.cfg);
require(req.ready && !req.terminal && req.generation == req.cfg->generation, "stale or incomplete flip request");
}
if (req.index >= 0) {
const auto& attribute = req.group.attribute;
require(attribute.reserved0 == 0 && attribute.pad0 == 0 && attribute.reserved1[0] == 0 && attribute.reserved1[1] == 0 && attribute.reserved1[2] == 0, "reserved buffer attribute bits are set");
require(attribute.width != 0 && attribute.height != 0, "empty registered buffer");
require(req.group.category == VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_UNCOMPRESSED && req.buffer.metadataAddress == 0 && attribute.dcc_control == 0 && attribute.dcc_cb_register_clear_color == 0, "DCC presentation is not implemented");
throw std::runtime_error("VideoOut: guest render-target tiling and image materialization are not implemented");
const auto interval = static_cast<uint64_t>(req.flipRate + 1);
require(req.cfg->lastFlipVblank <= std::numeric_limits<uint64_t>::max() - interval, "flip interval overflow");
const auto target = req.cfg->lastFlipVblank + interval;
req.cfg->vblankCond.wait(lock, [&] { return req.cfg->vblankStatus.count >= target || req.cfg->failure || req.cfg->closing; });
checkConfig(*req.cfg);
}
require(req.width != 0 && req.height != 0 && req.width <= static_cast<uint32_t>(std::numeric_limits<int>::max()) && req.height <= static_cast<uint32_t>(std::numeric_limits<int>::max()), "invalid window dimensions");
if (window == nullptr) {
window = SDL_CreateWindow("PS5", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, static_cast<int>(req.width), static_cast<int>(req.height), SDL_WINDOW_SHOWN | SDL_WINDOW_VULKAN);
if (window == nullptr) throw std::runtime_error(std::string("SDL_CreateWindow failed: ") + SDL_GetError());
} else {
int width = 0;
int height = 0;
SDL_GetWindowSize(window, &width, &height);
if (width != static_cast<int>(req.width) || height != static_cast<int>(req.height)) SDL_SetWindowSize(window, static_cast<int>(req.width), static_cast<int>(req.height));
}
unsigned extensionCount = 0;
if (!SDL_Vulkan_GetInstanceExtensions(window, &extensionCount, nullptr)) throw std::runtime_error(std::string("SDL_Vulkan_GetInstanceExtensions failed: ") + SDL_GetError());
@@ -320,37 +342,47 @@ void VideoOutDriver::processFlip(FlipRequest& req) {
if (!SDL_Vulkan_CreateSurface(static_cast<SDL_Window*>(context), instance, &surface)) throw std::runtime_error(std::string("SDL_Vulkan_CreateSurface failed: ") + SDL_GetError());
return surface;
}, req.width, req.height};
AgcDriverPresentClear_nid_postfix(target, req.index == VIDEO_OUT_BUFFER_INDEX_BLACK, [](void* context) {
const auto gpuReady = [](void* context) {
auto& request = *static_cast<FlipRequest*>(context);
std::lock_guard lock(request.cfg->mutex);
checkConfig(*request.cfg);
require(!request.terminal && !request.gpuComplete, "invalid GPU completion transition");
request.gpuComplete = true;
request.cfg->vblankCond.notify_all();
}, &req);
};
if (req.index >= 0) {
const auto display = DescribeVideoOutBuffer(req.buffer, req.group);
AgcDriverPresentBuffer_nid_postfix(target, display, gpuReady, &req);
} else {
AgcDriverPresentClear_nid_postfix(target, req.index == VIDEO_OUT_BUFFER_INDEX_BLACK, gpuReady, &req);
}
std::lock_guard lock(req.cfg->mutex);
checkConfig(*req.cfg);
require(!req.terminal && req.cfg->generation == req.generation, "flip cancelled during presentation");
require(req.cfg->flipStatus.count != std::numeric_limits<uint64_t>::max(), "flip counter overflow");
triggerEvents(*req.cfg, VIDEO_OUT_EVENT_FLIP, reinterpret_cast<void*>(req.flipArg));
++req.cfg->flipStatus.count;
req.cfg->lastFlipVblank = req.cfg->vblankStatus.count;
req.cfg->flipStatus.processTime = sceKernelGetProcessTime();
req.cfg->flipStatus.processTimeCounter = sceKernelGetProcessTimeCounter();
req.cfg->flipStatus.flipArg = req.flipArg;
req.cfg->flipStatus.currentBuffer = req.index;
req.cfg->width = req.width;
req.cfg->height = req.height;
--req.cfg->flipStatus.flipPendingNum;
--req.queue->reservations;
if (req.index >= 0) --req.cfg->bufferPending[req.index];
req.terminal = true;
req.cfg->vblankCond.notify_all();
}
void VideoOutDriver::presentLoop(std::stop_token token) {
std::shared_ptr<FlipRequest> current;
auto nextVblank = std::chrono::steady_clock::now();
try {
while (!token.stop_requested()) {
{
std::unique_lock lock(flipQueue->mutex);
flipQueue->changed.wait_until(lock, nextVblank, [&] { return token.stop_requested() || flipQueue->failure || !flipQueue->requests.empty(); });
flipQueue->changed.wait_for(lock, std::chrono::milliseconds(10), [&] { return token.stop_requested() || flipQueue->failure || !flipQueue->requests.empty(); });
if (flipQueue->failure) std::rethrow_exception(flipQueue->failure);
if (token.stop_requested()) break;
if (!flipQueue->requests.empty()) {
@@ -360,12 +392,6 @@ void VideoOutDriver::presentLoop(std::stop_token token) {
}
if (current) processFlip(*current);
current.reset();
const auto now = std::chrono::steady_clock::now();
if (now >= nextVblank) {
vblankBegin();
vblankEnd();
nextVblank = now + std::chrono::nanoseconds(1'000'000'000ULL / 60);
}
SDL_Event event;
while (SDL_PollEvent(&event)) {
require(event.type != SDL_QUIT, "window was closed");
@@ -404,3 +430,21 @@ void VideoOutDriver::presentLoop(std::stop_token token) {
AgcDriverReportFailure_nid_postfix(error);
}
}
void VideoOutDriver::vblankLoop(std::stop_token token) {
using Frame = std::chrono::duration<int64_t, std::ratio<1001, 60000>>;
const auto start = std::chrono::steady_clock::now();
try {
for (int64_t frame = 1; !token.stop_requested(); ++frame) {
const auto next = start + std::chrono::duration_cast<std::chrono::steady_clock::duration>(Frame(frame));
{
std::unique_lock lock(flipQueue->mutex);
flipQueue->changed.wait_until(lock, next, [&] { return token.stop_requested() || flipQueue->failure; });
if (token.stop_requested() || flipQueue->failure) return;
}
vblankEnd();
}
} catch (...) {
AgcDriverReportFailure_nid_postfix(std::current_exception());
}
}
+141 -16
View File
@@ -1,6 +1,8 @@
#include "prx/libSceVideoOut/include/VideoOutDriver.hpp"
#include "prx/libSceVideoOut/include/Buffer.hpp"
#include "prx/libSceVideoOut/include/Output.hpp"
#include "prx/libSceVideoOut/include/Event.hpp"
#include "prx/libkernel/Equeue/Equeue.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp"
#include "prx/libc/include/Shutdown.hpp"
@@ -8,9 +10,14 @@
#include <chrono>
#include <cstdio>
#include <string>
#include <limits>
#include <vector>
#undef main
extern "C" int APS5_VABI sceKernelCreateEqueue(KernelEqueue* eq, const char* name);
extern "C" int APS5_VABI sceKernelDeleteEqueue(KernelEqueue eq);
namespace {
void check(bool condition, const char* reason) {
@@ -42,6 +49,12 @@ public:
}
};
std::span<std::byte> alignedBuffer(std::vector<std::byte>& allocation) {
const auto address = reinterpret_cast<uintptr_t>(allocation.data());
const auto offset = (65536u - (address & 65535u)) & 65535u;
return {allocation.data() + offset, allocation.size() - 65535u};
}
void testLifetime(bool reopen) {
const int handle = sceVideoOutOpen(255, 0, 0, nullptr);
auto cfg = VideoOutDriver::Get().GetConfig(handle);
@@ -50,11 +63,13 @@ void testLifetime(bool reopen) {
std::array<uint32_t, 6> words{0xc004105c, 7, 0xfffffffeu, 1, 0, 0};
Packet packet{words.data(), 6, 0, {}};
sceAgcDriverSubmitDcb(&packet);
alignas(65536) static std::array<std::byte, 65536> storage{};
std::vector<std::byte> allocation(65536 + 65535);
const auto storage = alignedBuffer(allocation);
VideoOutBuffers buffer{storage.data(), nullptr, {nullptr, nullptr}};
VideoOutBufferAttribute2 attribute{};
attribute.width = 64;
attribute.height = 64;
attribute.pixel_format = 0x8000000000000000ull;
sceVideoOutRegisterBuffers2(handle, 0, 0, &buffer, 1, &attribute, 0, nullptr);
sceVideoOutSubmitFlip(handle, 0, 1, -9);
{
@@ -62,11 +77,12 @@ void testLifetime(bool reopen) {
check(cfg->flipStatus.flipPendingNum == 1 && cfg->flipStatus.count == 0, "reservation status is wrong");
}
attribute.dcc_control = 1;
sceVideoOutSubmitChangeBufferAttribute2(handle, 0, &attribute, nullptr);
sceVideoOutUnregisterBuffers(handle, 0);
check(expectFailure([&] { sceVideoOutSubmitChangeBufferAttribute2(handle, 0, &attribute, nullptr); }).find("pending flip") != std::string::npos, "pending attributes were changed");
check(expectFailure([&] { sceVideoOutUnregisterBuffers(handle, 0); }).find("pending flip") != std::string::npos, "pending buffer was unregistered");
check(sceVideoOutWaitVblank(handle) == 0 && sceVideoOutWaitVblank(handle) == 0, "vblank stalled behind the GPU queue");
std::shared_ptr<VideoOutConfig> replacement;
sceVideoOutClose(handle);
if (reopen) {
sceVideoOutClose(handle);
check(sceVideoOutOpen(255, 0, 0, nullptr) == handle, "reopen changed handle");
replacement = VideoOutDriver::Get().GetConfig(handle);
check(replacement != cfg && replacement->generation > cfg->generation, "reopen reused old port state");
@@ -80,38 +96,144 @@ void testLifetime(bool reopen) {
check(cfg->flipStatus.count == 0 && cfg->flipStatus.flipPendingNum == 0, "failed flip has successful or pending status");
}
const auto message = expectFailure([&] { std::rethrow_exception(failure); });
check(message.find(reopen ? "closed" : "tiling") != std::string::npos, "flip used changed attributes or port generation");
check(message.find("closed") != std::string::npos, "flip used a closed port");
if (replacement) {
std::lock_guard lock(replacement->mutex);
check(replacement->flipStatus.flipPendingNum == 0 && replacement->flipStatus.count == 0, "old request changed new port counters");
}
check(expectFailure([&] { sceVideoOutWaitVblank(handle); }).find(reopen ? "closed" : "tiling") != std::string::npos, "VideoOut lost worker failure");
check(expectFailure([&] { sceVideoOutWaitVblank(handle); }).find("closed") != std::string::npos, "VideoOut lost worker failure");
AgcDriverUnregisterVideoOutput_nid_postfix(7, gate);
sceVideoOutClose(handle);
if (reopen) sceVideoOutClose(handle);
const auto shutdown = expectFailure([] { LibcRunShutdown_nid_postfix(); });
check(shutdown.find(reopen ? "closed" : "tiling") != std::string::npos, "shutdown lost asynchronous error");
check(shutdown.find("closed") != std::string::npos, "shutdown lost asynchronous error");
}
void testPresentation() {
const int handle = sceVideoOutOpen(255, 0, 0, nullptr);
auto cfg = VideoOutDriver::Get().GetConfig(handle);
std::size_t tiledOffset(uint32_t x, uint32_t y, uint32_t width) {
constexpr std::array<uint32_t, 7> xMasks{4, 8, 128, 256, 0x2200, 0x800, 0x8400};
constexpr std::array<uint32_t, 7> yMasks{16, 32, 64, 0x1100, 0x200, 0x400, 0x4800};
uint32_t offset = 0;
for (uint32_t bit = 0; bit < 7; ++bit) {
if ((x & (1u << bit)) != 0) offset ^= xMasks[bit];
if ((y & (1u << bit)) != 0) offset ^= yMasks[bit];
}
return (static_cast<std::size_t>(y / 128u) * ((width + 127u) / 128u) + x / 128u) * 65536u + offset;
}
void fillBuffer(std::span<std::byte> bytes, uint32_t width, uint32_t height) {
for (uint32_t y = 0; y < height; ++y) {
for (uint32_t x = 0; x < width; ++x) {
const auto offset = tiledOffset(x, y, width);
bytes[offset] = static_cast<std::byte>(x & 255u);
bytes[offset + 1] = static_cast<std::byte>(y & 255u);
bytes[offset + 2] = static_cast<std::byte>((x ^ y) & 255u);
bytes[offset + 3] = std::byte{255};
}
}
}
void testDecode() {
std::vector<std::byte> allocation(6 * 65536 + 65535);
const auto tiled = alignedBuffer(allocation);
AgcDriver::DisplayBuffer buffer{reinterpret_cast<uint64_t>(tiled.data()), 0x8000000000000000ull, 259, 137};
check(AgcDriver::DisplayBufferSize(buffer) == tiled.size(), "incorrect padded display footprint");
fillBuffer(tiled, buffer.width, buffer.height);
for (const auto format : {0x8000000000000000ull, 0x8000000022000000ull}) {
buffer.pixelFormat = format;
const auto pixels = AgcDriver::ReadDisplayBuffer(buffer);
for (uint32_t y = 0; y < buffer.height; ++y) {
for (uint32_t x = 0; x < buffer.width; ++x) {
const auto offset = (static_cast<std::size_t>(y) * buffer.width + x) * 4;
const auto blue = format == 0x8000000000000000ull ? x : x ^ y;
const auto red = format == 0x8000000000000000ull ? x ^ y : x;
check(pixels[offset] == static_cast<std::byte>(blue & 255u) && pixels[offset + 1] == static_cast<std::byte>(y & 255u) && pixels[offset + 2] == static_cast<std::byte>(red & 255u) && pixels[offset + 3] == std::byte{255}, "detiled pixel or channel order mismatch");
}
}
}
expectFailure([&] { AgcDriver::DecodeDisplayBuffer(buffer, std::span(tiled).first(tiled.size() - 1)); });
buffer.pixelFormat = 0;
expectFailure([&] { AgcDriver::DisplayBufferSize(buffer); });
buffer.pixelFormat = 0x8000000000000000ull;
++buffer.address;
expectFailure([&] { AgcDriver::ReadDisplayBuffer(buffer); });
buffer.address = std::numeric_limits<uint64_t>::max() & ~uint64_t{65535};
expectFailure([&] { AgcDriver::DisplayBufferSize(buffer); });
}
void testControls() {
const auto handle = sceVideoOutOpen(255, 0, 0, nullptr);
const auto cfg = VideoOutDriver::Get().GetConfig(handle);
for (int rate = 0; rate <= 2; ++rate) {
check(sceVideoOutSetFlipRate(handle, rate) == 0 && cfg->flipRate == rate, "flip rate was not applied");
}
expectFailure([&] { sceVideoOutSetFlipRate(handle, 3); });
VideoOutColorSettings settings{};
expectFailure([&] { sceVideoOutColorSettingsSetGamma(&settings, std::numeric_limits<float>::quiet_NaN()); });
KernelEqueue queue = 0;
check(sceKernelCreateEqueue(&queue, "VideoOut test") == 0, "event queue creation failed");
auto owner = EqueuePin_nid_postfix(queue);
check(sceVideoOutAddOutputModeEvent(queue, handle, nullptr) == 0, "output mode subscription failed");
KernelEvent event{};
check(owner->GetTriggeredEvents(&event, 1) == 1, "initial output mode event missing");
int64_t mode = 0;
check(sceVideoOutGetEventData(&event, &mode) == 0 && mode == VIDEO_OUT_OUTPUT_MODE_DEFAULT && sceVideoOutGetEventCount(&event) == 1, "initial output mode event encoding is wrong");
check(sceVideoOutAddVblankEvent(queue, handle, nullptr) == 0 && sceVideoOutAddVblankEvent(queue, handle, &settings) == 0, "vblank subscription failed");
{
std::lock_guard lock(cfg->mutex);
cfg->width = 64;
cfg->height = 64;
check(cfg->vblankEvents.size() == 1, "duplicate vblank subscription");
}
for (int index : {-2, -1, -2}) {
check(sceVideoOutWaitVblank(handle) == 0, "vblank wait failed");
check(owner->GetTriggeredEvents(&event, 1) == 1 && event.udata == &settings && sceVideoOutGetEventId(&event) == VIDEO_OUT_EVENT_VBLANK, "vblank event or updated user data missing");
sceVideoOutClose(handle);
check(owner->GetTriggeredEvents(&event, 1) == 0, "closed port retained pending events");
check(sceKernelDeleteEqueue(queue) == 0, "event queue deletion failed");
LibcRunShutdown_nid_postfix();
}
void testPresentation(bool expectUnavailable) {
const int handle = sceVideoOutOpen(255, 0, 0, nullptr);
auto cfg = VideoOutDriver::Get().GetConfig(handle);
std::vector<std::byte> allocation(6 * 65536 + 65535);
const auto storage = alignedBuffer(allocation);
fillBuffer(storage, 259, 137);
VideoOutBuffers buffer{storage.data(), nullptr, {nullptr, nullptr}};
VideoOutBufferAttribute2 attribute{};
sceVideoOutSetBufferAttribute2(&attribute, 0x8000000000000000ull, 0, 259, 137, 0, 0, 0);
auto invalid = attribute;
invalid.dcc_control = 1;
check(expectFailure([&] { sceVideoOutRegisterBuffers2(handle, 0, 0, &buffer, 1, &invalid, 0, nullptr); }).find("DCC") != std::string::npos, "DCC buffer was accepted");
check(!cfg->groups[0].occupied, "rejected registration changed the buffer group");
sceVideoOutRegisterBuffers2(handle, 0, 0, &buffer, 1, &attribute, 0, nullptr);
sceVideoOutSetFlipRate(handle, 2);
for (int index : {0, -2, -1, 0}) {
uint64_t target;
uint64_t previousVblank;
{
std::lock_guard lock(cfg->mutex);
target = cfg->flipStatus.count + 1;
previousVblank = cfg->lastFlipVblank;
}
sceVideoOutSubmitFlip(handle, index, 1, -123456789);
std::unique_lock lock(cfg->mutex);
check(cfg->vblankCond.wait_for(lock, std::chrono::seconds(15), [&] { return cfg->failure || cfg->flipStatus.count == target; }), "presentation did not complete");
check(cfg->vblankCond.wait_for(lock, std::chrono::seconds(15), [&] { return (cfg->failure && cfg->flipStatus.flipPendingNum == 0) || cfg->flipStatus.count == target; }), "presentation did not complete");
if (expectUnavailable) {
check(cfg->failure != nullptr && cfg->flipStatus.count == 0 && cfg->bufferPending[0] == 0, "failed presentation was marked complete or retained its buffer");
const auto error = cfg->failure;
lock.unlock();
const auto message = expectFailure([&] { std::rethrow_exception(error); });
check(message.find("required instance extension missing") != std::string::npos, "unexpected presentation failure");
check(expectFailure([] { AgcDriverWaitIdle_nid_postfix(); }) == message, "AGC lost presentation failure");
check(expectFailure([] { LibcRunShutdown_nid_postfix(); }) == message, "shutdown lost presentation failure");
return;
}
if (cfg->failure) std::rethrow_exception(cfg->failure);
check(cfg->flipStatus.flipArg == -123456789 && cfg->flipStatus.currentBuffer == index && cfg->flipStatus.flipPendingNum == 0, "presentation status is wrong");
check(cfg->lastFlipVblank >= previousVblank + 3, "flip rate did not wait for its interval");
lock.unlock();
attribute.width = 65;
attribute.height = 33;
sceVideoOutSubmitChangeBufferAttribute2(handle, 0, &attribute, nullptr);
}
sceVideoOutUnregisterBuffers(handle, 0);
sceVideoOutClose(handle);
LibcRunShutdown_nid_postfix();
}
@@ -120,7 +242,10 @@ void testPresentation() {
int main(int argc, char** argv) {
try {
if (argc == 2 && std::string(argv[1]) == "present") testPresentation();
if (argc == 2 && std::string(argv[1]) == "decode") testDecode();
else if (argc == 2 && std::string(argv[1]) == "controls") testControls();
else if (argc == 2 && std::string(argv[1]) == "present") testPresentation(false);
else if (argc == 2 && std::string(argv[1]) == "unavailable") testPresentation(true);
else testLifetime(argc == 2 && std::string(argv[1]) == "reopen");
std::puts("VideoOut flip tests passed");
return 0;