Implement main compositor
Replace the patches to Monado's main compositor with a local implementation, reusing code when relevant. The layer squasher is very close to comp_render_cs, while distortion is completely replaced by foveation.
This commit is contained in:
@@ -21,7 +21,7 @@ function(compile_glsl_aux shader_stage shader_name glsl_filename output target_e
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${SPV_FILE}-nopt"
|
||||
COMMAND Vulkan::glslangValidator -V --target-env ${target_env} -S ${shader_stage} -D${shader_stage_upper}_SHADER ${in_file} ${SHADER_FLAGS} -o "${SPV_FILE}-nopt" --depfile "${SPV_FILE}.d"
|
||||
COMMAND Vulkan::glslangValidator -V --target-env ${target_env} -S ${shader_stage} -D${shader_stage_upper}_SHADER ${glsl_filename} ${SHADER_FLAGS} -o "${SPV_FILE}-nopt" --depfile "${SPV_FILE}.d"
|
||||
DEPENDS "${glsl_filename}"
|
||||
DEPFILE "${SPV_FILE}.d"
|
||||
VERBATIM
|
||||
|
||||
@@ -22,7 +22,6 @@ The encoder to use, either a single string or object applied to all streams, or
|
||||
When a string it is used, it is equivalent to the `encoder` item of the object.
|
||||
|
||||
WiVRn encodes each eye separately, and the alpha channel as one for both eyes. Each stream is processed independently, this may use resources more effectively and reduce latency.
|
||||
All the provided encoders are put into groups, groups are executed concurrently and items within a group are processed sequentially.
|
||||
|
||||
### `encoder`
|
||||
Default value: `nvenc` if Nvidia GPU and compiled with nvenc, `vaapi` for all other GPU when compiled with ffmpeg, else `x264`.
|
||||
@@ -46,12 +45,6 @@ Not all encoders support every codec:
|
||||
|
||||
If `nvenc` encoder is in use, you can refer to [nvidia website](https://developer.nvidia.com/video-encode-decode-support-matrix) to make sure that your GPU supports encoding with the desired codec.
|
||||
|
||||
### `group` (advanced)
|
||||
Default value: One value for each encoder type (nvenc, vaapi, vulkan, x264).
|
||||
|
||||
Identifier (number) of the encoder group. Encoders with the same identifier are executed sequentially, in the order they are defined in the configuration. Encoders with different identifiers are executed concurrently.
|
||||
Default setting will have all encoders of a given type execute sequentially, and different types in parallel.
|
||||
|
||||
### Examples
|
||||
1. Simple configuration
|
||||
```json
|
||||
|
||||
@@ -376,6 +376,7 @@ modules:
|
||||
- -DWIVRN_BUILD_SERVER=ON
|
||||
- -DWIVRN_BUILD_SERVER_LIBRARY=OFF
|
||||
- -DWIVRN_BUILD_DASHBOARD=ON
|
||||
- -DWIVRN_OPTIMIZE_SHADERS=OFF
|
||||
- -DWIVRN_USE_VAAPI=ON
|
||||
- -DWIVRN_USE_X264=ON
|
||||
- -DWIVRN_USE_NVENC=ON
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 6317d6556f2510cc63aa5f71d86585830a38b2a1 Mon Sep 17 00:00:00 2001
|
||||
From 0fe5a8e72f2ba178e155d2ab87e79f34294248dd Mon Sep 17 00:00:00 2001
|
||||
From: Patrick Nicolas <patricknicolas@laposte.net>
|
||||
Date: Tue, 22 Oct 2024 15:23:19 +0200
|
||||
Subject: [PATCH 1/9] c/multi: early wake of compositor
|
||||
Subject: [PATCH 1/8] c/multi: early wake of compositor
|
||||
|
||||
---
|
||||
.../compositor/multi/comp_multi_compositor.c | 14 +++++++++
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 71b4f13a8b7cb90edf83f75bef8459d2db66c386 Mon Sep 17 00:00:00 2001
|
||||
From c0019c2e8822db5efa7d6baf51b9773cc7bdc537 Mon Sep 17 00:00:00 2001
|
||||
From: Patrick Nicolas <patricknicolas@laposte.net>
|
||||
Date: Tue, 8 Oct 2024 22:13:15 +0200
|
||||
Subject: [PATCH 2/9] Use extern socket fd
|
||||
Subject: [PATCH 2/8] Use extern socket fd
|
||||
|
||||
---
|
||||
src/xrt/ipc/server/ipc_server_mainloop_linux.c | 8 ++++++++
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From d3fc5ebb88a59ce5fc1120ed33de921eec03384f Mon Sep 17 00:00:00 2001
|
||||
From 004623b9038b3043365061e77a0e3cc430fb2dd9 Mon Sep 17 00:00:00 2001
|
||||
From: galister <85970-galister@users.noreply.gitlab.freedesktop.org>
|
||||
Date: Sat, 23 Nov 2024 02:42:12 +0900
|
||||
Subject: [PATCH 3/9] change environment blend mode selection logic
|
||||
Subject: [PATCH 3/8] change environment blend mode selection logic
|
||||
|
||||
---
|
||||
src/xrt/compositor/multi/comp_multi_system.c | 26 +++++++++++++-------
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 42e1e561a98f5c9fd6f757232bd4821124ae9bb3 Mon Sep 17 00:00:00 2001
|
||||
From c0d86e77f011f0d75f17e5c30fb20bbf166dfc08 Mon Sep 17 00:00:00 2001
|
||||
From: Patrick Nicolas <patricknicolas@laposte.net>
|
||||
Date: Sat, 15 Mar 2025 22:19:48 +0100
|
||||
Subject: [PATCH 4/9] st/oxr: forward 0 refresh rate
|
||||
Subject: [PATCH 4/8] st/oxr: forward 0 refresh rate
|
||||
|
||||
---
|
||||
src/xrt/compositor/main/comp_compositor.c | 2 +-
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -1,7 +1,7 @@
|
||||
From 5664ae214c09deb241507526e749f83f3a16298c Mon Sep 17 00:00:00 2001
|
||||
From 80007ab047cb486e78eb0527dc97de56574bc8e2 Mon Sep 17 00:00:00 2001
|
||||
From: no name <git-am@invalid>
|
||||
Date: Sun, 28 Sep 2025 11:33:10 +0200
|
||||
Subject: [PATCH 6/9] d/steamvr_lh: prevent crash on vive pro2/WiVRn
|
||||
Subject: [PATCH 5/8] d/steamvr_lh: prevent crash on vive pro2/WiVRn
|
||||
|
||||
---
|
||||
src/xrt/drivers/steamvr_lh/steamvr_lh.cpp | 2 +-
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
From 4fdc8798f4810145c446fe147ae94e4c717b6b28 Mon Sep 17 00:00:00 2001
|
||||
From 659f5782066f77bb027accfcfe9ac4a810d27903 Mon Sep 17 00:00:00 2001
|
||||
From: Sapphire <imsapphire0@gmail.com>
|
||||
Date: Fri, 7 Nov 2025 20:41:16 -0600
|
||||
Subject: [PATCH 7/9] st/oxr: push XrEventDataInteractionProfileChanged when
|
||||
Subject: [PATCH 6/8] st/oxr: push XrEventDataInteractionProfileChanged when
|
||||
profile changes to NULL
|
||||
|
||||
---
|
||||
@@ -9,10 +9,10 @@ Subject: [PATCH 7/9] st/oxr: push XrEventDataInteractionProfileChanged when
|
||||
1 file changed, 3 deletions(-)
|
||||
|
||||
diff --git a/src/xrt/state_trackers/oxr/actions/oxr_input.c b/src/xrt/state_trackers/oxr/actions/oxr_input.c
|
||||
index 269c6ec62..05a747f74 100644
|
||||
index 51ae13b05..192833639 100644
|
||||
--- a/src/xrt/state_trackers/oxr/actions/oxr_input.c
|
||||
+++ b/src/xrt/state_trackers/oxr/actions/oxr_input.c
|
||||
@@ -1947,9 +1947,6 @@ session_update_action_bindings(struct oxr_logger *log,
|
||||
@@ -1932,9 +1932,6 @@ session_update_action_bindings(struct oxr_logger *log,
|
||||
#define POPULATE_PROFILE(X) \
|
||||
do { \
|
||||
XrPath path = profiles.X != NULL ? profiles.X->path : XR_NULL_PATH; \
|
||||
+3
-3
@@ -1,14 +1,14 @@
|
||||
From dfacf60061206ca6f41b8bc44e9cd7166230d77e Mon Sep 17 00:00:00 2001
|
||||
From 5dbb5983ab7f5ec1204ff8fe932519c0df7feeed Mon Sep 17 00:00:00 2001
|
||||
From: no name <git-am@invalid>
|
||||
Date: Sun, 25 Jan 2026 10:09:10 +0100
|
||||
Subject: [PATCH 9/9] don't verify GL stuff
|
||||
Subject: [PATCH 7/8] don't verify GL stuff
|
||||
|
||||
---
|
||||
src/xrt/state_trackers/oxr/oxr_verify.c | 10 ----------
|
||||
1 file changed, 10 deletions(-)
|
||||
|
||||
diff --git a/src/xrt/state_trackers/oxr/oxr_verify.c b/src/xrt/state_trackers/oxr/oxr_verify.c
|
||||
index 68906d7de..239f87fba 100644
|
||||
index 8f35222cf..1418a8231 100644
|
||||
--- a/src/xrt/state_trackers/oxr/oxr_verify.c
|
||||
+++ b/src/xrt/state_trackers/oxr/oxr_verify.c
|
||||
@@ -610,16 +610,6 @@ oxr_verify_XrGraphicsBindingOpenGLXlibKHR(struct oxr_logger *log, const XrGraphi
|
||||
@@ -1,85 +0,0 @@
|
||||
From 025dcad51542cd6c23d9a6ad16cca982bf2fa5ca Mon Sep 17 00:00:00 2001
|
||||
From: no name <git-am@invalid>
|
||||
Date: Thu, 15 Jan 2026 12:13:06 +0100
|
||||
Subject: [PATCH 8/9] Don't get pose data in compositor
|
||||
|
||||
Reproject onto the first projection layer's pose, if there isn't any get
|
||||
it from device instead.
|
||||
---
|
||||
src/xrt/compositor/main/comp_renderer.c | 53 +++++++++++++++++++++----
|
||||
1 file changed, 45 insertions(+), 8 deletions(-)
|
||||
|
||||
diff --git a/src/xrt/compositor/main/comp_renderer.c b/src/xrt/compositor/main/comp_renderer.c
|
||||
index ff9728a59..4a91bbcd0 100644
|
||||
--- a/src/xrt/compositor/main/comp_renderer.c
|
||||
+++ b/src/xrt/compositor/main/comp_renderer.c
|
||||
@@ -948,6 +948,24 @@ dispatch_graphics(struct comp_renderer *r,
|
||||
*
|
||||
*/
|
||||
|
||||
+static struct comp_layer *
|
||||
+get_projection_layer(struct comp_layer_accum *layers)
|
||||
+{
|
||||
+ for (uint32_t layer = 0; layer < layers->layer_count; ++layer) {
|
||||
+ switch (layers->layers[layer].data.type) {
|
||||
+ case XRT_LAYER_PROJECTION:
|
||||
+ case XRT_LAYER_PROJECTION_DEPTH: return &layers->layers[layer];
|
||||
+ case XRT_LAYER_QUAD:
|
||||
+ case XRT_LAYER_CUBE:
|
||||
+ case XRT_LAYER_CYLINDER:
|
||||
+ case XRT_LAYER_EQUIRECT1:
|
||||
+ case XRT_LAYER_EQUIRECT2:
|
||||
+ case XRT_LAYER_PASSTHROUGH: break;
|
||||
+ }
|
||||
+ }
|
||||
+ return NULL;
|
||||
+}
|
||||
+
|
||||
/*!
|
||||
* @pre render_compute_init(render, &c->nr)
|
||||
*/
|
||||
@@ -972,14 +990,33 @@ dispatch_compute(struct comp_renderer *r,
|
||||
struct xrt_pose world_poses_scanout_begin[XRT_MAX_VIEWS];
|
||||
struct xrt_pose world_poses_scanout_end[XRT_MAX_VIEWS];
|
||||
struct xrt_pose eye_poses[XRT_MAX_VIEWS];
|
||||
- calc_pose_data( //
|
||||
- r, //
|
||||
- fov_source, //
|
||||
- fovs, //
|
||||
- world_poses_scanout_begin, //
|
||||
- world_poses_scanout_end, //
|
||||
- eye_poses, //
|
||||
- render->r->view_count); //
|
||||
+ if (!c->base.frame_params.one_projection_layer_fast_path) {
|
||||
+ struct comp_layer *proj_layer = get_projection_layer(&c->base.layer_accum);
|
||||
+ int64_t predicted_display_time_ns = c->frame.rendering.predicted_display_time_ns;
|
||||
+ int64_t cutoff_ns = 3 * c->frame_interval_ns;
|
||||
+ if (proj_layer && llabs(predicted_display_time_ns - proj_layer->data.timestamp) <= cutoff_ns) {
|
||||
+ struct xrt_layer_projection_view_data *data = proj_layer->data.proj.v;
|
||||
+ // depth has the same first member as proj
|
||||
+ for (int view = 0; view < XRT_MAX_VIEWS; ++view) {
|
||||
+ fovs[view] = data[view].fov;
|
||||
+ world_poses_scanout_begin[view] = data[view].pose;
|
||||
+ world_poses_scanout_end[view] = data[view].pose;
|
||||
+ eye_poses[view] = data[view].pose;
|
||||
+
|
||||
+ r->c->base.frame_params.fovs[view] = data[view].fov;
|
||||
+ r->c->base.frame_params.poses[view] = data[view].pose;
|
||||
+ }
|
||||
+ } else {
|
||||
+ calc_pose_data( //
|
||||
+ r, //
|
||||
+ fov_source, //
|
||||
+ fovs, //
|
||||
+ world_poses_scanout_begin, //
|
||||
+ world_poses_scanout_end, //
|
||||
+ eye_poses, //
|
||||
+ render->r->view_count); //
|
||||
+ }
|
||||
+ }
|
||||
|
||||
// Target Vulkan resources..
|
||||
VkImage target_image = r->c->target->images[r->acquired_buffer].handle;
|
||||
--
|
||||
2.53.0
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
From a9ac675eab72a6ce96adb38215e83f7b3e9b51e7 Mon Sep 17 00:00:00 2001
|
||||
From 11fdc5a904db55867ed567bbc89ee5207e5741f0 Mon Sep 17 00:00:00 2001
|
||||
From: no name <git-am@invalid>
|
||||
Date: Fri, 20 Mar 2026 16:51:18 +0100
|
||||
Subject: [PATCH] configure u_git_tag in WiVRn
|
||||
Subject: [PATCH 8/8] configure u_git_tag in WiVRn
|
||||
|
||||
---
|
||||
src/xrt/auxiliary/util/CMakeLists.txt | 7 +------
|
||||
+17
-4
@@ -91,6 +91,11 @@ if (WIVRN_BUILD_SERVER)
|
||||
|
||||
audio/audio_setup.cpp
|
||||
|
||||
compositor/compositor.cpp
|
||||
compositor/layer_squasher.cpp
|
||||
compositor/foveation.cpp
|
||||
compositor/pacer.cpp
|
||||
|
||||
encoder/encoder_settings.cpp
|
||||
encoder/idr_handler.cpp
|
||||
encoder/video_encoder.cpp
|
||||
@@ -104,15 +109,12 @@ if (WIVRN_BUILD_SERVER)
|
||||
driver/tracking_control.cpp
|
||||
driver/view_list.cpp
|
||||
driver/wivrn_hmd.cpp
|
||||
driver/wivrn_pacer.cpp
|
||||
driver/wivrn_comp_target.cpp
|
||||
driver/wivrn_controller.cpp
|
||||
driver/wivrn_eye_tracker.cpp
|
||||
driver/wivrn_android_face_tracker.cpp
|
||||
driver/wivrn_fb_face2_tracker.cpp
|
||||
driver/wivrn_htc_face_tracker.cpp
|
||||
driver/wivrn_generic_tracker.cpp
|
||||
driver/wivrn_foveation.cpp
|
||||
driver/wivrn_uinput.cpp
|
||||
driver/wivrn_session.cpp
|
||||
driver/wivrn_connection.cpp
|
||||
@@ -226,7 +228,9 @@ if (WIVRN_BUILD_SERVER)
|
||||
aux_os
|
||||
aux_util
|
||||
aux_vk
|
||||
comp_main
|
||||
comp_multi
|
||||
comp_render
|
||||
comp_util
|
||||
ipc_server
|
||||
xrt-external-openxr
|
||||
xrt-interfaces
|
||||
@@ -239,6 +243,15 @@ if (WIVRN_BUILD_SERVER)
|
||||
nlohmann_json::nlohmann_json
|
||||
)
|
||||
|
||||
include(CompileGLSL)
|
||||
FetchContent_GetProperties(monado SOURCE_DIR _monado_src)
|
||||
wivrn_compile_glsl(wivrn-server
|
||||
TARGET_ENV vulkan1.3
|
||||
SHADERS
|
||||
"${_monado_src}/src/xrt/compositor/shaders/layer.comp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/compositor/shaders/foveation.comp"
|
||||
)
|
||||
|
||||
target_compile_definitions(wivrn-server PRIVATE JSON_DIAGNOSTICS=1)
|
||||
|
||||
configure_file(dist/wivrn.service.in wivrn.service)
|
||||
|
||||
@@ -0,0 +1,743 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright 2019-2024, Collabora, Ltd.
|
||||
// Copyright 2025-2026, NVIDIA CORPORATION.
|
||||
|
||||
#include "compositor.h"
|
||||
|
||||
// Monado includes
|
||||
#include "driver/xrt_cast.h"
|
||||
#include "main/comp_frame.h"
|
||||
#include "util/comp_render_helpers.h"
|
||||
#include "util/comp_vulkan.h"
|
||||
#include "util/u_debug.h"
|
||||
#include "util/u_handles.h"
|
||||
#include "util/u_time.h"
|
||||
#include "vk/vk_helpers.h"
|
||||
|
||||
#include "driver/wivrn_session.h"
|
||||
#include "encoder/video_encoder.h"
|
||||
#include "utils/method.h"
|
||||
|
||||
DEBUG_GET_ONCE_LOG_OPTION(log, "XRT_COMPOSITOR_LOG", U_LOGGING_INFO)
|
||||
|
||||
namespace details
|
||||
{
|
||||
template <auto Method, typename Result, typename... Args>
|
||||
struct method_trait<Method, Result (wivrn::compositor::*)(Args...)>
|
||||
{
|
||||
static Result magic(xrt_compositor * arg, Args... args)
|
||||
{
|
||||
return std::invoke(
|
||||
Method,
|
||||
static_cast<wivrn::compositor *>(reinterpret_cast<struct comp_base *>(arg)),
|
||||
args...);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
|
||||
namespace
|
||||
{
|
||||
os_mutex copy_mutex(std::mutex & m)
|
||||
{
|
||||
return {
|
||||
.mutex = *m.native_handle(),
|
||||
#ifndef NDEBUG
|
||||
.initialized = true,
|
||||
.recursive = false,
|
||||
#endif
|
||||
};
|
||||
}
|
||||
|
||||
const comp_swapchain_image & get_layer_image(const comp_layer & layer, uint32_t swapchain_index, uint32_t image_index)
|
||||
{
|
||||
return ((struct comp_swapchain *)(comp_layer_get_swapchain(&layer, swapchain_index)))->images[image_index];
|
||||
}
|
||||
|
||||
std::array<vk::Format, 3> image_formats(int bit_depth)
|
||||
{
|
||||
switch (bit_depth)
|
||||
{
|
||||
case 8:
|
||||
return {
|
||||
vk::Format::eR8Unorm,
|
||||
vk::Format::eR8G8Unorm,
|
||||
vk::Format::eG8B8R82Plane420Unorm,
|
||||
};
|
||||
case 10:
|
||||
return {
|
||||
vk::Format::eR16Unorm,
|
||||
vk::Format::eR16G16Unorm,
|
||||
vk::Format::eG10X6B10X6R10X62Plane420Unorm3Pack16,
|
||||
};
|
||||
}
|
||||
throw std::runtime_error(std::format("Unsupported bit depth {}", bit_depth));
|
||||
}
|
||||
|
||||
std::array<wivrn::compositor::image, 2> make_images(wivrn::vk_bundle & vk, vk::CommandPool command_pool, std::span<wivrn::encoder_settings> encoders)
|
||||
{
|
||||
auto formats = image_formats(encoders[0].bit_depth);
|
||||
|
||||
vk::StructureChain image_info{
|
||||
vk::ImageCreateInfo{
|
||||
.flags = vk::ImageCreateFlagBits::eExtendedUsage | vk::ImageCreateFlagBits::eMutableFormat,
|
||||
.imageType = vk::ImageType::e2D,
|
||||
.format = formats.back(),
|
||||
.extent = {
|
||||
.width = encoders[0].width,
|
||||
.height = encoders[0].height,
|
||||
.depth = 1,
|
||||
},
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 3, // left, right then alpha
|
||||
.samples = vk::SampleCountFlagBits::e1,
|
||||
.usage = vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eTransferSrc,
|
||||
},
|
||||
vk::ImageFormatListCreateInfo{
|
||||
.viewFormatCount = formats.size(),
|
||||
.pViewFormats = formats.data(),
|
||||
},
|
||||
};
|
||||
#if WIVRN_USE_VULKAN_ENCODE
|
||||
if (
|
||||
std::get<vk::PhysicalDeviceVideoMaintenance1FeaturesKHR>(vk.feat).videoMaintenance1 and
|
||||
std::ranges::contains(
|
||||
encoders,
|
||||
wivrn::encoder_vulkan,
|
||||
&wivrn::encoder_settings::encoder_name))
|
||||
{
|
||||
image_info.get().flags |= vk::ImageCreateFlagBits::eVideoProfileIndependentKHR;
|
||||
image_info.get().usage |= vk::ImageUsageFlagBits::eVideoEncodeSrcKHR;
|
||||
}
|
||||
#endif
|
||||
|
||||
auto bufs = vk.device.allocateCommandBuffers({
|
||||
.commandPool = command_pool,
|
||||
.commandBufferCount = 2,
|
||||
});
|
||||
|
||||
auto make_image = [&](int i) {
|
||||
vk::ImageViewUsageCreateInfo usage{
|
||||
.usage = vk::ImageUsageFlagBits::eStorage,
|
||||
};
|
||||
image_allocation image{
|
||||
vk.device,
|
||||
image_info.get(),
|
||||
VmaAllocationCreateInfo{.usage = VMA_MEMORY_USAGE_AUTO},
|
||||
std::format("compositor YCbCr image {}", i),
|
||||
};
|
||||
vk::Image vk_image{image};
|
||||
return wivrn::compositor::image{
|
||||
.sem{vk.device, vk::SemaphoreCreateInfo{}},
|
||||
.fence{vk.device, vk::FenceCreateInfo{}},
|
||||
.cmd{std::move(bufs[i])},
|
||||
.image{std::move(image)},
|
||||
.view_y{
|
||||
vk.device,
|
||||
{
|
||||
.pNext = &usage,
|
||||
.image = vk_image,
|
||||
.viewType = vk::ImageViewType::e2DArray,
|
||||
.format = formats[0],
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::ePlane0,
|
||||
.levelCount = 1,
|
||||
.layerCount = vk::RemainingArrayLayers,
|
||||
},
|
||||
},
|
||||
},
|
||||
.view_cbcr{
|
||||
vk.device,
|
||||
{
|
||||
.pNext = &usage,
|
||||
.image = vk_image,
|
||||
.viewType = vk::ImageViewType::e2DArray,
|
||||
.format = formats[1],
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::ePlane1,
|
||||
.levelCount = 1,
|
||||
.layerCount = vk::RemainingArrayLayers,
|
||||
},
|
||||
},
|
||||
}};
|
||||
};
|
||||
|
||||
return {make_image(0), make_image(1)};
|
||||
}
|
||||
|
||||
vk::raii::Fence make_fence(wivrn::vk_bundle & vk, const char * name)
|
||||
{
|
||||
vk::raii::Fence res{
|
||||
vk.device,
|
||||
vk::FenceCreateInfo{
|
||||
.flags = vk::FenceCreateFlagBits::eSignaled,
|
||||
},
|
||||
};
|
||||
vk.name(res, name);
|
||||
return res;
|
||||
}
|
||||
|
||||
vk::Extent3D render_extent(const wivrn::from_headset::headset_info_packet & info)
|
||||
{
|
||||
return {
|
||||
.width = info.render_eye_width,
|
||||
.height = info.render_eye_height,
|
||||
.depth = 1,
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
xrt_result_t compositor::predict_frame(int64_t * out_frame_id,
|
||||
int64_t * out_wake_time_ns,
|
||||
int64_t * out_predicted_gpu_time_ns,
|
||||
int64_t * out_predicted_display_time_ns,
|
||||
int64_t * out_predicted_display_period_ns)
|
||||
{
|
||||
int64_t frame_id = -1;
|
||||
int64_t wake_up_time_ns = 0;
|
||||
int64_t present_slop_ns = 0;
|
||||
int64_t desired_present_time_ns = 0;
|
||||
int64_t predicted_display_time_ns = 0;
|
||||
pacer.predict(
|
||||
frame_id,
|
||||
wake_up_time_ns,
|
||||
desired_present_time_ns,
|
||||
present_slop_ns,
|
||||
predicted_display_time_ns);
|
||||
|
||||
frame.waited.id = frame_id;
|
||||
frame.waited.desired_present_time_ns = desired_present_time_ns;
|
||||
frame.waited.present_slop_ns = present_slop_ns;
|
||||
frame.waited.predicted_display_time_ns = predicted_display_time_ns;
|
||||
|
||||
*out_frame_id = frame_id;
|
||||
*out_wake_time_ns = wake_up_time_ns;
|
||||
*out_predicted_gpu_time_ns = desired_present_time_ns; // Not quite right but close enough.
|
||||
*out_predicted_display_time_ns = predicted_display_time_ns;
|
||||
*out_predicted_display_period_ns = pacer.get_frame_duration();
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
|
||||
xrt_result_t compositor::mark_frame(int64_t frame_id,
|
||||
xrt_compositor_frame_point point,
|
||||
int64_t when_ns)
|
||||
{
|
||||
switch (point)
|
||||
{
|
||||
case XRT_COMPOSITOR_FRAME_POINT_WOKE:
|
||||
session.dump_time("wake_up", frame_id, when_ns);
|
||||
return XRT_SUCCESS;
|
||||
default:
|
||||
assert(false);
|
||||
}
|
||||
return XRT_ERROR_VULKAN;
|
||||
}
|
||||
|
||||
xrt_result_t compositor::layer_commit(xrt_graphics_sync_handle_t sync_handle)
|
||||
{
|
||||
u_graphics_sync_unref(&sync_handle);
|
||||
|
||||
// Move waited frame to rendering frame, clear waited.
|
||||
comp_frame_move_and_clear_locked(&frame.rendering, &frame.waited);
|
||||
|
||||
U_LOG_IFL_D(log_level, "frame %ld commit %d layers", frame.rendering.id, layer_accum.layer_count);
|
||||
|
||||
if (layer_accum.layer_count == 0 or not session.connected())
|
||||
{
|
||||
comp_frame_clear_locked(&frame.rendering);
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
|
||||
int i = acquire_image();
|
||||
if (i < 0)
|
||||
{
|
||||
comp_frame_clear_locked(&frame.rendering);
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
auto & view_info = images[i].view_info;
|
||||
images[i].frame_index = frame.rendering.id;
|
||||
view_info = {
|
||||
.display_time = session.get_offset().to_headset(frame.rendering.predicted_display_time_ns),
|
||||
.alpha = layer_accum.data.env_blend_mode == XRT_BLEND_MODE_ALPHA_BLEND,
|
||||
};
|
||||
|
||||
assert(images[i].fence.getStatus() == vk::Result::eNotReady);
|
||||
auto _ = vk.device.waitForFences(*fence, true, INT64_MAX);
|
||||
vk.device.resetFences(*fence);
|
||||
|
||||
session.dump_time("begin", frame.rendering.id, os_monotonic_get_ns());
|
||||
|
||||
cmd.reset();
|
||||
cmd.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
|
||||
|
||||
bool flip_y = false;
|
||||
std::array<vk::ImageView, 2> src;
|
||||
std::array<xrt_rect, 2> src_rect;
|
||||
std::array<xrt_fov, 2> src_fov;
|
||||
|
||||
// Check if we can pass a layer directly to foveation
|
||||
if (layer_accum.layer_count == 1 and
|
||||
(layer_accum.layers[0].data.type == XRT_LAYER_PROJECTION or
|
||||
layer_accum.layers[0].data.type == XRT_LAYER_PROJECTION_DEPTH))
|
||||
{
|
||||
const auto & layer = layer_accum.layers[0];
|
||||
for (int view = 0; view < 2; ++view)
|
||||
{
|
||||
const auto & data = (layer.data.type == XRT_LAYER_PROJECTION ? layer.data.proj.v : layer.data.depth.v)[view];
|
||||
src[view] = get_image_view(
|
||||
&get_layer_image(layer, view, data.sub.image_index),
|
||||
layer.data.flags,
|
||||
data.sub.array_index);
|
||||
src_rect[view] = data.sub.rect;
|
||||
src_fov[view] = data.fov;
|
||||
flip_y = layer.data.flip_y;
|
||||
view_info.pose[view] = xrt_cast(data.pose);
|
||||
view_info.fov[view] = xrt_cast(data.fov);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// no fast-path, squash layers
|
||||
std::array<xrt_pose, 2> poses;
|
||||
std::tie(poses, src_fov) = squasher.do_layers(
|
||||
vk.device,
|
||||
cmd,
|
||||
session.get_hmd(),
|
||||
pacer.get_frame_duration(),
|
||||
frame.rendering,
|
||||
layer_accum);
|
||||
|
||||
auto extent = squasher.extent();
|
||||
src_rect = {
|
||||
xrt_rect{
|
||||
.extent = {
|
||||
.w = int(extent.width),
|
||||
.h = int(extent.height),
|
||||
},
|
||||
},
|
||||
xrt_rect{
|
||||
.extent = {
|
||||
.w = int(extent.width),
|
||||
.h = int(extent.height),
|
||||
},
|
||||
},
|
||||
};
|
||||
src = squasher.get_views();
|
||||
|
||||
for (int view = 0; view < 2; ++view)
|
||||
{
|
||||
view_info.pose[view] = xrt_cast(poses[view]);
|
||||
view_info.fov[view] = xrt_cast(src_fov[view]);
|
||||
}
|
||||
}
|
||||
|
||||
vk::ImageMemoryBarrier2 target_barrier{
|
||||
.dstStageMask = vk::PipelineStageFlagBits2::eComputeShader,
|
||||
.dstAccessMask = vk::AccessFlagBits2::eShaderStorageWrite,
|
||||
.oldLayout = vk::ImageLayout::eUndefined,
|
||||
.newLayout = vk::ImageLayout::eGeneral,
|
||||
.image = images[i].image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = vk::RemainingArrayLayers,
|
||||
},
|
||||
};
|
||||
|
||||
cmd.pipelineBarrier2({
|
||||
.imageMemoryBarrierCount = 1,
|
||||
.pImageMemoryBarriers = &target_barrier,
|
||||
});
|
||||
|
||||
view_info.foveation = foveation.foveate(
|
||||
vk.device,
|
||||
cmd,
|
||||
images[i].view_y,
|
||||
images[i].view_cbcr,
|
||||
flip_y,
|
||||
src,
|
||||
src_rect,
|
||||
src_fov);
|
||||
|
||||
// FIXME: skip transfer layout in vulkan encode case
|
||||
target_barrier.srcAccessMask = target_barrier.dstAccessMask;
|
||||
target_barrier.srcStageMask = target_barrier.dstStageMask;
|
||||
target_barrier.oldLayout = target_barrier.newLayout;
|
||||
target_barrier.dstAccessMask = vk::AccessFlagBits2::eTransferRead;
|
||||
target_barrier.dstStageMask = vk::PipelineStageFlagBits2::eTransfer;
|
||||
target_barrier.newLayout = vk::ImageLayout::eTransferSrcOptimal;
|
||||
|
||||
cmd.pipelineBarrier2({
|
||||
.imageMemoryBarrierCount = 1,
|
||||
.pImageMemoryBarriers = &target_barrier,
|
||||
});
|
||||
cmd.end();
|
||||
|
||||
{
|
||||
std::unique_lock lock{vk.queue_mutex};
|
||||
vk.queue.submit(
|
||||
vk::SubmitInfo{
|
||||
.commandBufferCount = 1,
|
||||
.pCommandBuffers = &*cmd,
|
||||
.signalSemaphoreCount = 1,
|
||||
.pSignalSemaphores = &*images[i].sem,
|
||||
},
|
||||
*fence);
|
||||
}
|
||||
|
||||
images[i].cmd.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
|
||||
|
||||
auto info = pacer.present_to_info(frame.rendering.desired_present_time_ns);
|
||||
|
||||
bool need_queue_transfer = false;
|
||||
std::vector<vk::Semaphore> present_done_sem;
|
||||
for (auto & encoder: encoders)
|
||||
{
|
||||
if (encoder->stream_idx == 2 and not view_info.alpha)
|
||||
continue;
|
||||
auto [transfer, sem] = encoder->present_image(
|
||||
images[i].image,
|
||||
need_queue_transfer,
|
||||
images[i].cmd,
|
||||
info.frame_id);
|
||||
need_queue_transfer |= transfer;
|
||||
if (sem)
|
||||
present_done_sem.push_back(sem);
|
||||
}
|
||||
|
||||
vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eAllCommands;
|
||||
|
||||
vk::SubmitInfo submit_info{
|
||||
.waitSemaphoreCount = 1,
|
||||
.pWaitSemaphores = &*images[i].sem,
|
||||
.pWaitDstStageMask = &stages,
|
||||
};
|
||||
|
||||
#if WIVRN_USE_VULKAN_ENCODE
|
||||
if (need_queue_transfer)
|
||||
{
|
||||
vk::ImageMemoryBarrier2 video_barrier{
|
||||
.srcStageMask = vk::PipelineStageFlagBits2KHR::eTransfer,
|
||||
.srcAccessMask = vk::AccessFlagBits2::eMemoryRead,
|
||||
.dstStageMask = vk::PipelineStageFlagBits2KHR::eVideoEncodeKHR,
|
||||
.oldLayout = vk::ImageLayout::eTransferSrcOptimal,
|
||||
.newLayout = vk::ImageLayout::eVideoEncodeSrcKHR,
|
||||
.srcQueueFamilyIndex = vk.queue_family_index,
|
||||
.dstQueueFamilyIndex = vk.encode_queue_family_index,
|
||||
.image = images[i].image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = vk::RemainingArrayLayers,
|
||||
},
|
||||
};
|
||||
images[i].cmd.pipelineBarrier2({
|
||||
.imageMemoryBarrierCount = 1,
|
||||
.pImageMemoryBarriers = &video_barrier,
|
||||
});
|
||||
}
|
||||
submit_info.setSignalSemaphores(present_done_sem);
|
||||
#endif
|
||||
images[i].cmd.end();
|
||||
submit_info.setCommandBuffers(*images[i].cmd);
|
||||
|
||||
{
|
||||
std::unique_lock lock{vk.queue_mutex};
|
||||
vk.queue.submit(submit_info, *images[i].fence);
|
||||
for (auto & encoder: encoders)
|
||||
{
|
||||
if (encoder->stream_idx == 2 and not view_info.alpha)
|
||||
continue;
|
||||
encoder->post_submit();
|
||||
}
|
||||
}
|
||||
|
||||
auto j = encode_request.exchange(i);
|
||||
encode_request.notify_all();
|
||||
|
||||
// Now is a good point to garbage collect.
|
||||
comp_swapchain_shared_garbage_collect(&cscs);
|
||||
|
||||
if (j >= 0)
|
||||
{
|
||||
U_LOG_W("encoder skipped image %ld", images[j].frame_index);
|
||||
auto _ = vk.device.waitForFences(*images[j].fence, true, UINT64_MAX);
|
||||
images[j].busy = false;
|
||||
}
|
||||
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
|
||||
xrt_result_t compositor::get_display_refresh_rate(float * hz)
|
||||
{
|
||||
*hz = refresh_rate;
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
|
||||
xrt_result_t compositor::request_display_refresh_rate(float hz)
|
||||
{
|
||||
try
|
||||
{
|
||||
session.send_control(to_headset::refresh_rate_change{.fps = hz});
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
U_LOG_W("refresh rate change failed: %s", e.what());
|
||||
return XRT_ERROR_IPC_FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
int compositor::acquire_image()
|
||||
{
|
||||
for (auto [i, image]: std::ranges::enumerate_view(images))
|
||||
{
|
||||
if (not image.busy.exchange(true))
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void compositor::encoder_work(std::stop_token tok)
|
||||
{
|
||||
while (not tok.stop_requested())
|
||||
{
|
||||
auto req = encode_request.exchange(-1);
|
||||
if (req < 0)
|
||||
{
|
||||
encode_request.wait(req);
|
||||
continue;
|
||||
}
|
||||
|
||||
assert(req < images.size());
|
||||
auto & image = images[req];
|
||||
|
||||
auto _ = vk.device.waitForFences(*image.fence, true, UINT64_MAX);
|
||||
vk.device.resetFences(*image.fence);
|
||||
|
||||
try
|
||||
{
|
||||
for (auto & encoder: encoders)
|
||||
{
|
||||
if (encoder->stream_idx < 2 or image.view_info.alpha)
|
||||
encoder->encode(session, image.view_info, image.frame_index);
|
||||
}
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
U_LOG_W("encode error: %s", e.what());
|
||||
}
|
||||
image.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
void compositor::send_video_stream_description()
|
||||
|
||||
{
|
||||
to_headset::video_stream_description desc{
|
||||
.width = uint16_t(images[0].image.info().extent.width),
|
||||
.height = uint16_t(images[0].image.info().extent.height),
|
||||
.fps = settings[0].fps,
|
||||
};
|
||||
static_assert(std::tuple_size_v<decltype(settings)> == std::tuple_size_v<decltype(desc.codec)>);
|
||||
std::ranges::transform(settings, desc.codec.begin(), &encoder_settings::codec);
|
||||
session.send_control(std::move(desc));
|
||||
}
|
||||
|
||||
compositor::compositor(wivrn_session & session) :
|
||||
comp_base{
|
||||
.base = {
|
||||
.base = {
|
||||
.info{},
|
||||
.begin_session = method_pointer<&compositor::begin_session>,
|
||||
.end_session = method_pointer<&compositor::end_session>,
|
||||
.predict_frame = method_pointer<&compositor::predict_frame>,
|
||||
.mark_frame = method_pointer<&compositor::mark_frame>,
|
||||
.begin_frame = method_pointer<&compositor::begin_frame>,
|
||||
.discard_frame = method_pointer<&compositor::discard_frame>,
|
||||
.layer_commit = method_pointer<&compositor::layer_commit>,
|
||||
.get_display_refresh_rate = method_pointer<&compositor::get_display_refresh_rate>,
|
||||
.request_display_refresh_rate = method_pointer<&compositor::request_display_refresh_rate>,
|
||||
.destroy = method_pointer<&compositor::destroy>,
|
||||
},
|
||||
},
|
||||
},
|
||||
log_level(debug_get_log_option_log()),
|
||||
session(session),
|
||||
cmd_pool(vk.device, vk::CommandPoolCreateInfo{
|
||||
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
|
||||
.queueFamilyIndex = vk.queue_family_index,
|
||||
}),
|
||||
settings(get_encoder_settings(vk, session)),
|
||||
images{make_images(vk, cmd_pool, settings)},
|
||||
cmd{std::move(vk.device.allocateCommandBuffers({.commandPool = *cmd_pool, .commandBufferCount = 1})[0])},
|
||||
fence{make_fence(vk, "compositor fence")},
|
||||
refresh_rate(settings[0].fps),
|
||||
pacer(U_TIME_1S_IN_NS / refresh_rate),
|
||||
squasher(vk, render_extent(session.get_info())),
|
||||
foveation(vk, images[0].image.info().extent),
|
||||
encoder_thread{[&](std::stop_token t) { encoder_work(t); }}
|
||||
{
|
||||
comp_base * c_base = this;
|
||||
// Ensure we can safely cast pointers
|
||||
assert(intptr_t(&base) == intptr_t(this));
|
||||
auto res = vk_init_from_given(
|
||||
&c_base->vk,
|
||||
(PFN_vkGetInstanceProcAddr)vk.instance.getProcAddr("vkGetInstanceProcAddr"),
|
||||
*vk.instance,
|
||||
*vk.physical_device,
|
||||
*vk.device,
|
||||
vk.queue_family_index,
|
||||
0,
|
||||
vk.has_device_ext(VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME),
|
||||
vk.has_device_ext(VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME),
|
||||
std::get<vk::PhysicalDeviceVulkan12Features>(vk.feat).timelineSemaphore,
|
||||
true, // in Vulkan 1.2
|
||||
vk.has_instance_ext(VK_EXT_DEBUG_UTILS_EXTENSION_NAME),
|
||||
log_level);
|
||||
vk::detail::resultCheck(vk::Result(res), "vk_init_from_given");
|
||||
|
||||
// vk_init_from_given assumes a graphics queue was provided
|
||||
c_base->vk.graphics_queue = nullptr;
|
||||
|
||||
if (c_base->vk.main_queue)
|
||||
c_base->vk.main_queue->mutex = copy_mutex(vk.queue_mutex);
|
||||
if (c_base->vk.encode_queue)
|
||||
c_base->vk.encode_queue->mutex = copy_mutex(vk.encode_queue_mutex);
|
||||
|
||||
{
|
||||
comp_vulkan_formats formats{};
|
||||
comp_vulkan_formats_check(&c_base->vk, &formats);
|
||||
comp_vulkan_formats_copy_to_info(&formats, &base.base.info);
|
||||
comp_vulkan_formats_log(log_level, &formats);
|
||||
}
|
||||
|
||||
comp_base_init(this);
|
||||
|
||||
// Tie the lifetimes of swapchains to Vulkan.
|
||||
xrt_result_t xret = comp_swapchain_shared_init(&cscs, &c_base->vk);
|
||||
if (xret != XRT_SUCCESS)
|
||||
throw std::runtime_error("comp_swapchain_shared_init failed");
|
||||
|
||||
print_encoders(settings);
|
||||
for (auto [i, settings]: std::ranges::enumerate_view(settings))
|
||||
encoders[i] = video_encoder::create(vk, settings, i);
|
||||
send_video_stream_description();
|
||||
}
|
||||
|
||||
compositor::~compositor()
|
||||
{
|
||||
encoder_thread.request_stop();
|
||||
encode_request = -2;
|
||||
encode_request.notify_all();
|
||||
comp_base * c_base = this;
|
||||
comp_swapchain_shared_garbage_collect(&cscs);
|
||||
comp_swapchain_shared_destroy(&cscs, &c_base->vk);
|
||||
comp_base_fini(this);
|
||||
}
|
||||
|
||||
xrt_system_compositor_info compositor::sys_info() const
|
||||
{
|
||||
auto [prop, dev_id] = vk.physical_device.getProperties2<vk::PhysicalDeviceProperties2, vk::PhysicalDeviceIDProperties>();
|
||||
xrt_system_compositor_info res{
|
||||
.view_config_count = 1,
|
||||
.view_configs = {
|
||||
{
|
||||
.view_type = XRT_VIEW_TYPE_STEREO,
|
||||
.view_count = 2,
|
||||
.views = {},
|
||||
},
|
||||
},
|
||||
.max_layers = squasher.max_layers(prop.properties),
|
||||
.supported_blend_modes = {
|
||||
XRT_BLEND_MODE_OPAQUE,
|
||||
XRT_BLEND_MODE_ALPHA_BLEND,
|
||||
},
|
||||
.supported_blend_mode_count = uint8_t(1 + session.get_info().passthrough),
|
||||
.supports_fov_mutable = true,
|
||||
};
|
||||
|
||||
std::ranges::copy(dev_id.deviceUUID, res.compositor_vk_deviceUUID.data);
|
||||
std::ranges::copy(dev_id.deviceUUID, res.client_vk_deviceUUID.data);
|
||||
|
||||
const auto extent = render_extent(session.get_info());
|
||||
for (auto & view: std::span(res.view_configs[0].views, res.view_configs[0].view_count))
|
||||
{
|
||||
view = {
|
||||
.recommended = {
|
||||
.width_pixels = extent.width,
|
||||
.height_pixels = extent.height,
|
||||
.sample_count = 1,
|
||||
},
|
||||
.max = {
|
||||
.width_pixels = extent.width * 2u,
|
||||
.height_pixels = extent.height * 2u,
|
||||
.sample_count = 1,
|
||||
},
|
||||
};
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
void compositor::set_bitrate(uint32_t bitrate)
|
||||
{
|
||||
for (auto & encoder: encoders)
|
||||
encoder->set_bitrate(bitrate);
|
||||
}
|
||||
|
||||
void compositor::set_refresh_rate(float hz)
|
||||
{
|
||||
U_LOG_IFL_D(log_level, "Refresh rate change from %.0f to %.0f", refresh_rate.load(), hz);
|
||||
refresh_rate = hz;
|
||||
pacer.set_frame_duration(U_TIME_1S_IN_NS / hz);
|
||||
for (auto & encoder: encoders)
|
||||
encoder->set_framerate(hz);
|
||||
}
|
||||
|
||||
void compositor::update_tracking(const from_headset::tracking & tracking)
|
||||
{
|
||||
foveation.update_tracking(tracking);
|
||||
}
|
||||
|
||||
void compositor::update_foveation_center_override(const from_headset::override_foveation_center & center)
|
||||
{
|
||||
foveation.update_foveation_center_override(center);
|
||||
}
|
||||
|
||||
void compositor::on_feedback(const from_headset::feedback & feedback, const clock_offset & o)
|
||||
{
|
||||
uint8_t stream = feedback.stream_index;
|
||||
if (stream >= encoders.size())
|
||||
return;
|
||||
encoders[stream]->on_feedback(feedback);
|
||||
if (not o)
|
||||
return;
|
||||
pacer.on_feedback(feedback, o);
|
||||
}
|
||||
|
||||
} // namespace wivrn
|
||||
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright 2019-2024, Collabora, Ltd.
|
||||
// Copyright 2025-2026, NVIDIA CORPORATION.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "util/comp_base.h"
|
||||
#include "util/u_logging.h"
|
||||
|
||||
#include "encoder/encoder_settings.h"
|
||||
#include "foveation.h"
|
||||
#include "layer_squasher.h"
|
||||
#include "pacer.h"
|
||||
#include "utils/wivrn_vk_bundle.h"
|
||||
|
||||
#include "main/comp_compositor.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
class wivrn_session;
|
||||
class video_encoder;
|
||||
|
||||
class compositor : public comp_base
|
||||
{
|
||||
public:
|
||||
struct image
|
||||
{
|
||||
std::atomic<bool> busy = false;
|
||||
vk::raii::Semaphore sem;
|
||||
vk::raii::Fence fence;
|
||||
vk::raii::CommandBuffer cmd;
|
||||
image_allocation image;
|
||||
vk::raii::ImageView view_y;
|
||||
vk::raii::ImageView view_cbcr;
|
||||
to_headset::video_stream_data_shard::view_info_t view_info{};
|
||||
uint64_t frame_index;
|
||||
};
|
||||
|
||||
private:
|
||||
const u_logging_level log_level;
|
||||
wivrn_session & session;
|
||||
vk_bundle vk;
|
||||
vk::raii::CommandPool cmd_pool;
|
||||
|
||||
std::array<encoder_settings, 3> settings;
|
||||
|
||||
std::array<image, 2> images;
|
||||
vk::raii::CommandBuffer cmd;
|
||||
vk::raii::Fence fence;
|
||||
|
||||
std::atomic<float> requested_refresh_rate;
|
||||
std::atomic<float> refresh_rate;
|
||||
wivrn::pacer pacer;
|
||||
|
||||
layer_squasher squasher;
|
||||
wivrn::foveation foveation;
|
||||
|
||||
std::array<std::unique_ptr<video_encoder>, 3> encoders;
|
||||
|
||||
#ifdef __cpp_lib_atomic_lock_free_type_aliases
|
||||
using status_type = std::atomic_signed_lock_free;
|
||||
#else
|
||||
using status_type = std::atomic_int8_t;
|
||||
#endif
|
||||
status_type encode_request{-1}; // id of the image to encode
|
||||
std::jthread encoder_thread;
|
||||
|
||||
struct
|
||||
{
|
||||
comp_frame waited{.id = -1};
|
||||
comp_frame rendering{.id = -1};
|
||||
} frame;
|
||||
|
||||
xrt_result_t begin_session(const xrt_begin_session_info * info)
|
||||
{
|
||||
return XRT_SUCCESS;
|
||||
};
|
||||
xrt_result_t end_session()
|
||||
{
|
||||
return XRT_SUCCESS;
|
||||
};
|
||||
|
||||
xrt_result_t predict_frame(int64_t * out_frame_id,
|
||||
int64_t * out_wake_time_ns,
|
||||
int64_t * out_predicted_gpu_time_ns,
|
||||
int64_t * out_predicted_display_time_ns,
|
||||
int64_t * out_predicted_display_period_ns);
|
||||
|
||||
xrt_result_t mark_frame(int64_t frame_id,
|
||||
xrt_compositor_frame_point point,
|
||||
int64_t when_ns);
|
||||
|
||||
xrt_result_t begin_frame(int64_t frame_id)
|
||||
{
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
xrt_result_t discard_frame(int64_t frame_id)
|
||||
{
|
||||
return XRT_SUCCESS;
|
||||
};
|
||||
|
||||
xrt_result_t layer_commit(xrt_graphics_sync_handle_t sync_handle);
|
||||
|
||||
xrt_result_t get_display_refresh_rate(float * out_display_refresh_rate_hz);
|
||||
|
||||
public:
|
||||
xrt_result_t request_display_refresh_rate(float display_refresh_rate_hz);
|
||||
|
||||
private:
|
||||
void destroy()
|
||||
{
|
||||
// do nothing, actually owned by wivrn_session object
|
||||
}
|
||||
|
||||
int acquire_image();
|
||||
|
||||
void encoder_work(std::stop_token);
|
||||
|
||||
void send_video_stream_description();
|
||||
|
||||
public:
|
||||
using base_t = xrt_compositor;
|
||||
compositor(wivrn_session &);
|
||||
~compositor();
|
||||
|
||||
xrt_system_compositor_info sys_info() const;
|
||||
|
||||
int64_t get_frame_duration() const
|
||||
{
|
||||
return pacer.get_frame_duration();
|
||||
}
|
||||
|
||||
float get_requested_refresh_rate() const
|
||||
{
|
||||
return requested_refresh_rate;
|
||||
}
|
||||
|
||||
float get_refresh_rate() const
|
||||
{
|
||||
return refresh_rate;
|
||||
}
|
||||
void set_refresh_rate(float hz);
|
||||
|
||||
void set_bitrate(uint32_t);
|
||||
void update_tracking(const from_headset::tracking &);
|
||||
void update_foveation_center_override(const from_headset::override_foveation_center &);
|
||||
|
||||
void on_feedback(const from_headset::feedback &, const clock_offset &);
|
||||
};
|
||||
|
||||
} // namespace wivrn
|
||||
@@ -0,0 +1,658 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2024 galister <galister@librevr.org>
|
||||
* Copyright (C) 2025 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "foveation.h"
|
||||
|
||||
#include "driver/xrt_cast.h"
|
||||
#include "utils/wivrn_vk_bundle.h"
|
||||
#include "wivrn_packets.h"
|
||||
|
||||
#include "xrt/xrt_defines.h"
|
||||
#include "xrt/xrt_limits.h"
|
||||
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <ranges>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
#include <vulkan/vulkan_structs.hpp>
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
#define RENDER_FOVEATION_BUFFER_DIMENSIONS (4096 + 1)
|
||||
|
||||
namespace
|
||||
{
|
||||
struct ubo_data
|
||||
{
|
||||
uint32_t x[XRT_MAX_VIEWS * RENDER_FOVEATION_BUFFER_DIMENSIONS];
|
||||
uint32_t y[XRT_MAX_VIEWS * RENDER_FOVEATION_BUFFER_DIMENSIONS];
|
||||
uint32_t alpha_width;
|
||||
};
|
||||
|
||||
vk::raii::Sampler make_sampler(wivrn::vk_bundle & vk)
|
||||
{
|
||||
vk::raii::Sampler res(
|
||||
vk.device,
|
||||
vk::SamplerCreateInfo{
|
||||
.magFilter = vk::Filter::eLinear,
|
||||
.minFilter = vk::Filter::eLinear,
|
||||
.mipmapMode = vk::SamplerMipmapMode::eLinear,
|
||||
.addressModeU = vk::SamplerAddressMode::eClampToBorder,
|
||||
.addressModeV = vk::SamplerAddressMode::eClampToBorder,
|
||||
.addressModeW = vk::SamplerAddressMode::eClampToBorder,
|
||||
.borderColor = vk::BorderColor::eFloatOpaqueBlack,
|
||||
});
|
||||
vk.name(res, "foveation sampler");
|
||||
return res;
|
||||
}
|
||||
|
||||
vk::raii::DescriptorSetLayout make_ds_layout(wivrn::vk_bundle & vk)
|
||||
{
|
||||
std::array bindings{
|
||||
vk::DescriptorSetLayoutBinding{
|
||||
.binding = 0,
|
||||
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
|
||||
.descriptorCount = 2,
|
||||
.stageFlags = vk::ShaderStageFlagBits::eCompute,
|
||||
},
|
||||
vk::DescriptorSetLayoutBinding{
|
||||
.binding = 1,
|
||||
.descriptorType = vk::DescriptorType::eStorageBuffer,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = vk::ShaderStageFlagBits::eCompute,
|
||||
},
|
||||
vk::DescriptorSetLayoutBinding{
|
||||
.binding = 2,
|
||||
.descriptorType = vk::DescriptorType::eStorageImage,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = vk::ShaderStageFlagBits::eCompute,
|
||||
},
|
||||
vk::DescriptorSetLayoutBinding{
|
||||
.binding = 3,
|
||||
.descriptorType = vk::DescriptorType::eStorageImage,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = vk::ShaderStageFlagBits::eCompute,
|
||||
},
|
||||
};
|
||||
vk::raii::DescriptorSetLayout res{
|
||||
vk.device,
|
||||
vk::DescriptorSetLayoutCreateInfo{
|
||||
.bindingCount = bindings.size(),
|
||||
.pBindings = bindings.data(),
|
||||
},
|
||||
};
|
||||
vk.name(*res, "foveation descriptor set layout");
|
||||
return res;
|
||||
}
|
||||
|
||||
vk::raii::PipelineLayout make_layout(wivrn::vk_bundle & vk, vk::DescriptorSetLayout ds_layout)
|
||||
{
|
||||
vk::raii::PipelineLayout res(vk.device,
|
||||
vk::PipelineLayoutCreateInfo{
|
||||
.setLayoutCount = 1,
|
||||
.pSetLayouts = &ds_layout,
|
||||
});
|
||||
vk.name(*res, "foveation pipeline layout");
|
||||
return res;
|
||||
}
|
||||
|
||||
vk::raii::Pipeline make_pipeline(wivrn::vk_bundle & vk, vk::PipelineLayout layout)
|
||||
{
|
||||
vk::raii::Pipeline res(
|
||||
vk.device,
|
||||
nullptr,
|
||||
vk::ComputePipelineCreateInfo{
|
||||
.stage = {
|
||||
.stage = vk::ShaderStageFlagBits::eCompute,
|
||||
.module = *vk.load_shader("foveation"),
|
||||
.pName = "main",
|
||||
},
|
||||
.layout = layout,
|
||||
});
|
||||
vk.name(*res, "foveation pipeline");
|
||||
return res;
|
||||
}
|
||||
|
||||
vk::raii::DescriptorPool make_ds_pool(wivrn::vk_bundle & vk)
|
||||
{
|
||||
std::array pool_sizes{
|
||||
vk::DescriptorPoolSize{
|
||||
.type = vk::DescriptorType::eCombinedImageSampler,
|
||||
.descriptorCount = 2,
|
||||
},
|
||||
vk::DescriptorPoolSize{
|
||||
.type = vk::DescriptorType::eStorageImage,
|
||||
.descriptorCount = 2,
|
||||
},
|
||||
vk::DescriptorPoolSize{
|
||||
.type = vk::DescriptorType::eStorageBuffer,
|
||||
.descriptorCount = 1,
|
||||
},
|
||||
};
|
||||
vk::raii::DescriptorPool res{
|
||||
vk.device,
|
||||
vk::DescriptorPoolCreateInfo{
|
||||
.maxSets = 5,
|
||||
.poolSizeCount = pool_sizes.size(),
|
||||
.pPoolSizes = pool_sizes.data(),
|
||||
},
|
||||
};
|
||||
vk.name(*res, "foveation descriptor pool");
|
||||
return res;
|
||||
}
|
||||
uint32_t divide_and_round_up(uint32_t a, uint32_t b)
|
||||
{
|
||||
return (a + (b - 1)) / b;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// a, b: parameters computed by solve_foveation
|
||||
// λ: pixel ratio between full size and foveated image (in range ]0,1[)
|
||||
// c: coordinates in -1,1 range of the full size image where pixel ratio must be 1:1
|
||||
// x: coordinates in -1,1 range of the foveated image
|
||||
// result: full size image coordinates in -1,1 range
|
||||
static double defoveate(double a, double b, double λ, double c, double x)
|
||||
{
|
||||
// In order to save encoding, transmit and decoding time, only a portion of the image is encoded in full resolution.
|
||||
// on each axis, foveated coordinates are defined by the following formula.
|
||||
return λ / a * tan(a * x + b) + c;
|
||||
// a and b are defined such as:
|
||||
// edges of the image are not moved
|
||||
// f(-1) = -1
|
||||
// f( 1) = 1
|
||||
// the function also enforces pixel ratio 1:1 at fovea
|
||||
// df⁻¹(x)/dx = 1/scale for x = c
|
||||
|
||||
// We then ensure that source and destination pixel grids match by
|
||||
// rounding to integer pixel ratios: 1:1, 1:2 etc.
|
||||
// Finally, pixel spans are sorted so that we only have increasing
|
||||
// ratios going out from the center.
|
||||
}
|
||||
|
||||
static std::tuple<float, float> solve_foveation(float λ, float c)
|
||||
{
|
||||
// Compute a and b for the foveation function such that:
|
||||
// foveate(a, b, scale, c, -1) = -1 (eq. 1)
|
||||
// foveate(a, b, scale, c, 1) = 1 (eq. 2)
|
||||
//
|
||||
// Use eq. 2 to express a as function of b, then replace in eq. 1
|
||||
// equation that needs to be null is:
|
||||
auto b = [λ, c](double a) { return atan(a * (1 - c) / λ) - a; };
|
||||
auto eq = [λ, c](double a) { return atan(a * (1 - c) / λ) + atan(a * (1 + c) / λ) - 2 * a; }; // (eq. 3)
|
||||
|
||||
// function starts positive, reaches a maximum then decreases to -∞
|
||||
double a0 = 0;
|
||||
// Find a negative value by computing eq(2^n)
|
||||
double a1 = 1;
|
||||
while (eq(a1) > 0)
|
||||
a1 *= 2;
|
||||
|
||||
// last computed values for f(a0) and f(a1)
|
||||
std::optional<double> f_a0;
|
||||
double f_a1 = eq(a1);
|
||||
|
||||
int n = 0;
|
||||
double a = 0;
|
||||
while (std::abs(a1 - a0) > 0.0000001 && n++ < 100)
|
||||
{
|
||||
if (not f_a0)
|
||||
{
|
||||
// use binary search
|
||||
a = 0.5 * (a0 + a1);
|
||||
double val = eq(a);
|
||||
if (val > 0)
|
||||
{
|
||||
a0 = a;
|
||||
f_a0 = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
a1 = a;
|
||||
f_a1 = val;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// f(a1) is always defined
|
||||
// when f(a0) is defined, use secant method
|
||||
a = a1 - f_a1 * (a1 - a0) / (f_a1 - *f_a0);
|
||||
a0 = a1;
|
||||
a1 = a;
|
||||
f_a0 = f_a1;
|
||||
f_a1 = eq(a);
|
||||
}
|
||||
}
|
||||
|
||||
return {a, b(a)};
|
||||
}
|
||||
|
||||
static bool is_zero_quat(xrt_quat q)
|
||||
{
|
||||
return q.x == 0 and q.y == 0 and q.z == 0 and q.w == 0;
|
||||
}
|
||||
|
||||
static xrt_vec2 yaw_pitch(xrt_quat q)
|
||||
{
|
||||
if (is_zero_quat(q))
|
||||
return xrt_vec2{};
|
||||
|
||||
float sine_theta = std::clamp(-2.0f * (q.y * q.z - q.w * q.x), -1.0f, 1.0f);
|
||||
|
||||
float pitch = std::asin(sine_theta);
|
||||
|
||||
if (std::abs(sine_theta) > 0.99999f)
|
||||
{
|
||||
float scale = std::copysign(2.0, sine_theta);
|
||||
return {scale * std::atan2(-q.z, q.w), pitch};
|
||||
}
|
||||
|
||||
return {
|
||||
std::atan2(2.0f * (q.x * q.z + q.w * q.y),
|
||||
q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z),
|
||||
pitch};
|
||||
}
|
||||
|
||||
static float angles_to_center(float e, float l, float r)
|
||||
{
|
||||
e = tan(e);
|
||||
l = tan(l);
|
||||
r = tan(r);
|
||||
float res = std::clamp((e - l) / (r - l) * 2 - 1, -1.f, 1.f);
|
||||
// If the center isn't in the FoV, fallback to middle of image
|
||||
if (std::isnan(res))
|
||||
return 0;
|
||||
return res;
|
||||
}
|
||||
|
||||
static float convergence_angle(float distance, float eye_x, float gaze_yaw)
|
||||
{
|
||||
auto b = distance * std::sin(gaze_yaw) - eye_x;
|
||||
return std::asin(b / distance);
|
||||
}
|
||||
|
||||
static void fill_param_2d(
|
||||
float c,
|
||||
size_t foveated_dim,
|
||||
size_t source_dim,
|
||||
std::vector<uint16_t> & out)
|
||||
{
|
||||
float scale = float(foveated_dim) / source_dim;
|
||||
auto [a, b] = solve_foveation(scale, c);
|
||||
|
||||
uint16_t last = 0;
|
||||
std::vector<uint16_t> left; // index 0: 1:1 ratio, then 2:1 etc.
|
||||
std::vector<uint16_t> right;
|
||||
for (size_t i = 1; i < foveated_dim; ++i)
|
||||
{
|
||||
double u = (i * 2.) / foveated_dim - 1;
|
||||
auto f = defoveate(a, b, scale, c, u);
|
||||
uint16_t n = std::clamp<uint16_t>((f * 0.5 + 0.5) * source_dim + 0.5, 0, source_dim);
|
||||
assert(n > last);
|
||||
size_t count = n - last;
|
||||
auto & vec = u < c ? left : right;
|
||||
if (count > vec.size())
|
||||
vec.resize(count);
|
||||
vec[count - 1]++;
|
||||
last = n;
|
||||
}
|
||||
assert(last < source_dim);
|
||||
size_t count = source_dim - last;
|
||||
if (count > right.size())
|
||||
right.resize(count);
|
||||
right[count - 1]++;
|
||||
|
||||
count = std::max(left.size(), right.size());
|
||||
out.clear();
|
||||
out.resize(count - left.size());
|
||||
out.insert(out.end(), left.rbegin(), left.rend());
|
||||
if (not right.empty())
|
||||
out.back() += right.front();
|
||||
if (right.size() > 1)
|
||||
out.insert(out.end(), right.begin() + 1, right.end());
|
||||
out.resize(count * 2 - 1);
|
||||
}
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
void foveation::compute_params()
|
||||
{
|
||||
auto e = yaw_pitch(gaze);
|
||||
|
||||
if (manual_foveation.enabled)
|
||||
e.y = manual_foveation.pitch;
|
||||
|
||||
for (size_t i = 0; i < 2; ++i)
|
||||
{
|
||||
const auto & fov = last.fovs[i];
|
||||
|
||||
size_t extent_w = std::abs(last.src[i].extent.w);
|
||||
if (foveated_size.width < extent_w)
|
||||
{
|
||||
auto distance = manual_foveation.enabled ? manual_foveation.distance : convergence_distance;
|
||||
auto angle_x = convergence_angle(distance, eye_x[i], -e.x);
|
||||
auto center = angles_to_center(angle_x, fov.angle_left, fov.angle_right);
|
||||
fill_param_2d(center, foveated_size.width, extent_w, params[i].x);
|
||||
}
|
||||
else
|
||||
params[i].x = {uint16_t(last.src[i].extent.w)};
|
||||
|
||||
size_t extent_h = std::abs(last.src[i].extent.h);
|
||||
if (foveated_size.height < extent_h)
|
||||
{
|
||||
auto angle_y = -e.y;
|
||||
if (is_zero_quat(gaze) and not manual_foveation.enabled)
|
||||
{
|
||||
// Natural gaze is not straight forward, adjust the angle
|
||||
angle_y += angle_offset;
|
||||
}
|
||||
auto center = angles_to_center(-angle_y, fov.angle_up, fov.angle_down);
|
||||
fill_param_2d(center, foveated_size.height, extent_h, params[i].y);
|
||||
}
|
||||
else
|
||||
params[i].y = {uint16_t(last.src[i].extent.h)};
|
||||
}
|
||||
}
|
||||
|
||||
foveation::foveation(wivrn::vk_bundle & bundle, vk::Extent3D foveated_size) :
|
||||
foveated_size(foveated_size),
|
||||
// normal sight line is between 10° and 15° below horizontal
|
||||
// https://apps.dtic.mil/sti/tr/pdf/AD0758339.pdf pages 393-394
|
||||
// testing shows 10° looks better
|
||||
angle_offset(10 * M_PI / 180),
|
||||
convergence_distance(1 /* meter*/),
|
||||
gpu_buffer(
|
||||
bundle.device,
|
||||
{
|
||||
.size = sizeof(ubo_data),
|
||||
.usage = vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eStorageBuffer,
|
||||
},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
},
|
||||
"foveation storage buffer"),
|
||||
sampler(make_sampler(bundle)),
|
||||
ds_layout(make_ds_layout(bundle)),
|
||||
layout(make_layout(bundle, ds_layout)),
|
||||
pipeline(make_pipeline(bundle, layout)),
|
||||
descriptor_pool(make_ds_pool(bundle)),
|
||||
descriptor_set(bundle.device.allocateDescriptorSets(vk::DescriptorSetAllocateInfo{
|
||||
.descriptorPool = descriptor_pool,
|
||||
.descriptorSetCount = 1,
|
||||
.pSetLayouts = &*ds_layout,
|
||||
})[0]
|
||||
.release())
|
||||
{
|
||||
if (not(gpu_buffer.properties() & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT))
|
||||
{
|
||||
host_buffer = buffer_allocation(
|
||||
bundle.device,
|
||||
{
|
||||
.size = gpu_buffer.info().size,
|
||||
.usage = vk::BufferUsageFlagBits::eTransferSrc,
|
||||
},
|
||||
{
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST,
|
||||
},
|
||||
"foveation staging buffer");
|
||||
}
|
||||
|
||||
bundle.name(descriptor_set, "foveation descriptor set");
|
||||
}
|
||||
|
||||
void foveation::update_tracking(const from_headset::tracking & tracking)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
|
||||
const uint8_t orientation_ok = from_headset::tracking::orientation_valid | from_headset::tracking::orientation_tracked;
|
||||
|
||||
if (tracking.view_flags & XR_VIEW_STATE_POSITION_VALID_BIT)
|
||||
{
|
||||
eye_x[0] = tracking.views[0].pose.position.x;
|
||||
eye_x[1] = tracking.views[1].pose.position.x;
|
||||
}
|
||||
|
||||
for (const auto & pose: tracking.device_poses)
|
||||
{
|
||||
if (pose.device != device_id::EYE_GAZE)
|
||||
continue;
|
||||
|
||||
if ((pose.flags & orientation_ok) != orientation_ok)
|
||||
return;
|
||||
|
||||
gaze = xrt_cast(pose.pose.orientation);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void foveation::update_foveation_center_override(const from_headset::override_foveation_center & center)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
manual_foveation = center;
|
||||
}
|
||||
|
||||
static void fill_ubo(
|
||||
std::span<uint32_t> ubo,
|
||||
const std::vector<uint16_t> & params,
|
||||
bool flip,
|
||||
size_t offset,
|
||||
size_t size,
|
||||
[[maybe_unused]] int count)
|
||||
{
|
||||
assert(params.size() % 2 == 1);
|
||||
const int n_ratio = (params.size() - 1) / 2;
|
||||
ubo[0] = offset;
|
||||
if (flip)
|
||||
ubo[0] += size;
|
||||
for (auto [i, n]: std::ranges::enumerate_view(params))
|
||||
{
|
||||
const int n_source = std::abs(n_ratio - int(i)) + 1;
|
||||
for (size_t j = 0; j < n; ++j)
|
||||
{
|
||||
assert(count > 0);
|
||||
if (flip)
|
||||
ubo[1] = ubo[0] - n_source;
|
||||
else
|
||||
ubo[1] = ubo[0] + n_source;
|
||||
ubo = ubo.subspan(1);
|
||||
--count;
|
||||
}
|
||||
}
|
||||
if (not ubo.empty())
|
||||
std::ranges::fill(ubo, ubo[0]);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
static bool operator==(const T & a, const T & b)
|
||||
{
|
||||
static_assert(std::has_unique_object_representations_v<T>);
|
||||
return std::memcmp(&a, &b, sizeof(T)) == 0;
|
||||
}
|
||||
static bool operator==(const xrt_quat & a, const xrt_quat & b)
|
||||
{
|
||||
return a.x == b.x and a.y == b.y and a.z == b.z and a.w == b.w;
|
||||
}
|
||||
static bool operator==(const xrt_fov & a, const xrt_fov & b)
|
||||
{
|
||||
return a.angle_left == b.angle_left and a.angle_right == b.angle_right and a.angle_up == b.angle_up and a.angle_down == b.angle_down;
|
||||
}
|
||||
void foveation::update_ubo(
|
||||
vk::raii::CommandBuffer & cmd,
|
||||
bool flip_y,
|
||||
std::array<xrt_rect, 2> src_rect,
|
||||
std::array<xrt_fov, 2> src_fov)
|
||||
{
|
||||
// Check if the last value is still valid
|
||||
std::lock_guard lock(mutex);
|
||||
if (last.flip_y == flip_y and
|
||||
last.src[0] == src_rect[0] and
|
||||
last.src[1] == src_rect[1] and
|
||||
last.fovs[0] == src_fov[0] and
|
||||
last.fovs[1] == src_fov[1] and
|
||||
(last.gaze == gaze or manual_foveation.enabled) and // Ignore the gaze if foveation center is overridden
|
||||
std::abs(last.eye_x[0] - eye_x[0]) < 0.0005 and
|
||||
std::abs(last.eye_x[1] - eye_x[1]) < 0.0005 and
|
||||
last.manual_foveation.enabled == manual_foveation.enabled and
|
||||
std::abs(last.manual_foveation.pitch - manual_foveation.pitch) < 0.0005 and
|
||||
std::abs(last.manual_foveation.distance - manual_foveation.distance) < 0.0005)
|
||||
return;
|
||||
|
||||
if (host_buffer)
|
||||
cmd.copyBuffer(host_buffer, gpu_buffer, vk::BufferCopy{.size = sizeof(ubo_data)});
|
||||
|
||||
last = {
|
||||
.gaze = gaze,
|
||||
.flip_y = flip_y,
|
||||
.src = {src_rect[0], src_rect[1]},
|
||||
.fovs = {src_fov[0], src_fov[1]},
|
||||
.eye_x = {eye_x[0], eye_x[1]},
|
||||
.manual_foveation = manual_foveation,
|
||||
};
|
||||
|
||||
compute_params();
|
||||
|
||||
auto ubo = host_buffer ? host_buffer.data<ubo_data>() : gpu_buffer.data<ubo_data>();
|
||||
ubo->alpha_width = foveated_size.width / 2;
|
||||
for (size_t view = 0; view < 2; ++view)
|
||||
{
|
||||
bool flip = false;
|
||||
size_t offset, extent;
|
||||
|
||||
if (src_rect[view].extent.w < 0)
|
||||
{
|
||||
flip = true;
|
||||
offset = src_rect[view].offset.w + src_rect[view].extent.w;
|
||||
extent = -src_rect[view].extent.w;
|
||||
}
|
||||
else
|
||||
{
|
||||
offset = src_rect[view].offset.w;
|
||||
extent = src_rect[view].extent.w;
|
||||
}
|
||||
fill_ubo(std::span(ubo->x + view * RENDER_FOVEATION_BUFFER_DIMENSIONS, RENDER_FOVEATION_BUFFER_DIMENSIONS),
|
||||
params[view].x,
|
||||
flip,
|
||||
offset,
|
||||
extent,
|
||||
foveated_size.width);
|
||||
|
||||
if (src_rect[view].extent.h < 0)
|
||||
{
|
||||
flip = not flip_y;
|
||||
offset = src_rect[view].offset.h + src_rect[view].extent.h;
|
||||
extent = -src_rect[view].extent.h;
|
||||
}
|
||||
else
|
||||
{
|
||||
flip = flip_y;
|
||||
offset = src_rect[view].offset.h;
|
||||
extent = src_rect[view].extent.h;
|
||||
}
|
||||
fill_ubo(std::span(ubo->y + view * RENDER_FOVEATION_BUFFER_DIMENSIONS, RENDER_FOVEATION_BUFFER_DIMENSIONS),
|
||||
params[view].y,
|
||||
flip,
|
||||
offset,
|
||||
extent,
|
||||
foveated_size.height);
|
||||
}
|
||||
}
|
||||
|
||||
std::array<to_headset::foveation_parameter, 2> foveation::foveate(
|
||||
vk::raii::Device & device,
|
||||
vk::raii::CommandBuffer & cmd,
|
||||
vk::ImageView y,
|
||||
vk::ImageView cbcr,
|
||||
bool flip_y,
|
||||
std::array<vk::ImageView, 2> src,
|
||||
std::array<xrt_rect, 2> src_rect,
|
||||
std::array<xrt_fov, 2> src_fov)
|
||||
{
|
||||
update_ubo(cmd, flip_y, src_rect, src_fov);
|
||||
|
||||
std::array src_image_info{
|
||||
vk::DescriptorImageInfo{
|
||||
.sampler = *sampler,
|
||||
.imageView = src[0],
|
||||
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
|
||||
},
|
||||
vk::DescriptorImageInfo{
|
||||
.sampler = *sampler,
|
||||
.imageView = src[1],
|
||||
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
|
||||
},
|
||||
};
|
||||
|
||||
vk::DescriptorBufferInfo ubo_info{
|
||||
.buffer = gpu_buffer,
|
||||
.range = vk::WholeSize,
|
||||
};
|
||||
|
||||
vk::DescriptorImageInfo y_info{
|
||||
.imageView = y,
|
||||
.imageLayout = vk::ImageLayout::eGeneral,
|
||||
};
|
||||
vk::DescriptorImageInfo cbcr_info{
|
||||
.imageView = cbcr,
|
||||
.imageLayout = vk::ImageLayout::eGeneral,
|
||||
};
|
||||
|
||||
std::array writes = {
|
||||
vk::WriteDescriptorSet{
|
||||
.dstSet = descriptor_set,
|
||||
.dstBinding = 0,
|
||||
.descriptorCount = src_image_info.size(),
|
||||
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
|
||||
.pImageInfo = src_image_info.data(),
|
||||
},
|
||||
vk::WriteDescriptorSet{
|
||||
.dstSet = descriptor_set,
|
||||
.dstBinding = 1,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eStorageBuffer,
|
||||
.pBufferInfo = &ubo_info,
|
||||
},
|
||||
vk::WriteDescriptorSet{
|
||||
.dstSet = descriptor_set,
|
||||
.dstBinding = 2,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eStorageImage,
|
||||
.pImageInfo = &y_info,
|
||||
},
|
||||
vk::WriteDescriptorSet{
|
||||
.dstSet = descriptor_set,
|
||||
.dstBinding = 3,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eStorageImage,
|
||||
.pImageInfo = &cbcr_info,
|
||||
},
|
||||
};
|
||||
|
||||
device.updateDescriptorSets(writes, {});
|
||||
|
||||
cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *pipeline);
|
||||
cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *layout, 0, descriptor_set, {});
|
||||
cmd.dispatch(divide_and_round_up(foveated_size.width, 8),
|
||||
divide_and_round_up(foveated_size.height, 8),
|
||||
2);
|
||||
|
||||
return params;
|
||||
}
|
||||
} // namespace wivrn
|
||||
@@ -22,9 +22,7 @@
|
||||
#include "vk/allocation.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include "xrt/xrt_defines.h"
|
||||
#include "xrt/xrt_device.h"
|
||||
|
||||
#include "utils/singleton.h"
|
||||
#include <mutex>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
@@ -34,14 +32,13 @@ namespace wivrn
|
||||
{
|
||||
|
||||
struct clock_offset;
|
||||
struct wivrn_vk_bundle;
|
||||
struct vk_bundle;
|
||||
|
||||
class wivrn_foveation : public singleton<wivrn_foveation>
|
||||
class foveation
|
||||
{
|
||||
std::mutex mutex;
|
||||
|
||||
const size_t foveated_width; // per eye
|
||||
const size_t foveated_height;
|
||||
const vk::Extent3D foveated_size; // per eye
|
||||
|
||||
// Natural vertical gaze angle
|
||||
const float angle_offset;
|
||||
@@ -53,10 +50,15 @@ class wivrn_foveation : public singleton<wivrn_foveation>
|
||||
from_headset::override_foveation_center manual_foveation = {};
|
||||
std::array<to_headset::foveation_parameter, 2> params;
|
||||
|
||||
vk::raii::CommandPool command_pool;
|
||||
vk::raii::CommandBuffer cmd;
|
||||
buffer_allocation gpu_buffer;
|
||||
buffer_allocation host_buffer;
|
||||
vk::raii::Sampler sampler;
|
||||
|
||||
vk::raii::DescriptorSetLayout ds_layout;
|
||||
vk::raii::PipelineLayout layout;
|
||||
vk::raii::Pipeline pipeline;
|
||||
vk::raii::DescriptorPool descriptor_pool;
|
||||
vk::DescriptorSet descriptor_set;
|
||||
|
||||
// parameters used for last computation
|
||||
struct P
|
||||
@@ -72,23 +74,29 @@ class wivrn_foveation : public singleton<wivrn_foveation>
|
||||
P last;
|
||||
|
||||
// must hold lock on mutex to call it
|
||||
void compute_params(
|
||||
xrt_rect src[2],
|
||||
const xrt_fov fovs[2]);
|
||||
void compute_params();
|
||||
|
||||
void update_ubo(
|
||||
vk::raii::CommandBuffer & cmd,
|
||||
bool flip_y,
|
||||
std::array<xrt_rect, 2> src_rect,
|
||||
std::array<xrt_fov, 2> src_fov);
|
||||
|
||||
public:
|
||||
wivrn_foveation(wivrn_vk_bundle &, const xrt_hmd_parts &);
|
||||
foveation(wivrn::vk_bundle &,
|
||||
vk::Extent3D foveated_size);
|
||||
|
||||
void update_tracking(const from_headset::tracking &, const clock_offset &);
|
||||
void update_tracking(const from_headset::tracking &);
|
||||
void update_foveation_center_override(const from_headset::override_foveation_center &);
|
||||
std::array<to_headset::foveation_parameter, 2> get_parameters();
|
||||
|
||||
vk::Buffer get_gpu_buffer();
|
||||
|
||||
vk::CommandBuffer update_foveation_buffer(
|
||||
vk::Buffer target,
|
||||
std::array<to_headset::foveation_parameter, 2> foveate(
|
||||
vk::raii::Device &,
|
||||
vk::raii::CommandBuffer & cmd,
|
||||
vk::ImageView y,
|
||||
vk::ImageView cbcr,
|
||||
bool flip_y,
|
||||
xrt_rect src[2],
|
||||
xrt_fov fovs[2]);
|
||||
std::array<vk::ImageView, 2> src,
|
||||
std::array<xrt_rect, 2> src_rect,
|
||||
std::array<xrt_fov, 2> src_fov);
|
||||
};
|
||||
} // namespace wivrn
|
||||
@@ -0,0 +1,846 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// uses code borrowed from Monado with the following copyright notice:
|
||||
// Copyright 2019-2024, Collabora, Ltd.
|
||||
// Copyright 2025, NVIDIA CORPORATION.
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
/*!
|
||||
* @file
|
||||
* @brief Compositor (compute shader) rendering code.
|
||||
* @author Jakob Bornecrantz <jakob@collabora.com>
|
||||
* @author Christoph Haag <christoph.haag@collabora.com>
|
||||
* @author Fernando Velazquez Innella <finnella@magicleap.com>
|
||||
* @author Rylie Pavlik <rylie.pavlik@collabora.com>
|
||||
* @ingroup comp_util
|
||||
*/
|
||||
|
||||
#include "render/render_interface.h"
|
||||
|
||||
#include "layer_squasher.h"
|
||||
|
||||
#include "driver/wivrn_hmd.h"
|
||||
#include "utils/wivrn_vk_bundle.h"
|
||||
#include "vk/specialization_constants.h"
|
||||
|
||||
#include "main/comp_compositor.h"
|
||||
#include "math/m_space.h"
|
||||
#include "shaders/layer_defines.inc.glsl"
|
||||
#include "util/comp_layer_accum.h"
|
||||
#include "util/comp_render_helpers.h"
|
||||
|
||||
#include <array>
|
||||
#include <format>
|
||||
#include <ranges>
|
||||
|
||||
namespace
|
||||
{
|
||||
const uint32_t view_count = 2;
|
||||
const bool do_timewarp = true;
|
||||
|
||||
const std::array formats{
|
||||
vk::Format::eR8G8B8A8Srgb,
|
||||
vk::Format::eR8G8B8A8Unorm,
|
||||
};
|
||||
|
||||
const comp_layer *
|
||||
get_projection_layer(const comp_layer_accum & layers)
|
||||
{
|
||||
for (const auto & layer: std::span(layers.layers, layers.layer_count))
|
||||
switch (layer.data.type)
|
||||
{
|
||||
case XRT_LAYER_PROJECTION:
|
||||
case XRT_LAYER_PROJECTION_DEPTH:
|
||||
return &layer;
|
||||
case XRT_LAYER_QUAD:
|
||||
case XRT_LAYER_CUBE:
|
||||
case XRT_LAYER_CYLINDER:
|
||||
case XRT_LAYER_EQUIRECT1:
|
||||
case XRT_LAYER_EQUIRECT2:
|
||||
case XRT_LAYER_PASSTHROUGH:
|
||||
break;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
struct pose_data
|
||||
{
|
||||
std::array<xrt_fov, XRT_MAX_VIEWS> fovs;
|
||||
std::array<xrt_pose, XRT_MAX_VIEWS> world_poses;
|
||||
std::array<xrt_pose, XRT_MAX_VIEWS> eye_poses;
|
||||
pose_data(
|
||||
wivrn::wivrn_hmd & hmd,
|
||||
uint64_t frame_interval_ns,
|
||||
const comp_frame & frame,
|
||||
const comp_layer_accum & layers)
|
||||
{
|
||||
// Get pose data from projection layer so we avoid one resampling step
|
||||
const auto * proj = get_projection_layer(layers);
|
||||
// Except if it's not for the right frame, as it would make quads stutter
|
||||
int64_t predicted_display_time_ns = frame.predicted_display_time_ns;
|
||||
int64_t cutoff_ns = 3 * frame_interval_ns;
|
||||
if (proj and llabs(predicted_display_time_ns - proj->data.timestamp) <= cutoff_ns)
|
||||
{
|
||||
// depth has the same first member as proj
|
||||
for (auto [i, data]: std::ranges::enumerate_view(proj->data.proj.v))
|
||||
{
|
||||
fovs[i] = data.fov;
|
||||
world_poses[i] = data.pose;
|
||||
eye_poses[i] = data.pose;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
xrt_space_relation head_rel;
|
||||
hmd.get_view_poses(
|
||||
nullptr, // unused
|
||||
frame.predicted_display_time_ns,
|
||||
XRT_VIEW_TYPE_STEREO,
|
||||
view_count,
|
||||
&head_rel,
|
||||
fovs.data(),
|
||||
eye_poses.data());
|
||||
for (uint32_t i = 0; i < view_count; ++i)
|
||||
{
|
||||
xrt_relation_chain xrc{};
|
||||
xrt_space_relation rel = XRT_SPACE_RELATION_ZERO;
|
||||
|
||||
m_relation_chain_push_pose_if_not_identity(&xrc, &eye_poses[i]);
|
||||
m_relation_chain_push_relation(&xrc, &head_rel);
|
||||
m_relation_chain_resolve(&xrc, &rel);
|
||||
world_poses[i] = rel.pose;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const comp_swapchain_image & get_layer_image(const comp_layer & layer, uint32_t swapchain_index, uint32_t image_index)
|
||||
{
|
||||
return ((struct comp_swapchain *)(comp_layer_get_swapchain(&layer, swapchain_index)))->images[image_index];
|
||||
}
|
||||
|
||||
const struct comp_swapchain_image &
|
||||
get_layer_depth_image(const comp_layer & layer, uint32_t swapchain_index, uint32_t image_index)
|
||||
{
|
||||
return ((struct comp_swapchain *)(comp_layer_get_depth_swapchain(&layer, swapchain_index)))->images[image_index];
|
||||
}
|
||||
|
||||
uint32_t
|
||||
uint_divide_and_round_up(uint32_t a, uint32_t b)
|
||||
{
|
||||
return (a + (b - 1)) / b;
|
||||
}
|
||||
|
||||
std::array<uint32_t, 2> calc_dispatch_dims_1_view(const render_viewport_data & views)
|
||||
{
|
||||
// Power of two divide and round up.
|
||||
return {
|
||||
uint_divide_and_round_up(views.w, 8),
|
||||
uint_divide_and_round_up(views.h, 8),
|
||||
};
|
||||
}
|
||||
|
||||
buffer_allocation make_ubo(vk::raii::Device & device, int i)
|
||||
{
|
||||
return buffer_allocation{
|
||||
device,
|
||||
vk::BufferCreateInfo{
|
||||
.size = sizeof(render_compute_layer_ubo_data),
|
||||
.usage = vk::BufferUsageFlagBits::eUniformBuffer,
|
||||
},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
},
|
||||
std::format("layer squasher UBO {}", i)};
|
||||
}
|
||||
|
||||
vk::raii::ImageView make_view(wivrn::vk_bundle & vk, image_allocation & image, vk::ImageUsageFlagBits flag, uint32_t view)
|
||||
{
|
||||
vk::raii::ImageView res{vk.device,
|
||||
vk::StructureChain{
|
||||
vk::ImageViewCreateInfo{
|
||||
.image = image,
|
||||
.viewType = vk::ImageViewType::e2D,
|
||||
.format = flag == vk::ImageUsageFlagBits::eSampled ? formats[0] : formats[1],
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = view,
|
||||
.layerCount = 1,
|
||||
},
|
||||
},
|
||||
vk::ImageViewUsageCreateInfo{
|
||||
.usage = flag,
|
||||
},
|
||||
|
||||
}
|
||||
.get()};
|
||||
vk.name(*res, std::format("layer squasher view {}", view).c_str());
|
||||
return res;
|
||||
}
|
||||
|
||||
vk::raii::DescriptorSetLayout make_ds_layout(wivrn::vk_bundle & vk, uint32_t image_array_size, bool partially_bound_desc)
|
||||
{
|
||||
std::array bindings{
|
||||
vk::DescriptorSetLayoutBinding{
|
||||
.binding = 0,
|
||||
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
|
||||
.descriptorCount = image_array_size,
|
||||
.stageFlags = vk::ShaderStageFlagBits::eCompute,
|
||||
},
|
||||
vk::DescriptorSetLayoutBinding{
|
||||
.binding = 2,
|
||||
.descriptorType = vk::DescriptorType::eStorageImage,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = vk::ShaderStageFlagBits::eCompute,
|
||||
},
|
||||
vk::DescriptorSetLayoutBinding{
|
||||
.binding = 3,
|
||||
.descriptorType = vk::DescriptorType::eUniformBuffer,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = vk::ShaderStageFlagBits::eCompute,
|
||||
},
|
||||
};
|
||||
std::array<vk::DescriptorBindingFlags, std::size(bindings)> flags{
|
||||
vk::DescriptorBindingFlagBits::ePartiallyBound,
|
||||
vk::DescriptorBindingFlagBits::ePartiallyBound,
|
||||
vk::DescriptorBindingFlags{},
|
||||
};
|
||||
|
||||
vk::StructureChain info{
|
||||
vk::DescriptorSetLayoutCreateInfo{
|
||||
.bindingCount = bindings.size(),
|
||||
.pBindings = bindings.data(),
|
||||
},
|
||||
vk::DescriptorSetLayoutBindingFlagsCreateInfo{
|
||||
.bindingCount = flags.size(),
|
||||
.pBindingFlags = flags.data(),
|
||||
}};
|
||||
|
||||
if (not partially_bound_desc)
|
||||
info.unlink<vk::DescriptorSetLayoutBindingFlagsCreateInfo>();
|
||||
|
||||
vk::raii::DescriptorSetLayout res(vk.device, info.get());
|
||||
vk.name(*res, "layer squasher descriptor set layout");
|
||||
return res;
|
||||
}
|
||||
vk::raii::PipelineLayout make_layout(wivrn::vk_bundle & vk, vk::DescriptorSetLayout ds_layout)
|
||||
{
|
||||
vk::raii::PipelineLayout res(vk.device,
|
||||
vk::PipelineLayoutCreateInfo{
|
||||
.setLayoutCount = 1,
|
||||
.pSetLayouts = &ds_layout,
|
||||
});
|
||||
vk.name(*res, "layer squasher pipeline layout");
|
||||
return res;
|
||||
}
|
||||
|
||||
vk::raii::Pipeline make_pipeline(wivrn::vk_bundle & vk, uint32_t image_array_size, vk::PipelineLayout layout)
|
||||
{
|
||||
auto specialization = make_specialization_constants(int32_t(image_array_size));
|
||||
vk::raii::Pipeline res(
|
||||
vk.device,
|
||||
nullptr,
|
||||
vk::ComputePipelineCreateInfo{
|
||||
.stage = {
|
||||
.stage = vk::ShaderStageFlagBits::eCompute,
|
||||
.module = *vk.load_shader("layer"),
|
||||
.pName = "main",
|
||||
.pSpecializationInfo = specialization,
|
||||
},
|
||||
.layout = layout,
|
||||
});
|
||||
vk.name(*res, "layer squasher pipeline");
|
||||
return res;
|
||||
}
|
||||
|
||||
vk::raii::DescriptorPool make_ds_pool(wivrn::vk_bundle & vk, uint32_t image_array_size)
|
||||
{
|
||||
const uint32_t view_size = 2;
|
||||
std::array pool_sizes{
|
||||
vk::DescriptorPoolSize{
|
||||
.type = vk::DescriptorType::eCombinedImageSampler,
|
||||
.descriptorCount = view_size * image_array_size,
|
||||
},
|
||||
vk::DescriptorPoolSize{
|
||||
.type = vk::DescriptorType::eStorageImage,
|
||||
.descriptorCount = view_size,
|
||||
},
|
||||
vk::DescriptorPoolSize{
|
||||
.type = vk::DescriptorType::eUniformBuffer,
|
||||
.descriptorCount = view_size,
|
||||
},
|
||||
};
|
||||
vk::raii::DescriptorPool res{
|
||||
vk.device,
|
||||
vk::DescriptorPoolCreateInfo{
|
||||
.maxSets = view_size,
|
||||
.poolSizeCount = pool_sizes.size(),
|
||||
.pPoolSizes = pool_sizes.data(),
|
||||
},
|
||||
};
|
||||
vk.name(*res, "layer squasher descriptor pool");
|
||||
return res;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
layer_squasher::layer_squasher(vk_bundle & vk, vk::Extent3D target_size) :
|
||||
partially_bound_desc{bool(std::get<vk::PhysicalDeviceVulkan12Features>(vk.feat).descriptorBindingPartiallyBound)},
|
||||
image_array_size{std::min<uint32_t>(vk.physical_device.getProperties().limits.maxPerStageDescriptorSampledImages, RENDER_MAX_IMAGES_SIZE)},
|
||||
clamp_to_border_black{vk.device,
|
||||
vk::SamplerCreateInfo{
|
||||
.magFilter = vk::Filter::eLinear,
|
||||
.minFilter = vk::Filter::eLinear,
|
||||
.mipmapMode = vk::SamplerMipmapMode::eLinear,
|
||||
.addressModeU = vk::SamplerAddressMode::eClampToBorder,
|
||||
.addressModeV = vk::SamplerAddressMode::eClampToBorder,
|
||||
.addressModeW = vk::SamplerAddressMode::eClampToBorder,
|
||||
.borderColor = vk::BorderColor::eFloatOpaqueBlack,
|
||||
}},
|
||||
clamp_to_edge{vk.device,
|
||||
vk::SamplerCreateInfo{
|
||||
.magFilter = vk::Filter::eLinear,
|
||||
.minFilter = vk::Filter::eLinear,
|
||||
.mipmapMode = vk::SamplerMipmapMode::eLinear,
|
||||
.addressModeU = vk::SamplerAddressMode::eClampToEdge,
|
||||
.addressModeV = vk::SamplerAddressMode::eClampToEdge,
|
||||
.addressModeW = vk::SamplerAddressMode::eClampToEdge,
|
||||
.borderColor = vk::BorderColor::eFloatOpaqueBlack,
|
||||
}},
|
||||
ubo{make_ubo(vk.device, 0), make_ubo(vk.device, 1)},
|
||||
render_target{vk.device,
|
||||
vk::StructureChain{
|
||||
vk::ImageCreateInfo{
|
||||
.flags = vk::ImageCreateFlagBits::eExtendedUsage | vk::ImageCreateFlagBits::eMutableFormat,
|
||||
.imageType = vk::ImageType::e2D,
|
||||
.format = formats[0],
|
||||
.extent = target_size,
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = view_count,
|
||||
.usage = vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eSampled,
|
||||
},
|
||||
vk::ImageFormatListCreateInfo{
|
||||
.viewFormatCount = formats.size(),
|
||||
.pViewFormats = formats.data(),
|
||||
},
|
||||
|
||||
}
|
||||
.get(),
|
||||
VmaAllocationCreateInfo{},
|
||||
"layer squasher target"},
|
||||
render_view_srgb{make_view(vk, render_target, vk::ImageUsageFlagBits::eSampled, 0), make_view(vk, render_target, vk::ImageUsageFlagBits::eSampled, 1)},
|
||||
render_view_unorm{make_view(vk, render_target, vk::ImageUsageFlagBits::eStorage, 0), make_view(vk, render_target, vk::ImageUsageFlagBits::eStorage, 1)},
|
||||
ds_layout{make_ds_layout(vk, image_array_size, partially_bound_desc)},
|
||||
layout{make_layout(vk, *ds_layout)},
|
||||
pipeline{make_pipeline(vk, image_array_size, *layout)},
|
||||
descriptor_pool{make_ds_pool(vk, image_array_size)}
|
||||
{
|
||||
{
|
||||
std::array layouts = {*ds_layout, *ds_layout};
|
||||
auto sets = vk.device.allocateDescriptorSets(vk::DescriptorSetAllocateInfo{
|
||||
.descriptorPool = descriptor_pool,
|
||||
.descriptorSetCount = uint32_t(descriptor_sets.size()),
|
||||
.pSetLayouts = layouts.data(),
|
||||
});
|
||||
for (int i = 0; i < view_count; ++i)
|
||||
descriptor_sets[i] = sets[i].release();
|
||||
}
|
||||
}
|
||||
|
||||
std::tuple<std::array<xrt_pose, 2>,
|
||||
std::array<xrt_fov, 2>>
|
||||
layer_squasher::do_layers(
|
||||
vk::raii::Device & device,
|
||||
vk::raii::CommandBuffer & cmd,
|
||||
wivrn_hmd & hmd,
|
||||
uint64_t frame_interval_ns,
|
||||
const comp_frame & frame,
|
||||
const comp_layer_accum & layers)
|
||||
{
|
||||
// get the head/pose to reproject to
|
||||
const pose_data poses{hmd, frame_interval_ns, frame, layers};
|
||||
|
||||
vk::ImageMemoryBarrier im_barrier{
|
||||
.dstAccessMask = vk::AccessFlagBits::eShaderWrite,
|
||||
.oldLayout = vk::ImageLayout::eUndefined,
|
||||
.newLayout = vk::ImageLayout::eGeneral,
|
||||
.image = render_target,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.levelCount = 1,
|
||||
.layerCount = vk::RemainingArrayLayers,
|
||||
},
|
||||
};
|
||||
|
||||
cmd.pipelineBarrier(
|
||||
vk::PipelineStageFlagBits::eAllCommands,
|
||||
vk::PipelineStageFlagBits::eComputeShader,
|
||||
{},
|
||||
{},
|
||||
{},
|
||||
im_barrier);
|
||||
|
||||
for (int view = 0; view < view_count; ++view)
|
||||
{
|
||||
// TODO: staging buffer?
|
||||
auto & ubo = *(render_compute_layer_ubo_data *)this->ubo[view].map();
|
||||
|
||||
const auto & extent = render_target.info().extent;
|
||||
|
||||
render_viewport_data viewport{
|
||||
.w = extent.width,
|
||||
.h = extent.height,
|
||||
};
|
||||
|
||||
ubo.view = viewport;
|
||||
render_calc_uv_to_tangent_lengths_rect(&poses.fovs[view], &ubo.pre_transform);
|
||||
|
||||
// Not the transform of the views, but the inverse: actual view matrices.
|
||||
xrt_matrix_4x4 world_view_mat, eye_view_mat;
|
||||
math_matrix_4x4_view_from_pose(&poses.world_poses[view], &world_view_mat);
|
||||
math_matrix_4x4_view_from_pose(&poses.eye_poses[view], &eye_view_mat);
|
||||
|
||||
std::array<vk::DescriptorImageInfo, RENDER_MAX_IMAGES_SIZE> src_image_info{};
|
||||
for (auto & src: src_image_info)
|
||||
src.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
|
||||
|
||||
uint32_t cur_image = 0;
|
||||
int cur_layer = 0;
|
||||
for (const auto & layer: std::span(layers.layers, layers.layer_count))
|
||||
{
|
||||
if (not is_layer_view_visible(&layer.data, view))
|
||||
continue;
|
||||
|
||||
const auto & data = layer.data;
|
||||
|
||||
/*!
|
||||
* Stop compositing layers if device's sampled image limit is
|
||||
* reached. For most hardware this isn't a problem, most have
|
||||
* well over 32 max samplers. But notably the RPi4 only have 16
|
||||
* which is a limit we may run into. But if you got 16+ layers
|
||||
* on a RPi4 you have more problems then max samplers.
|
||||
*/
|
||||
uint32_t required_image_samplers;
|
||||
switch (data.type)
|
||||
{
|
||||
case XRT_LAYER_CYLINDER:
|
||||
case XRT_LAYER_EQUIRECT2:
|
||||
case XRT_LAYER_PROJECTION:
|
||||
case XRT_LAYER_QUAD:
|
||||
required_image_samplers = 1;
|
||||
break;
|
||||
case XRT_LAYER_PROJECTION_DEPTH:
|
||||
required_image_samplers = 2;
|
||||
break;
|
||||
default:
|
||||
U_LOG_E("Skipping layer %ld, unknown type: %u", std::distance(layers.layers, &layer), data.type);
|
||||
continue; // Skip this layer if don't know about it.
|
||||
}
|
||||
|
||||
//! Exit loop if shader cannot receive more image samplers
|
||||
if (cur_image + required_image_samplers > image_array_size)
|
||||
break;
|
||||
|
||||
switch (data.type)
|
||||
{
|
||||
case XRT_LAYER_PROJECTION:
|
||||
case XRT_LAYER_PROJECTION_DEPTH:
|
||||
do_projection_layer(
|
||||
layer,
|
||||
poses.world_poses[view],
|
||||
view,
|
||||
cur_layer,
|
||||
cur_image,
|
||||
src_image_info,
|
||||
ubo);
|
||||
break;
|
||||
case XRT_LAYER_QUAD:
|
||||
do_quad_layer(
|
||||
layer,
|
||||
eye_view_mat,
|
||||
world_view_mat,
|
||||
view,
|
||||
cur_layer,
|
||||
cur_image,
|
||||
src_image_info,
|
||||
ubo);
|
||||
break;
|
||||
case XRT_LAYER_CYLINDER:
|
||||
do_cylinder_layer(
|
||||
layer,
|
||||
eye_view_mat,
|
||||
world_view_mat,
|
||||
view,
|
||||
cur_layer,
|
||||
cur_image,
|
||||
src_image_info,
|
||||
ubo);
|
||||
break;
|
||||
case XRT_LAYER_EQUIRECT2:
|
||||
do_equirect2_layer(
|
||||
layer,
|
||||
eye_view_mat,
|
||||
world_view_mat,
|
||||
view,
|
||||
cur_layer,
|
||||
cur_image,
|
||||
src_image_info,
|
||||
ubo);
|
||||
break;
|
||||
case XRT_LAYER_EQUIRECT1:
|
||||
case XRT_LAYER_PASSTHROUGH:
|
||||
case XRT_LAYER_CUBE:
|
||||
U_LOG_E("unsupported layer type");
|
||||
assert(false);
|
||||
continue;
|
||||
}
|
||||
ubo.layers[cur_layer].layer_data.unpremultiplied_alpha = is_layer_unpremultiplied(&layer.data);
|
||||
apply_bias_and_scale_from_layer(
|
||||
&data,
|
||||
&ubo.layers[cur_layer].color_scale,
|
||||
&ubo.layers[cur_layer].color_bias);
|
||||
cur_layer++;
|
||||
}
|
||||
ubo.layer_count.value = cur_layer;
|
||||
|
||||
for (auto & layer: std::span(ubo.layers).subspan(cur_layer))
|
||||
layer.layer_data.layer_type = LAYER_COMP_TYPE_NOOP;
|
||||
|
||||
vk::DescriptorImageInfo target_image_info{
|
||||
.imageView = *render_view_unorm[view],
|
||||
.imageLayout = vk::ImageLayout::eGeneral,
|
||||
};
|
||||
|
||||
vk::DescriptorBufferInfo ubo_info{
|
||||
.buffer = this->ubo[view],
|
||||
.range = vk::WholeSize,
|
||||
};
|
||||
|
||||
std::array writes = {
|
||||
vk::WriteDescriptorSet{
|
||||
.dstSet = descriptor_sets[view],
|
||||
.dstBinding = 0,
|
||||
.descriptorCount = uint32_t(cur_image),
|
||||
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
|
||||
.pImageInfo = src_image_info.data(),
|
||||
},
|
||||
vk::WriteDescriptorSet{
|
||||
.dstSet = descriptor_sets[view],
|
||||
.dstBinding = 2,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eStorageImage,
|
||||
.pImageInfo = &target_image_info,
|
||||
},
|
||||
vk::WriteDescriptorSet{
|
||||
.dstSet = descriptor_sets[view],
|
||||
.dstBinding = 3,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eUniformBuffer,
|
||||
.pBufferInfo = &ubo_info,
|
||||
},
|
||||
};
|
||||
|
||||
if (not partially_bound_desc)
|
||||
{
|
||||
for (int i = cur_image; i < image_array_size; ++i)
|
||||
src_image_info[i] = src_image_info[0];
|
||||
writes[0].descriptorCount = image_array_size;
|
||||
}
|
||||
|
||||
device.updateDescriptorSets(writes, {});
|
||||
|
||||
cmd.bindPipeline(vk::PipelineBindPoint::eCompute, *pipeline);
|
||||
cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *layout, 0, descriptor_sets[view], {});
|
||||
auto [w, h] = calc_dispatch_dims_1_view(viewport);
|
||||
cmd.dispatch(w, h, 1);
|
||||
}
|
||||
|
||||
im_barrier.oldLayout = im_barrier.newLayout;
|
||||
im_barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
|
||||
im_barrier.srcAccessMask = im_barrier.dstAccessMask;
|
||||
im_barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
|
||||
cmd.pipelineBarrier(
|
||||
vk::PipelineStageFlagBits::eComputeShader,
|
||||
vk::PipelineStageFlagBits::eComputeShader,
|
||||
{},
|
||||
{},
|
||||
{},
|
||||
im_barrier);
|
||||
|
||||
return {poses.world_poses, poses.fovs};
|
||||
}
|
||||
|
||||
std::array<vk::ImageView, 2> layer_squasher::get_views()
|
||||
{
|
||||
return {*render_view_srgb[0], *render_view_srgb[1]};
|
||||
}
|
||||
|
||||
uint32_t layer_squasher::max_layers(const vk::PhysicalDeviceProperties & prop) const
|
||||
{
|
||||
// We may be limited by samplers, and use up to 2 samplers per layer
|
||||
return std::min({XRT_MAX_LAYERS * 2u,
|
||||
prop.limits.maxPerStageDescriptorSampledImages,
|
||||
prop.limits.maxPerStageDescriptorSamplers}) /
|
||||
2u;
|
||||
}
|
||||
|
||||
void layer_squasher::do_projection_layer(
|
||||
const comp_layer & layer,
|
||||
const xrt_pose & world_pose,
|
||||
int view,
|
||||
int cur_layer,
|
||||
uint32_t & cur_image,
|
||||
std::span<vk::DescriptorImageInfo> src_image_info,
|
||||
render_compute_layer_ubo_data & ubo)
|
||||
{
|
||||
const xrt_layer_data & layer_data = layer.data;
|
||||
const auto & vd = layer_data.type == XRT_LAYER_PROJECTION ? layer_data.proj.v[view] : layer_data.depth.v[view];
|
||||
|
||||
uint32_t sc_array_index = view % 2;
|
||||
|
||||
ubo.layers[cur_layer].layer_data.layer_type = LAYER_COMP_TYPE_PROJECTION;
|
||||
|
||||
// Color
|
||||
src_image_info[cur_image].sampler = *clamp_to_border_black;
|
||||
src_image_info[cur_image].imageView = get_image_view(
|
||||
&get_layer_image(layer, sc_array_index, vd.sub.image_index),
|
||||
layer_data.flags,
|
||||
vd.sub.array_index);
|
||||
ubo.layers[cur_layer].image_info.color_image_index = cur_image++;
|
||||
|
||||
// Depth
|
||||
if (layer_data.type == XRT_LAYER_PROJECTION_DEPTH)
|
||||
{
|
||||
const auto & dvd = layer_data.depth.d[view];
|
||||
|
||||
src_image_info[cur_image].sampler = *clamp_to_edge; // Edge to keep depth stable at edges.
|
||||
src_image_info[cur_image].imageView = get_image_view(
|
||||
&get_layer_depth_image(layer, sc_array_index, dvd.sub.image_index),
|
||||
layer_data.flags,
|
||||
dvd.sub.array_index);
|
||||
ubo.layers[cur_layer].image_info.depth_image_index = cur_image++;
|
||||
}
|
||||
|
||||
set_post_transform_rect(
|
||||
&layer_data,
|
||||
&vd.sub.norm_rect,
|
||||
false,
|
||||
&ubo.layers[cur_layer].post_transforms);
|
||||
|
||||
// unused if timewarp is off
|
||||
if (do_timewarp)
|
||||
render_calc_time_warp_matrix(
|
||||
&vd.pose,
|
||||
&vd.fov,
|
||||
&world_pose,
|
||||
&ubo.layers[cur_layer].transforms_timewarp);
|
||||
}
|
||||
|
||||
void layer_squasher::do_quad_layer(const comp_layer & layer,
|
||||
const xrt_matrix_4x4 & eye_view_mat,
|
||||
const xrt_matrix_4x4 & world_view_mat,
|
||||
uint32_t view_index,
|
||||
int cur_layer,
|
||||
uint32_t & cur_image,
|
||||
std::span<vk::DescriptorImageInfo> src_image_info,
|
||||
render_compute_layer_ubo_data & ubo)
|
||||
{
|
||||
const xrt_layer_data & layer_data = layer.data;
|
||||
const xrt_layer_quad_data & q = layer_data.quad;
|
||||
|
||||
ubo.layers[cur_layer].layer_data.layer_type = LAYER_COMP_TYPE_QUAD;
|
||||
|
||||
// Image to use.
|
||||
src_image_info[cur_image].sampler = *clamp_to_edge;
|
||||
src_image_info[cur_image].imageView = get_image_view(
|
||||
&get_layer_image(layer, 0, q.sub.image_index),
|
||||
layer_data.flags,
|
||||
q.sub.array_index);
|
||||
|
||||
// Set the normalized post transform values.
|
||||
xrt_normalized_rect post_transform{};
|
||||
|
||||
// Used for Subimage and OpenGL flip.
|
||||
set_post_transform_rect(
|
||||
&layer_data,
|
||||
&q.sub.norm_rect,
|
||||
true,
|
||||
&post_transform);
|
||||
|
||||
// Is this layer viewspace or not.
|
||||
const xrt_matrix_4x4 & view_mat = is_layer_view_space(&layer_data) ? eye_view_mat : world_view_mat;
|
||||
|
||||
// Transform quad pose into view space.
|
||||
xrt_vec3 quad_position{};
|
||||
math_matrix_4x4_transform_vec3(&view_mat, &layer_data.quad.pose.position, &quad_position);
|
||||
|
||||
// neutral quad layer faces +z, towards the user
|
||||
xrt_vec3 normal{.x = 0, .y = 0, .z = 1};
|
||||
|
||||
// rotation of the quad normal in world space
|
||||
math_quat_rotate_vec3(&layer_data.quad.pose.orientation, &normal, &normal);
|
||||
|
||||
/*
|
||||
* normal is a vector that originates on the plane, not on the origin.
|
||||
* Instead of using the inverse quad transform to transform it into view space we can
|
||||
* simply add up vectors:
|
||||
*
|
||||
* combined_normal [in world space] = plane_origin [in world space] + normal [in plane
|
||||
* space] [with plane in world space]
|
||||
*
|
||||
* Then combined_normal can be transformed to view space via view matrix and a new
|
||||
* normal_view_space retrieved:
|
||||
*
|
||||
* normal_view_space = combined_normal [in view space] - plane_origin [in view space]
|
||||
*/
|
||||
xrt_vec3 normal_view_space = normal;
|
||||
math_vec3_accum(&layer_data.quad.pose.position, &normal_view_space);
|
||||
math_matrix_4x4_transform_vec3(&view_mat, &normal_view_space, &normal_view_space);
|
||||
math_vec3_subtract(&quad_position, &normal_view_space);
|
||||
|
||||
xrt_vec3 scale{1.f, 1.f, 1.f};
|
||||
xrt_matrix_4x4 plane_transform_view_space, inverse_quad_transform;
|
||||
math_matrix_4x4_model(&layer_data.quad.pose, &scale, &plane_transform_view_space);
|
||||
math_matrix_4x4_multiply(&view_mat, &plane_transform_view_space, &plane_transform_view_space);
|
||||
math_matrix_4x4_inverse(&plane_transform_view_space, &inverse_quad_transform);
|
||||
|
||||
// Write all of the UBO data.
|
||||
ubo.layers[cur_layer].post_transforms = post_transform;
|
||||
ubo.layers[cur_layer].quad_extent.val = layer_data.quad.size;
|
||||
ubo.layers[cur_layer].quad_position.val = quad_position;
|
||||
ubo.layers[cur_layer].quad_normal.val = normal_view_space;
|
||||
ubo.layers[cur_layer].inverse_quad_transform = inverse_quad_transform;
|
||||
ubo.layers[cur_layer].image_info.color_image_index = cur_image;
|
||||
cur_image++;
|
||||
}
|
||||
|
||||
void layer_squasher::do_cylinder_layer(const comp_layer & layer,
|
||||
const xrt_matrix_4x4 & eye_view_mat,
|
||||
const xrt_matrix_4x4 & world_view_mat,
|
||||
uint32_t view_index,
|
||||
int cur_layer,
|
||||
uint32_t & cur_image,
|
||||
std::span<vk::DescriptorImageInfo> src_image_info,
|
||||
render_compute_layer_ubo_data & ubo)
|
||||
{
|
||||
const xrt_layer_data & layer_data = layer.data;
|
||||
const xrt_layer_cylinder_data & c = layer_data.cylinder;
|
||||
|
||||
ubo.layers[cur_layer].layer_data.layer_type = LAYER_COMP_TYPE_CYLINDER;
|
||||
|
||||
// Image to use.
|
||||
src_image_info[cur_image].sampler = *clamp_to_edge;
|
||||
src_image_info[cur_image].imageView = get_image_view(
|
||||
&get_layer_image(layer, 0, c.sub.image_index),
|
||||
layer_data.flags,
|
||||
c.sub.array_index);
|
||||
|
||||
// Used for Subimage and OpenGL flip.
|
||||
set_post_transform_rect(
|
||||
&layer_data,
|
||||
&c.sub.norm_rect,
|
||||
false,
|
||||
&ubo.layers[cur_layer].post_transforms);
|
||||
|
||||
ubo.layers[cur_layer].cylinder_data.central_angle = c.central_angle;
|
||||
ubo.layers[cur_layer].cylinder_data.aspect_ratio = c.aspect_ratio;
|
||||
|
||||
xrt_vec3 scale{1.f, 1.f, 1.f};
|
||||
|
||||
xrt_matrix_4x4 model;
|
||||
math_matrix_4x4_model(&c.pose, &scale, &model);
|
||||
|
||||
xrt_matrix_4x4 model_inv;
|
||||
math_matrix_4x4_inverse(&model, &model_inv);
|
||||
|
||||
const xrt_matrix_4x4 & v = is_layer_view_space(&layer_data) ? eye_view_mat : world_view_mat;
|
||||
|
||||
xrt_matrix_4x4 v_inv;
|
||||
math_matrix_4x4_inverse(&v, &v_inv);
|
||||
|
||||
math_matrix_4x4_multiply(&model_inv, &v_inv, &ubo.layers[cur_layer].mv_inverse);
|
||||
|
||||
// Simplifies the shader.
|
||||
ubo.layers[cur_layer].cylinder_data.radius = c.radius >= INFINITY ? 0.f : c.radius;
|
||||
|
||||
ubo.layers[cur_layer].cylinder_data.central_angle = c.central_angle;
|
||||
ubo.layers[cur_layer].cylinder_data.aspect_ratio = c.aspect_ratio;
|
||||
|
||||
ubo.layers[cur_layer].image_info.color_image_index = cur_image;
|
||||
cur_image++;
|
||||
}
|
||||
|
||||
void layer_squasher::do_equirect2_layer(const comp_layer & layer,
|
||||
const xrt_matrix_4x4 & eye_view_mat,
|
||||
const xrt_matrix_4x4 & world_view_mat,
|
||||
uint32_t view_index,
|
||||
int cur_layer,
|
||||
uint32_t & cur_image,
|
||||
std::span<vk::DescriptorImageInfo> src_image_info,
|
||||
render_compute_layer_ubo_data & ubo)
|
||||
{
|
||||
const xrt_layer_data & layer_data = layer.data;
|
||||
const xrt_layer_equirect2_data & eq2 = layer_data.equirect2;
|
||||
|
||||
ubo.layers[cur_layer].layer_data.layer_type = LAYER_COMP_TYPE_EQUIRECT2;
|
||||
|
||||
// Image to use.
|
||||
src_image_info[cur_image].sampler = *clamp_to_edge;
|
||||
src_image_info[cur_image].imageView = get_image_view(
|
||||
&get_layer_image(layer, 0, eq2.sub.image_index),
|
||||
layer_data.flags,
|
||||
eq2.sub.array_index);
|
||||
|
||||
// Used for Subimage and OpenGL flip.
|
||||
set_post_transform_rect( //
|
||||
&layer_data, // data
|
||||
&eq2.sub.norm_rect, // src_norm_rect
|
||||
false, // invert_flip
|
||||
&ubo.layers[cur_layer].post_transforms); // out_norm_rect
|
||||
|
||||
xrt_vec3 scale{1.f, 1.f, 1.f};
|
||||
|
||||
xrt_matrix_4x4 model;
|
||||
math_matrix_4x4_model(&eq2.pose, &scale, &model);
|
||||
|
||||
xrt_matrix_4x4 model_inv;
|
||||
math_matrix_4x4_inverse(&model, &model_inv);
|
||||
|
||||
const xrt_matrix_4x4 & v = is_layer_view_space(&layer_data) ? eye_view_mat : world_view_mat;
|
||||
|
||||
xrt_matrix_4x4 v_inv;
|
||||
math_matrix_4x4_inverse(&v, &v_inv);
|
||||
|
||||
math_matrix_4x4_multiply(&model_inv, &v_inv, &ubo.layers[cur_layer].mv_inverse);
|
||||
|
||||
// Simplifies the shader.
|
||||
ubo.layers[cur_layer].eq2_data.radius = eq2.radius >= INFINITY ? 0.f : eq2.radius;
|
||||
|
||||
ubo.layers[cur_layer].eq2_data.central_horizontal_angle = eq2.central_horizontal_angle;
|
||||
ubo.layers[cur_layer].eq2_data.upper_vertical_angle = eq2.upper_vertical_angle;
|
||||
ubo.layers[cur_layer].eq2_data.lower_vertical_angle = eq2.lower_vertical_angle;
|
||||
|
||||
ubo.layers[cur_layer].image_info.color_image_index = cur_image;
|
||||
cur_image++;
|
||||
}
|
||||
|
||||
} // namespace wivrn
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "vk/allocation.h"
|
||||
|
||||
#include "xrt/xrt_defines.h"
|
||||
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
struct comp_layer;
|
||||
struct comp_layer_accum;
|
||||
struct comp_frame;
|
||||
struct render_compute_layer_ubo_data;
|
||||
|
||||
struct xrt_pose;
|
||||
struct xrt_matrix_4x4;
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
struct vk_bundle;
|
||||
class wivrn_hmd;
|
||||
class layer_squasher
|
||||
{
|
||||
const bool partially_bound_desc;
|
||||
const uint32_t image_array_size;
|
||||
vk::raii::Sampler clamp_to_border_black;
|
||||
vk::raii::Sampler clamp_to_edge;
|
||||
std::array<buffer_allocation, 2> ubo;
|
||||
image_allocation render_target;
|
||||
std::array<vk::raii::ImageView, 2> render_view_srgb;
|
||||
std::array<vk::raii::ImageView, 2> render_view_unorm;
|
||||
vk::raii::DescriptorSetLayout ds_layout;
|
||||
vk::raii::PipelineLayout layout;
|
||||
vk::raii::Pipeline pipeline;
|
||||
vk::raii::DescriptorPool descriptor_pool;
|
||||
std::array<vk::DescriptorSet, 2> descriptor_sets;
|
||||
|
||||
public:
|
||||
layer_squasher(vk_bundle &, vk::Extent3D target_size);
|
||||
|
||||
std::tuple<std::array<xrt_pose, 2>,
|
||||
std::array<xrt_fov, 2>>
|
||||
do_layers(
|
||||
vk::raii::Device &,
|
||||
vk::raii::CommandBuffer &,
|
||||
wivrn_hmd &,
|
||||
uint64_t frame_interval_ns,
|
||||
const comp_frame &,
|
||||
const comp_layer_accum &);
|
||||
|
||||
std::array<vk::ImageView, 2> get_views();
|
||||
vk::Extent3D extent() const
|
||||
{
|
||||
return render_target.info().extent;
|
||||
}
|
||||
|
||||
uint32_t max_layers(const vk::PhysicalDeviceProperties &) const;
|
||||
|
||||
private:
|
||||
void do_projection_layer(
|
||||
const comp_layer & layer,
|
||||
const xrt_pose & world_pose,
|
||||
int view,
|
||||
int cur_layer,
|
||||
uint32_t & cur_image,
|
||||
std::span<vk::DescriptorImageInfo> src_image_info,
|
||||
render_compute_layer_ubo_data & ubo);
|
||||
|
||||
void do_quad_layer(const comp_layer & layer,
|
||||
const xrt_matrix_4x4 & eye_view_mat,
|
||||
const xrt_matrix_4x4 & world_view_mat,
|
||||
uint32_t view_index,
|
||||
int cur_layer,
|
||||
uint32_t & cur_image,
|
||||
std::span<vk::DescriptorImageInfo> src_image_info,
|
||||
render_compute_layer_ubo_data & ubo);
|
||||
void do_cylinder_layer(const comp_layer & layer,
|
||||
const xrt_matrix_4x4 & eye_view_mat,
|
||||
const xrt_matrix_4x4 & world_view_mat,
|
||||
uint32_t view_index,
|
||||
int cur_layer,
|
||||
uint32_t & cur_image,
|
||||
std::span<vk::DescriptorImageInfo> src_image_info,
|
||||
render_compute_layer_ubo_data & ubo);
|
||||
void do_equirect2_layer(const comp_layer & layer,
|
||||
const xrt_matrix_4x4 & eye_view_mat,
|
||||
const xrt_matrix_4x4 & world_view_mat,
|
||||
uint32_t view_index,
|
||||
int cur_layer,
|
||||
uint32_t & cur_image,
|
||||
std::span<vk::DescriptorImageInfo> src_image_info,
|
||||
render_compute_layer_ubo_data & ubo);
|
||||
};
|
||||
} // namespace wivrn
|
||||
@@ -17,7 +17,7 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "wivrn_pacer.h"
|
||||
#include "pacer.h"
|
||||
#include "driver/clock_offset.h"
|
||||
#include "os/os_time.h"
|
||||
#include <algorithm>
|
||||
@@ -41,7 +41,7 @@ static T lerp_mod(T a, T b, double t, T mod)
|
||||
return T(std::lerp(a, b, t)) % mod;
|
||||
}
|
||||
|
||||
wivrn_pacer::wivrn_pacer(uint64_t frame_duration) :
|
||||
pacer::pacer(uint64_t frame_duration) :
|
||||
frame_duration_ns(frame_duration),
|
||||
frame_times(5000),
|
||||
frame_times_compute(frame_times),
|
||||
@@ -70,25 +70,25 @@ wivrn_pacer::wivrn_pacer(uint64_t frame_duration) :
|
||||
})
|
||||
{}
|
||||
|
||||
wivrn_pacer::~wivrn_pacer()
|
||||
pacer::~pacer()
|
||||
{
|
||||
worker.request_stop();
|
||||
compute_cv.notify_all();
|
||||
}
|
||||
|
||||
uint64_t wivrn_pacer::get_frame_duration()
|
||||
uint64_t pacer::get_frame_duration() const
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
return frame_duration_ns;
|
||||
}
|
||||
|
||||
void wivrn_pacer::set_frame_duration(uint64_t frame_duration_ns)
|
||||
void pacer::set_frame_duration(uint64_t frame_duration_ns)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
this->frame_duration_ns = frame_duration_ns;
|
||||
}
|
||||
|
||||
void wivrn_pacer::predict(
|
||||
void pacer::predict(
|
||||
int64_t & frame_id,
|
||||
int64_t & out_wake_up_time_ns,
|
||||
int64_t & out_desired_present_time_ns,
|
||||
@@ -122,7 +122,7 @@ void wivrn_pacer::predict(
|
||||
out_present_slop_ns = slop_ns;
|
||||
}
|
||||
|
||||
void wivrn_pacer::on_feedback(const wivrn::from_headset::feedback & feedback, const clock_offset & offset)
|
||||
void pacer::on_feedback(const wivrn::from_headset::feedback & feedback, const clock_offset & offset)
|
||||
{
|
||||
if (feedback.times_displayed > 1 or not feedback.blitted)
|
||||
return;
|
||||
@@ -156,7 +156,7 @@ void wivrn_pacer::on_feedback(const wivrn::from_headset::feedback & feedback, co
|
||||
if (feedback.displayed and feedback.displayed > feedback.blitted and feedback.displayed < feedback.blitted + 100'000'000)
|
||||
mean_render_to_display_ns = std::lerp(mean_render_to_display_ns, feedback.displayed - feedback.blitted, 0.1);
|
||||
}
|
||||
void wivrn_pacer::mark_timing_point(
|
||||
void pacer::mark_timing_point(
|
||||
comp_target_timing_point point,
|
||||
int64_t frame_id,
|
||||
int64_t when_ns)
|
||||
@@ -185,7 +185,7 @@ void wivrn_pacer::mark_timing_point(
|
||||
}
|
||||
}
|
||||
|
||||
wivrn_pacer::frame_info wivrn_pacer::present_to_info(int64_t present)
|
||||
pacer::frame_info pacer::present_to_info(int64_t present)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
for (const auto & info: in_flight_frames)
|
||||
@@ -197,7 +197,7 @@ wivrn_pacer::frame_info wivrn_pacer::present_to_info(int64_t present)
|
||||
return {};
|
||||
}
|
||||
|
||||
void wivrn_pacer::reset()
|
||||
void pacer::reset()
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
std::ranges::fill(frame_times, frame_time{});
|
||||
@@ -33,7 +33,7 @@ namespace wivrn
|
||||
|
||||
struct clock_offset;
|
||||
|
||||
class wivrn_pacer
|
||||
class pacer
|
||||
{
|
||||
public:
|
||||
struct frame_info
|
||||
@@ -44,7 +44,7 @@ public:
|
||||
};
|
||||
|
||||
private:
|
||||
std::mutex mutex;
|
||||
mutable std::mutex mutex;
|
||||
uint64_t frame_duration_ns;
|
||||
int64_t last_ns = 0;
|
||||
int64_t frame_id = 0;
|
||||
@@ -73,10 +73,10 @@ private:
|
||||
std::array<frame_info, 8> in_flight_frames;
|
||||
|
||||
public:
|
||||
wivrn_pacer(uint64_t frame_duration);
|
||||
~wivrn_pacer();
|
||||
pacer(uint64_t frame_duration);
|
||||
~pacer();
|
||||
|
||||
uint64_t get_frame_duration();
|
||||
uint64_t get_frame_duration() const;
|
||||
void set_frame_duration(uint64_t frame_duration);
|
||||
|
||||
void predict(
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright 2021-2022, Collabora Ltd.
|
||||
// Author: Jakob Bornecrantz <jakob@collabora.com>
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#version 460
|
||||
#extension GL_KHR_shader_subgroup_basic: require
|
||||
#extension GL_KHR_shader_subgroup_shuffle: require
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
|
||||
|
||||
#define MAX_DIM 4097
|
||||
#define MAX_SAMPLES 4
|
||||
|
||||
layout(set = 0, binding = 0) uniform sampler2D source[2];
|
||||
layout(set = 0, binding = 1, std430) buffer restrict Config
|
||||
{
|
||||
// foveation parameters
|
||||
uint x[2*MAX_DIM];
|
||||
uint y[2*MAX_DIM];
|
||||
// output parameters
|
||||
uint alpha_width;
|
||||
} ubo;
|
||||
|
||||
layout(set = 0, binding = 2) uniform writeonly restrict image2DArray luma;
|
||||
layout(set = 0, binding = 3) uniform writeonly restrict image2DArray chroma;
|
||||
|
||||
const mat3 color_space = mat3(
|
||||
// R G B
|
||||
/* Y */ 0.2126, 0.7152, 0.0722,
|
||||
/* Cb*/-0.1146, -0.3854, 0.5,
|
||||
/* Cr*/ 0.5 , -0.4542, -0.0458);
|
||||
|
||||
vec3 rgb_to_ycbcr(vec3 color)
|
||||
{
|
||||
return transpose(color_space) * color + vec3(0, 0.5, 0.5);
|
||||
}
|
||||
|
||||
float from_linear_to_srgb_channel(float value)
|
||||
{
|
||||
if (value < 0.0031308) {
|
||||
return 12.92 * value;
|
||||
} else {
|
||||
return 1.055 * pow(value, 1.0 / 2.4) - 0.055;
|
||||
}
|
||||
}
|
||||
|
||||
vec3 from_linear_to_srgb(vec3 linear_rgb)
|
||||
{
|
||||
return vec3(
|
||||
from_linear_to_srgb_channel(linear_rgb.r),
|
||||
from_linear_to_srgb_channel(linear_rgb.g),
|
||||
from_linear_to_srgb_channel(linear_rgb.b)
|
||||
);
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
uint iz = gl_GlobalInvocationID.z;
|
||||
|
||||
uint iy = gl_GlobalInvocationID.y;
|
||||
uint ymin = ubo.y[MAX_DIM * iz + iy];
|
||||
uint ymax = ubo.y[MAX_DIM * iz + iy + 1];
|
||||
if (ymin == ymax)
|
||||
return;
|
||||
if (ymin > ymax)
|
||||
{
|
||||
uint tmp = ymin;
|
||||
ymin = ymax;
|
||||
ymax = tmp;
|
||||
}
|
||||
uint ix = gl_GlobalInvocationID.x;
|
||||
|
||||
uint xmin = ubo.x[MAX_DIM * iz + ix];
|
||||
uint xmax = ubo.x[MAX_DIM * iz + ix + 1];
|
||||
if (xmin == xmax)
|
||||
return;
|
||||
|
||||
uint xstep = (xmax - xmin + MAX_SAMPLES - 1) / MAX_SAMPLES;
|
||||
uint ystep = (ymax - ymin + MAX_SAMPLES - 1) / MAX_SAMPLES;
|
||||
|
||||
vec4 colour = vec4(0);
|
||||
uint count = 0;
|
||||
for (uint y = ymin ; y < ymax; y += ystep) {
|
||||
for (uint x = xmin ; x < xmax; x += xstep) {
|
||||
colour += texelFetch(source[iz], ivec2(x, y), 0);
|
||||
++count;
|
||||
}
|
||||
}
|
||||
colour /= count;
|
||||
colour.xyz = rgb_to_ycbcr(from_linear_to_srgb(colour.rgb));
|
||||
|
||||
imageStore(luma, ivec3(ix, iy, iz), vec4(colour.x));
|
||||
|
||||
vec4 sum = colour;
|
||||
for (uint i = 0 ; i < gl_SubgroupSize; ++i)
|
||||
{
|
||||
uvec3 other = subgroupShuffle(gl_GlobalInvocationID, i);
|
||||
vec4 c = subgroupShuffle(colour, i);
|
||||
if (
|
||||
other == gl_GlobalInvocationID + uvec3(1, 0, 0)
|
||||
|| other == gl_GlobalInvocationID + uvec3(0, 1, 0)
|
||||
|| other == gl_GlobalInvocationID + uvec3(1, 1, 0))
|
||||
{
|
||||
sum += c;
|
||||
}
|
||||
}
|
||||
|
||||
if (ix %2 == 0 && iy %2 == 0)
|
||||
{
|
||||
// actual chroma
|
||||
imageStore(chroma, ivec3(gl_GlobalInvocationID.xy/2, iz), vec4(sum.y, sum.z, 0, 0) / 4);
|
||||
|
||||
// alpha in luma
|
||||
ivec2 offset = ivec2(ubo.alpha_width * iz, 0);
|
||||
imageStore(luma, ivec3(offset.xy + gl_GlobalInvocationID.xy/2, 2), vec4(sum.w, 0, 0, 0) / 4);
|
||||
imageStore(chroma, ivec3(offset.xy + gl_GlobalInvocationID.xy/2, 2), vec4(0.5, 0.5, 0, 0));
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ class app_pacer : public u_pacing_app
|
||||
}
|
||||
|
||||
public:
|
||||
using base = u_pacing_app;
|
||||
using base_t = u_pacing_app;
|
||||
|
||||
app_pacer(pacing_app_factory & parent) :
|
||||
u_pacing_app{
|
||||
|
||||
@@ -37,7 +37,7 @@ class pacing_app_factory : public u_pacing_app_factory
|
||||
void remove_app(app_pacer *);
|
||||
|
||||
public:
|
||||
using base = u_pacing_app_factory;
|
||||
using base_t = u_pacing_app_factory;
|
||||
|
||||
pacing_app_factory();
|
||||
xrt_result_t create(struct u_pacing_app ** out_upa);
|
||||
|
||||
@@ -89,7 +89,7 @@ class wivrn_android_face_tracker : public xrt_device
|
||||
wivrn::wivrn_session & cnx;
|
||||
|
||||
public:
|
||||
using base = xrt_device;
|
||||
using base_t = xrt_device;
|
||||
wivrn_android_face_tracker(xrt_device * hmd, wivrn::wivrn_session & cnx);
|
||||
|
||||
xrt_result_t update_inputs();
|
||||
|
||||
@@ -1,881 +0,0 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
* Copyright (C) 2026 Sapphire <imsapphire0@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "wivrn_comp_target.h"
|
||||
|
||||
#include "driver/wivrn_session.h"
|
||||
#include "encoder/video_encoder.h"
|
||||
#include "util/u_logging.h"
|
||||
#include "utils/method.h"
|
||||
#include "utils/scoped_lock.h"
|
||||
#include "wivrn_config.h"
|
||||
#include "wivrn_foveation.h"
|
||||
|
||||
#include "main/comp_compositor.h"
|
||||
#include "math/m_space.h"
|
||||
#include "xrt_cast.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <ranges>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.hpp>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <vulkan/vulkan_handles.hpp>
|
||||
|
||||
#include "xrt/xrt_config_build.h" // IWYU pragma: keep
|
||||
#ifdef XRT_FEATURE_RENDERDOC
|
||||
#include "renderdoc_app.h"
|
||||
#endif
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
std::vector<const char *> wivrn_comp_target::wanted_instance_extensions = {};
|
||||
std::vector<const char *> wivrn_comp_target::wanted_device_extensions = {
|
||||
// For FFMPEG
|
||||
#ifdef VK_EXT_external_memory_dma_buf
|
||||
VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_EXT_image_drm_format_modifier
|
||||
VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME,
|
||||
#endif
|
||||
|
||||
// For vulkan video encode
|
||||
#ifdef VK_KHR_video_queue
|
||||
VK_KHR_VIDEO_QUEUE_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_KHR_video_encode_queue
|
||||
VK_KHR_VIDEO_ENCODE_QUEUE_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_KHR_video_maintenance1
|
||||
VK_KHR_VIDEO_MAINTENANCE_1_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_KHR_video_encode_h264
|
||||
VK_KHR_VIDEO_ENCODE_H264_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_KHR_video_encode_h265
|
||||
VK_KHR_VIDEO_ENCODE_H265_EXTENSION_NAME,
|
||||
#endif
|
||||
};
|
||||
|
||||
#ifdef XRT_FEATURE_RENDERDOC
|
||||
static auto renderdoc()
|
||||
{
|
||||
auto x = []() {
|
||||
RENDERDOC_API_1_5_0 * rdoc_api = nullptr;
|
||||
const char * env = std::getenv("ENABLE_VULKAN_RENDERDOC_CAPTURE");
|
||||
if (not env or env != std::string_view("1"))
|
||||
return rdoc_api;
|
||||
void * mod = dlopen("librenderdoc.so", RTLD_NOW | RTLD_NOLOAD);
|
||||
if (mod)
|
||||
{
|
||||
pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dlsym(mod, "RENDERDOC_GetAPI");
|
||||
XRT_MAYBE_UNUSED int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_5_0, (void **)&rdoc_api);
|
||||
assert(ret == 1);
|
||||
}
|
||||
return rdoc_api;
|
||||
};
|
||||
static auto res = x();
|
||||
return res;
|
||||
}
|
||||
#endif
|
||||
|
||||
void wivrn_comp_target::init_semaphores()
|
||||
{
|
||||
auto vk = get_vk();
|
||||
VkResult ret;
|
||||
|
||||
fini_semaphores();
|
||||
|
||||
VkSemaphoreCreateInfo info = {
|
||||
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
|
||||
};
|
||||
|
||||
ret = vk->vkCreateSemaphore(vk->device, &info, nullptr, &semaphores.present_complete);
|
||||
if (ret != VK_SUCCESS)
|
||||
{
|
||||
COMP_ERROR(c, "vkCreateSemaphore: %s", vk_result_string(ret));
|
||||
}
|
||||
|
||||
semaphores.render_complete_is_timeline = false;
|
||||
ret = vk->vkCreateSemaphore(vk->device, &info, nullptr, &semaphores.render_complete);
|
||||
if (ret != VK_SUCCESS)
|
||||
{
|
||||
COMP_ERROR(c, "vkCreateSemaphore: %s", vk_result_string(ret));
|
||||
}
|
||||
}
|
||||
void wivrn_comp_target::fini_semaphores()
|
||||
{
|
||||
auto vk = get_vk();
|
||||
|
||||
if (semaphores.present_complete != VK_NULL_HANDLE)
|
||||
{
|
||||
vk->vkDestroySemaphore(vk->device, semaphores.present_complete, nullptr);
|
||||
semaphores.present_complete = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
if (semaphores.render_complete != VK_NULL_HANDLE)
|
||||
{
|
||||
vk->vkDestroySemaphore(vk->device, semaphores.render_complete, nullptr);
|
||||
semaphores.render_complete = VK_NULL_HANDLE;
|
||||
}
|
||||
}
|
||||
|
||||
VkResult wivrn_comp_target::create_images_impl(vk::ImageUsageFlags flags)
|
||||
{
|
||||
auto vk = get_vk();
|
||||
assert(image_count > 0);
|
||||
COMP_DEBUG(c, "Creating %d images.", image_count);
|
||||
auto & device = wivrn_bundle->device;
|
||||
|
||||
destroy_images();
|
||||
|
||||
auto format = vk::Format(this->format);
|
||||
|
||||
bool is_10bit = format == vk::Format::eG10X6B10X6R10X62Plane420Unorm3Pack16;
|
||||
|
||||
std::array formats = {
|
||||
is_10bit ? vk::Format::eR16Unorm : vk::Format::eR8Unorm,
|
||||
is_10bit ? vk::Format::eR16G16Unorm : vk::Format::eR8G8Unorm,
|
||||
format};
|
||||
|
||||
images = U_TYPED_ARRAY_CALLOC(comp_target_image, image_count);
|
||||
|
||||
vk::StructureChain image_info{
|
||||
vk::ImageCreateInfo{
|
||||
.flags = vk::ImageCreateFlagBits::eExtendedUsage | vk::ImageCreateFlagBits::eMutableFormat,
|
||||
.imageType = vk::ImageType::e2D,
|
||||
.format = format,
|
||||
.extent = {
|
||||
.width = width,
|
||||
.height = height,
|
||||
.depth = 1,
|
||||
},
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 3, // left, right then alpha
|
||||
.samples = vk::SampleCountFlagBits::e1,
|
||||
.tiling = vk::ImageTiling::eOptimal,
|
||||
.usage = flags | vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eTransferSrc,
|
||||
.sharingMode = vk::SharingMode::eExclusive,
|
||||
},
|
||||
vk::ImageFormatListCreateInfo{
|
||||
.viewFormatCount = formats.size(),
|
||||
.pViewFormats = formats.data(),
|
||||
},
|
||||
};
|
||||
#if WIVRN_USE_VULKAN_ENCODE
|
||||
if (
|
||||
vk->features.video_maintenance_1 and
|
||||
std::ranges::contains(
|
||||
settings,
|
||||
encoder_vulkan,
|
||||
&encoder_settings::encoder_name))
|
||||
{
|
||||
image_info.get().flags |= vk::ImageCreateFlagBits::eVideoProfileIndependentKHR;
|
||||
image_info.get().usage |= vk::ImageUsageFlagBits::eVideoEncodeSrcKHR;
|
||||
}
|
||||
#endif
|
||||
|
||||
psc.images.resize(image_count);
|
||||
for (uint32_t i = 0; i < image_count; i++)
|
||||
{
|
||||
auto & image = psc.images[i].image;
|
||||
image = image_allocation(
|
||||
device,
|
||||
image_info.get(),
|
||||
{.usage = VMA_MEMORY_USAGE_AUTO},
|
||||
std::format("comp target image {}", i));
|
||||
images[i].handle = image;
|
||||
}
|
||||
|
||||
for (uint32_t i = 0; i < image_count; i++)
|
||||
{
|
||||
auto & item = psc.images[i];
|
||||
vk::ImageViewUsageCreateInfo usage{
|
||||
.usage = flags,
|
||||
};
|
||||
item.image_view_y = vk::raii::ImageView(device,
|
||||
{
|
||||
.pNext = &usage,
|
||||
.image = item.image,
|
||||
.viewType = vk::ImageViewType::e2DArray,
|
||||
.format = formats[0],
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::ePlane0,
|
||||
.levelCount = 1,
|
||||
.layerCount = vk::RemainingArrayLayers,
|
||||
},
|
||||
});
|
||||
item.image_view_cbcr = vk::raii::ImageView(device,
|
||||
{
|
||||
.pNext = &usage,
|
||||
.image = item.image,
|
||||
.viewType = vk::ImageViewType::e2DArray,
|
||||
.format = formats[1],
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::ePlane1,
|
||||
.levelCount = 1,
|
||||
.layerCount = vk::RemainingArrayLayers,
|
||||
},
|
||||
});
|
||||
images[i].view = VkImageView(*item.image_view_y);
|
||||
images[i].view_cbcr = VkImageView(*item.image_view_cbcr);
|
||||
wivrn_bundle->name(item.image_view_y, "comp target image view (y)");
|
||||
wivrn_bundle->name(item.image_view_cbcr, "comp target image view (CbCr)");
|
||||
}
|
||||
|
||||
psc.fence = vk::raii::Fence(device, vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled});
|
||||
wivrn_bundle->name(psc.fence, "comp target fence");
|
||||
|
||||
psc.command_buffer = std::move(device.allocateCommandBuffers(
|
||||
{.commandPool = *command_pool,
|
||||
.commandBufferCount = 1})[0]);
|
||||
wivrn_bundle->name(psc.command_buffer, "comp target command buffer");
|
||||
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
void wivrn_comp_target::destroy_images()
|
||||
{
|
||||
if (images == nullptr)
|
||||
return;
|
||||
|
||||
if (wivrn_bundle)
|
||||
wivrn_bundle->device.waitIdle();
|
||||
|
||||
psc.status = 1;
|
||||
psc.status.notify_all();
|
||||
encoder_threads.clear();
|
||||
encoders.clear();
|
||||
|
||||
psc.images.clear();
|
||||
|
||||
free(images);
|
||||
images = nullptr;
|
||||
|
||||
fini_semaphores();
|
||||
}
|
||||
|
||||
void wivrn_comp_target::create_encoders()
|
||||
{
|
||||
auto vk = get_vk();
|
||||
assert(encoders.empty());
|
||||
assert(encoder_threads.empty());
|
||||
assert(wivrn_bundle);
|
||||
psc.status = 0;
|
||||
|
||||
desc.width = width;
|
||||
desc.height = height;
|
||||
|
||||
std::map<int, std::vector<std::shared_ptr<video_encoder>>> thread_params;
|
||||
|
||||
for (auto [i, settings]: std::ranges::enumerate_view(settings))
|
||||
{
|
||||
auto & encoder = encoders.emplace_back(
|
||||
video_encoder::create(*wivrn_bundle, settings, i));
|
||||
desc.codec[i] = settings.codec;
|
||||
|
||||
thread_params[settings.group].emplace_back(encoder);
|
||||
}
|
||||
|
||||
for (auto & [group, params]: thread_params)
|
||||
{
|
||||
auto & thread = encoder_threads.emplace_back([this](auto stop_token, auto... args) { return run_present(stop_token, args...); }, encoder_threads.size(), std::move(params));
|
||||
std::string name = "encoder " + std::to_string(group);
|
||||
pthread_setname_np(thread.native_handle(), name.c_str());
|
||||
}
|
||||
cnx.send_control(to_headset::video_stream_description{desc});
|
||||
}
|
||||
|
||||
bool wivrn_comp_target::init_pre_vulkan()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
bool wivrn_comp_target::init_post_vulkan(uint32_t preferred_width, uint32_t preferred_height)
|
||||
{
|
||||
auto vk = get_vk();
|
||||
try
|
||||
{
|
||||
wivrn_bundle.emplace(*vk,
|
||||
wivrn_comp_target::wanted_instance_extensions,
|
||||
wivrn_comp_target::wanted_device_extensions);
|
||||
command_pool = vk::raii::CommandPool(
|
||||
wivrn_bundle->device,
|
||||
{
|
||||
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
|
||||
.queueFamilyIndex = vk->main_queue->family_index,
|
||||
});
|
||||
wivrn_bundle->name(command_pool, "comp target command pool");
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
U_LOG_E("Compositor target init failed: %s", e.what());
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
settings = get_encoder_settings(
|
||||
*wivrn_bundle,
|
||||
cnx.get_info(),
|
||||
*cnx.get_settings());
|
||||
print_encoders(settings);
|
||||
|
||||
c->settings.preferred.width = settings[0].width;
|
||||
c->settings.preferred.height = settings[0].height;
|
||||
}
|
||||
catch (const std::exception & e)
|
||||
{
|
||||
wivrn_ipc_socket_monado->send(from_monado::server_error{
|
||||
.where = "Error creating encoder",
|
||||
.message = e.what(),
|
||||
});
|
||||
U_LOG_E("Failed to create video encoder: %s", e.what());
|
||||
return false;
|
||||
}
|
||||
cnx.set_foveated_size(c->settings.preferred.width, c->settings.preferred.height);
|
||||
foveation.emplace(*wivrn_bundle, *cnx.get_hmd().hmd);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool wivrn_comp_target::check_ready()
|
||||
{
|
||||
if (not cnx.connected())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void wivrn_comp_target::create_images(const comp_target_create_images_info * create_info, vk_bundle_queue * present_queue)
|
||||
{
|
||||
assert(present_queue != nullptr);
|
||||
(void)present_queue;
|
||||
|
||||
// Free old images.
|
||||
destroy_images();
|
||||
|
||||
init_semaphores();
|
||||
|
||||
// will fail on encoder init if bit_depth is arbitrary garbage
|
||||
if (settings[0].bit_depth == 10)
|
||||
format = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16;
|
||||
else
|
||||
format = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM;
|
||||
|
||||
width = create_info->extent.width;
|
||||
height = create_info->extent.height;
|
||||
surface_transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
|
||||
|
||||
image_count = 3;
|
||||
color_space = create_info->color_space;
|
||||
|
||||
VkResult res = create_images_impl(vk::ImageUsageFlags(create_info->image_usage));
|
||||
if (res != VK_SUCCESS)
|
||||
{
|
||||
vk_print_result(get_vk(), __FILE__, __LINE__, __func__, res, "create_images");
|
||||
// TODO
|
||||
abort();
|
||||
}
|
||||
create_encoders();
|
||||
}
|
||||
|
||||
bool wivrn_comp_target::has_images()
|
||||
{
|
||||
return images;
|
||||
}
|
||||
|
||||
VkResult wivrn_comp_target::acquire(uint32_t * out_index)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
for (uint32_t i = 0; i < image_count; i++)
|
||||
{
|
||||
if (psc.images[i].status == pseudo_swapchain::status_t::free)
|
||||
{
|
||||
psc.images[i].status = pseudo_swapchain::status_t::acquired;
|
||||
*out_index = i;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
void wivrn_comp_target::run_present(std::stop_token stop_token, int index, std::vector<std::shared_ptr<video_encoder>> encoders)
|
||||
{
|
||||
auto & vk = *wivrn_bundle;
|
||||
U_LOG_I("Starting encoder thread %d", index);
|
||||
|
||||
const uint8_t status_bit = 1 << (index + 1);
|
||||
|
||||
while (not stop_token.stop_requested())
|
||||
{
|
||||
{
|
||||
auto status = psc.status.load();
|
||||
// Bit 0 to request exit
|
||||
if (status & 1)
|
||||
return;
|
||||
|
||||
if (not(status & status_bit))
|
||||
{
|
||||
psc.status.wait(status);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Get local copies before releasing the image
|
||||
auto view_info = psc.view_info;
|
||||
auto frame_index = psc.frame_index;
|
||||
|
||||
auto res = vk.device.waitForFences(*psc.fence, true, UINT64_MAX);
|
||||
|
||||
try
|
||||
{
|
||||
for (auto & encoder: encoders)
|
||||
{
|
||||
if (encoder->stream_idx < 2 or view_info.alpha)
|
||||
encoder->encode(cnx, view_info, frame_index);
|
||||
}
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
U_LOG_W("encode error: %s", e.what());
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
// Ignore errors
|
||||
}
|
||||
|
||||
// Update encoder status, release image
|
||||
if ((psc.status &= ~status_bit) == 0)
|
||||
{
|
||||
psc.status.notify_all();
|
||||
for (auto & img: psc.images)
|
||||
{
|
||||
if (img.status == pseudo_swapchain::status_t::encoding)
|
||||
{
|
||||
img.status = pseudo_swapchain::status_t::free;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
VkResult wivrn_comp_target::present(
|
||||
vk_bundle_queue * present_queue,
|
||||
uint32_t index,
|
||||
uint64_t timeline_semaphore_value,
|
||||
int64_t desired_present_time_ns,
|
||||
int64_t present_slop_ns)
|
||||
{
|
||||
assert(present_queue != nullptr);
|
||||
(void)present_queue;
|
||||
|
||||
assert(index < image_count);
|
||||
assert(psc.images[index].status == pseudo_swapchain::status_t::acquired);
|
||||
|
||||
auto vk = get_vk();
|
||||
auto res = wivrn_bundle->device.waitForFences(*psc.fence, true, UINT64_MAX);
|
||||
|
||||
vk::Semaphore wait_semaphore(semaphores.render_complete);
|
||||
vk::PipelineStageFlags wait_stage = vk::PipelineStageFlagBits::eTransfer;
|
||||
vk::SubmitInfo submit_info{
|
||||
.waitSemaphoreCount = 1,
|
||||
.pWaitSemaphores = &wait_semaphore,
|
||||
.pWaitDstStageMask = &wait_stage,
|
||||
};
|
||||
|
||||
if (c->base.layer_accum.layer_count == 0 or not cnx.get_offset() or skip_encoding)
|
||||
{
|
||||
scoped_lock lock(vk->main_queue->mutex);
|
||||
wivrn_bundle->queue.submit(submit_info);
|
||||
psc.images[index].status = pseudo_swapchain::status_t::free;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
auto & command_buffer = psc.command_buffer;
|
||||
auto & psc_image = psc.images[index];
|
||||
|
||||
// Wait for encoders to be done with previous frame
|
||||
for (auto status = psc.status.load(); status != 0; status = psc.status)
|
||||
psc.status.wait(status);
|
||||
|
||||
command_buffer.reset();
|
||||
command_buffer.begin(vk::CommandBufferBeginInfo{
|
||||
.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit,
|
||||
});
|
||||
|
||||
wivrn_bundle->device.resetFences(*psc.fence);
|
||||
psc_image.status = pseudo_swapchain::status_t::encoding;
|
||||
auto info = pacer.present_to_info(desired_present_time_ns);
|
||||
const bool do_alpha = c->base.layer_accum.data.env_blend_mode == XRT_BLEND_MODE_ALPHA_BLEND;
|
||||
|
||||
bool need_queue_transfer = false;
|
||||
std::vector<vk::Semaphore> present_done_sem;
|
||||
for (auto & encoder: encoders)
|
||||
{
|
||||
if (encoder->stream_idx == 2 and not do_alpha)
|
||||
continue;
|
||||
auto [transfer, sem] = encoder->present_image(
|
||||
psc_image.image,
|
||||
need_queue_transfer,
|
||||
command_buffer,
|
||||
info.frame_id);
|
||||
need_queue_transfer |= transfer;
|
||||
if (sem)
|
||||
present_done_sem.push_back(sem);
|
||||
}
|
||||
|
||||
#if WIVRN_USE_VULKAN_ENCODE
|
||||
if (need_queue_transfer)
|
||||
{
|
||||
vk::ImageMemoryBarrier2 video_barrier{
|
||||
.srcStageMask = vk::PipelineStageFlagBits2KHR::eTransfer,
|
||||
.srcAccessMask = vk::AccessFlagBits2::eMemoryRead,
|
||||
.dstStageMask = vk::PipelineStageFlagBits2KHR::eVideoEncodeKHR,
|
||||
.oldLayout = vk::ImageLayout::eTransferSrcOptimal,
|
||||
.newLayout = vk::ImageLayout::eVideoEncodeSrcKHR,
|
||||
.srcQueueFamilyIndex = vk->main_queue->family_index,
|
||||
.dstQueueFamilyIndex = vk->encode_queue->family_index,
|
||||
.image = psc_image.image,
|
||||
.subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = vk::RemainingArrayLayers},
|
||||
};
|
||||
command_buffer.pipelineBarrier2({
|
||||
.imageMemoryBarrierCount = 1,
|
||||
.pImageMemoryBarriers = &video_barrier,
|
||||
});
|
||||
}
|
||||
submit_info.setSignalSemaphores(present_done_sem);
|
||||
#endif
|
||||
command_buffer.end();
|
||||
submit_info.setCommandBuffers(*command_buffer);
|
||||
|
||||
{
|
||||
scoped_lock lock(vk->main_queue->mutex);
|
||||
wivrn_bundle->queue.submit(submit_info, *psc.fence);
|
||||
for (auto & encoder: encoders)
|
||||
{
|
||||
if (encoder->stream_idx == 2 and not do_alpha)
|
||||
continue;
|
||||
encoder->post_submit();
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef XRT_FEATURE_RENDERDOC
|
||||
if (auto r = renderdoc())
|
||||
r->EndFrameCapture(nullptr, nullptr);
|
||||
#endif
|
||||
|
||||
auto & view_info = psc.view_info;
|
||||
view_info.foveation = foveation->get_parameters();
|
||||
view_info.display_time = cnx.get_offset().to_headset(info.predicted_display_time);
|
||||
if (view_info.alpha != do_alpha)
|
||||
pacer.reset();
|
||||
view_info.alpha = do_alpha;
|
||||
for (int eye = 0; eye < 2; ++eye)
|
||||
{
|
||||
const auto & frame_params = c->base.frame_params;
|
||||
view_info.fov[eye] = xrt_cast(frame_params.fovs[eye]);
|
||||
view_info.pose[eye] = xrt_cast(frame_params.poses[eye]);
|
||||
if (c->base.frame_params.one_projection_layer_fast_path)
|
||||
{
|
||||
const auto & proj = c->base.layer_accum.layers[0].data.proj;
|
||||
view_info.pose[eye] = xrt_cast(proj.v[eye].pose);
|
||||
view_info.fov[eye] = xrt_cast(proj.v[eye].fov);
|
||||
}
|
||||
else
|
||||
{
|
||||
xrt_relation_chain xrc{};
|
||||
xrt_space_relation result{};
|
||||
m_relation_chain_push_pose_if_not_identity(&xrc, &frame_params.poses[eye]);
|
||||
m_relation_chain_resolve(&xrc, &result);
|
||||
view_info.pose[eye] = xrt_cast(result.pose);
|
||||
}
|
||||
}
|
||||
// set bits to 1 for index 1..num encoder threads + 1
|
||||
psc.status = (1 << (encoder_threads.size() + 1)) - 2;
|
||||
psc.frame_index = info.frame_id;
|
||||
psc.status.notify_all();
|
||||
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
void wivrn_comp_target::flush()
|
||||
{
|
||||
#ifdef XRT_FEATURE_RENDERDOC
|
||||
if (auto r = renderdoc())
|
||||
r->StartFrameCapture(nullptr, nullptr);
|
||||
#endif
|
||||
|
||||
if (cnx.get_info().eye_gaze)
|
||||
{
|
||||
// FIXME: actually get the gaze data here
|
||||
auto now = os_monotonic_get_ns();
|
||||
cnx.add_tracking_request(device_id::EYE_GAZE, c->base.layer_accum.data.display_time_ns, now, now);
|
||||
}
|
||||
|
||||
vk::CommandBuffer cmd;
|
||||
// apply foveation for current frame
|
||||
if (c->base.frame_params.one_projection_layer_fast_path)
|
||||
{
|
||||
const auto & data = c->base.layer_accum.layers[0].data;
|
||||
const auto & hmd = cnx.get_hmd().hmd;
|
||||
xrt_rect rect[] = {data.proj.v[0].sub.rect, data.proj.v[1].sub.rect};
|
||||
xrt_fov fov[] = {data.proj.v[0].fov, data.proj.v[1].fov};
|
||||
cmd = foveation->update_foveation_buffer(
|
||||
c->nr.distortion.buffer,
|
||||
data.flip_y,
|
||||
rect,
|
||||
fov);
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto & hmd = cnx.get_hmd().hmd;
|
||||
xrt_rect rect[] = {
|
||||
{.extent = {
|
||||
.w = int(hmd->views[0].display.w_pixels),
|
||||
.h = int(hmd->views[0].display.h_pixels),
|
||||
}},
|
||||
{.extent = {
|
||||
.w = int(hmd->views[1].display.w_pixels),
|
||||
.h = int(hmd->views[1].display.h_pixels),
|
||||
}},
|
||||
};
|
||||
cmd = foveation->update_foveation_buffer(
|
||||
c->nr.distortion.buffer,
|
||||
false,
|
||||
rect,
|
||||
hmd->distortion.fov);
|
||||
}
|
||||
|
||||
auto vk = get_vk();
|
||||
|
||||
vk::Semaphore sem(semaphores.present_complete);
|
||||
|
||||
vk::SubmitInfo submit_info{
|
||||
.commandBufferCount = cmd ? 1u : 0,
|
||||
.pCommandBuffers = &cmd,
|
||||
.signalSemaphoreCount = 1,
|
||||
.pSignalSemaphores = &sem,
|
||||
};
|
||||
|
||||
{
|
||||
scoped_lock lock(vk->main_queue->mutex);
|
||||
wivrn_bundle->queue.submit(submit_info);
|
||||
}
|
||||
}
|
||||
|
||||
void wivrn_comp_target::calc_frame_pacing(
|
||||
int64_t * out_frame_id,
|
||||
int64_t * out_wake_up_time_ns,
|
||||
int64_t * out_desired_present_time_ns,
|
||||
int64_t * out_present_slop_ns,
|
||||
int64_t * out_predicted_display_time_ns)
|
||||
{
|
||||
pacer.predict(
|
||||
*out_frame_id,
|
||||
*out_wake_up_time_ns,
|
||||
*out_desired_present_time_ns,
|
||||
*out_present_slop_ns,
|
||||
*out_predicted_display_time_ns);
|
||||
}
|
||||
|
||||
void wivrn_comp_target::mark_timing_point(
|
||||
enum comp_target_timing_point point,
|
||||
int64_t frame_id,
|
||||
int64_t when_ns)
|
||||
{
|
||||
pacer.mark_timing_point(point, frame_id, when_ns);
|
||||
|
||||
switch (point)
|
||||
{
|
||||
case COMP_TARGET_TIMING_POINT_WAKE_UP:
|
||||
cnx.dump_time("wake_up", frame_id, when_ns);
|
||||
break;
|
||||
case COMP_TARGET_TIMING_POINT_BEGIN:
|
||||
cnx.dump_time("begin", frame_id, when_ns);
|
||||
break;
|
||||
case COMP_TARGET_TIMING_POINT_SUBMIT_BEGIN:
|
||||
break;
|
||||
case COMP_TARGET_TIMING_POINT_SUBMIT_END:
|
||||
cnx.dump_time("submit", frame_id, when_ns);
|
||||
break;
|
||||
default:
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
VkResult wivrn_comp_target::update_timings()
|
||||
{
|
||||
// TODO
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
void wivrn_comp_target::set_title(const char * title)
|
||||
{}
|
||||
|
||||
xrt_result_t wivrn_comp_target::get_refresh_rates(uint32_t * count, float * refresh_rates_hz)
|
||||
{
|
||||
const auto & rates = cnx.get_info().available_refresh_rates;
|
||||
*count = std::min<uint32_t>(rates.size(), XRT_MAX_SUPPORTED_REFRESH_RATES);
|
||||
std::copy_n(rates.begin(), *count, refresh_rates_hz);
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
|
||||
xrt_result_t wivrn_comp_target::get_current_refresh_rate(float * refresh_rate_hz)
|
||||
{
|
||||
*refresh_rate_hz = desc.fps;
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
|
||||
xrt_result_t wivrn_comp_target::request_refresh_rate(float refresh_rate_hz)
|
||||
{
|
||||
requested_refresh_rate = refresh_rate_hz;
|
||||
if (refresh_rate_hz == 0.0f)
|
||||
refresh_rate_hz = get_default_rate(cnx.get_info(), *cnx.get_settings());
|
||||
|
||||
try
|
||||
{
|
||||
cnx.send_control(to_headset::refresh_rate_change{.fps = refresh_rate_hz});
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
// ignore network errors
|
||||
}
|
||||
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
|
||||
wivrn_comp_target::~wivrn_comp_target()
|
||||
{
|
||||
destroy_images();
|
||||
}
|
||||
|
||||
void wivrn_comp_target::destroy()
|
||||
{
|
||||
cnx.unset_comp_target();
|
||||
delete this;
|
||||
}
|
||||
|
||||
void wivrn_comp_target::info_gpu(int64_t frame_id, int64_t gpu_start_ns, int64_t gpu_end_ns, int64_t when_ns)
|
||||
{
|
||||
COMP_TRACE_MARKER();
|
||||
}
|
||||
|
||||
void wivrn_comp_target::on_feedback(const from_headset::feedback & feedback, const clock_offset & o)
|
||||
{
|
||||
uint8_t stream = feedback.stream_index;
|
||||
if (psc.status & 1)
|
||||
return;
|
||||
if (encoders.size() <= stream)
|
||||
return;
|
||||
encoders[stream]->on_feedback(feedback);
|
||||
if (not o)
|
||||
return;
|
||||
pacer.on_feedback(feedback, o);
|
||||
}
|
||||
|
||||
void wivrn_comp_target::reset_encoders()
|
||||
{
|
||||
pacer.reset();
|
||||
for (auto & encoder: encoders)
|
||||
encoder->reset();
|
||||
cnx.send_control(to_headset::video_stream_description{desc});
|
||||
}
|
||||
|
||||
float wivrn_comp_target::get_requested_refresh_rate() const
|
||||
{
|
||||
return requested_refresh_rate;
|
||||
}
|
||||
void wivrn_comp_target::reset_requested_refresh_rate()
|
||||
{
|
||||
requested_refresh_rate = 0;
|
||||
}
|
||||
|
||||
void wivrn_comp_target::pause()
|
||||
{
|
||||
skip_encoding = true;
|
||||
}
|
||||
|
||||
void wivrn_comp_target::resume()
|
||||
{
|
||||
if (!skip_encoding)
|
||||
return;
|
||||
|
||||
reset_encoders();
|
||||
skip_encoding = false;
|
||||
}
|
||||
|
||||
void wivrn_comp_target::set_bitrate(uint32_t bitrate_bps)
|
||||
{
|
||||
for (auto & encoder: encoders)
|
||||
{
|
||||
auto encoder_bps = (uint32_t)(bitrate_bps * encoder->bitrate_multiplier);
|
||||
U_LOG_D("Encoder %d bitrate: %d", encoder->stream_idx, encoder_bps);
|
||||
encoder->set_bitrate(encoder_bps);
|
||||
}
|
||||
}
|
||||
|
||||
void wivrn_comp_target::set_refresh_rate(float refresh_rate_hz)
|
||||
{
|
||||
U_LOG_I("Refresh rate change from %.0f to %.0f", desc.fps, refresh_rate_hz);
|
||||
desc.fps = refresh_rate_hz;
|
||||
c->frame_interval_ns = U_TIME_1S_IN_NS / refresh_rate_hz;
|
||||
pacer.set_frame_duration(c->frame_interval_ns);
|
||||
for (auto & encoder: encoders)
|
||||
encoder->set_framerate(refresh_rate_hz);
|
||||
}
|
||||
|
||||
float wivrn_comp_target::get_refresh_rate()
|
||||
{
|
||||
return desc.fps;
|
||||
}
|
||||
|
||||
wivrn_comp_target::wivrn_comp_target(wivrn::wivrn_session & cnx, struct comp_compositor * c) :
|
||||
comp_target{
|
||||
.c = c,
|
||||
.init_pre_vulkan = method_pointer<&wivrn_comp_target::init_pre_vulkan>,
|
||||
.init_post_vulkan = method_pointer<&wivrn_comp_target::init_post_vulkan>,
|
||||
.check_ready = method_pointer<&wivrn_comp_target::check_ready>,
|
||||
.create_images = method_pointer<&wivrn_comp_target::create_images>,
|
||||
.has_images = method_pointer<&wivrn_comp_target::has_images>,
|
||||
.acquire = method_pointer<&wivrn_comp_target::acquire>,
|
||||
.present = method_pointer<&wivrn_comp_target::present>,
|
||||
.flush = method_pointer<&wivrn_comp_target::flush>,
|
||||
.calc_frame_pacing = method_pointer<&wivrn_comp_target::calc_frame_pacing>,
|
||||
.mark_timing_point = method_pointer<&wivrn_comp_target::mark_timing_point>,
|
||||
.update_timings = method_pointer<&wivrn_comp_target::update_timings>,
|
||||
.info_gpu = method_pointer<&wivrn_comp_target::info_gpu>,
|
||||
.set_title = method_pointer<&wivrn_comp_target::set_title>,
|
||||
.get_refresh_rates = method_pointer<&wivrn_comp_target::get_refresh_rates>,
|
||||
.get_current_refresh_rate = method_pointer<&wivrn_comp_target::get_current_refresh_rate>,
|
||||
.request_refresh_rate = method_pointer<&wivrn_comp_target::request_refresh_rate>,
|
||||
.destroy = method_pointer<&wivrn_comp_target::destroy>,
|
||||
},
|
||||
desc{.fps = get_default_rate(cnx.get_info(), *cnx.get_settings())},
|
||||
cnx(cnx),
|
||||
pacer(U_TIME_1S_IN_NS / desc.fps)
|
||||
{
|
||||
c->frame_interval_ns = U_TIME_1S_IN_NS / desc.fps;
|
||||
}
|
||||
} // namespace wivrn
|
||||
@@ -1,176 +0,0 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
* Copyright (C) 2026 Sapphire <imsapphire0@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "main/comp_compositor.h"
|
||||
#include "main/comp_target.h"
|
||||
|
||||
#include "encoder/encoder_settings.h"
|
||||
#include "utils/wivrn_vk_bundle.h"
|
||||
#include "vk/allocation.h"
|
||||
#include "wivrn_foveation.h"
|
||||
#include "wivrn_pacer.h"
|
||||
#include "wivrn_packets.h"
|
||||
|
||||
#include <array>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
class wivrn_session;
|
||||
class video_encoder;
|
||||
|
||||
struct pseudo_swapchain
|
||||
{
|
||||
#ifdef __cpp_lib_atomic_lock_free_type_aliases
|
||||
using status_type = std::atomic_unsigned_lock_free;
|
||||
#else
|
||||
using status_type = std::atomic_uint64_t;
|
||||
#endif
|
||||
enum class status_t
|
||||
{
|
||||
free,
|
||||
acquired,
|
||||
encoding,
|
||||
};
|
||||
struct item
|
||||
{
|
||||
image_allocation image;
|
||||
vk::raii::ImageView image_view_y = nullptr;
|
||||
vk::raii::ImageView image_view_cbcr = nullptr;
|
||||
status_t status;
|
||||
};
|
||||
std::vector<item> images;
|
||||
|
||||
// bitmask of encoder status, first bit to request exit, then one bit per thread:
|
||||
// 0 when encoder is done
|
||||
// 1 when busy/image to be encoded
|
||||
status_type status;
|
||||
|
||||
// Data to be encoded
|
||||
vk::raii::Fence fence = nullptr;
|
||||
vk::raii::CommandBuffer command_buffer = nullptr;
|
||||
|
||||
int64_t frame_index;
|
||||
to_headset::video_stream_data_shard::view_info_t view_info{};
|
||||
};
|
||||
|
||||
class wivrn_comp_target : public comp_target
|
||||
{
|
||||
to_headset::video_stream_description desc{};
|
||||
|
||||
std::optional<wivrn_vk_bundle> wivrn_bundle;
|
||||
vk::raii::CommandPool command_pool = nullptr;
|
||||
|
||||
int64_t current_frame_id = 0;
|
||||
|
||||
pseudo_swapchain psc;
|
||||
|
||||
VkColorSpaceKHR color_space;
|
||||
|
||||
std::array<encoder_settings, 3> settings;
|
||||
std::list<std::jthread> encoder_threads;
|
||||
std::vector<std::shared_ptr<video_encoder>> encoders;
|
||||
|
||||
wivrn::wivrn_session & cnx;
|
||||
|
||||
std::atomic<float> requested_refresh_rate;
|
||||
std::atomic<bool> skip_encoding;
|
||||
|
||||
inline vk_bundle * get_vk()
|
||||
{
|
||||
return &c->base.vk;
|
||||
}
|
||||
|
||||
void init_semaphores();
|
||||
void fini_semaphores();
|
||||
VkResult create_images_impl(vk::ImageUsageFlags flags);
|
||||
void destroy_images();
|
||||
void create_encoders();
|
||||
|
||||
void run_present(std::stop_token stop_token, int index, std::vector<std::shared_ptr<video_encoder>> encoders);
|
||||
|
||||
bool init_pre_vulkan();
|
||||
bool init_post_vulkan(uint32_t preferred_width, uint32_t preferred_height);
|
||||
bool check_ready();
|
||||
void create_images(const struct comp_target_create_images_info * create_info, struct vk_bundle_queue * present_queue);
|
||||
bool has_images();
|
||||
VkResult acquire(uint32_t * out_index);
|
||||
VkResult present(struct vk_bundle_queue * present_queue,
|
||||
uint32_t index,
|
||||
uint64_t timeline_semaphore_value,
|
||||
int64_t desired_present_time_ns,
|
||||
int64_t present_slop_ns);
|
||||
void flush();
|
||||
void calc_frame_pacing(int64_t * out_frame_id,
|
||||
int64_t * out_wake_up_time_ns,
|
||||
int64_t * out_desired_present_time_ns,
|
||||
int64_t * out_present_slop_ns,
|
||||
int64_t * out_predicted_display_time_ns);
|
||||
void mark_timing_point(enum comp_target_timing_point point,
|
||||
int64_t frame_id,
|
||||
int64_t when_ns);
|
||||
VkResult update_timings();
|
||||
void info_gpu(int64_t frame_id, int64_t gpu_start_ns, int64_t gpu_end_ns, int64_t when_ns);
|
||||
void set_title(const char * title);
|
||||
xrt_result_t get_refresh_rates(uint32_t * count, float * refresh_rates_hz);
|
||||
xrt_result_t get_current_refresh_rate(float * refresh_rate_hz);
|
||||
xrt_result_t request_refresh_rate(float refresh_rate_hz);
|
||||
void destroy();
|
||||
|
||||
public:
|
||||
static std::vector<const char *> wanted_instance_extensions;
|
||||
static std::vector<const char *> wanted_device_extensions;
|
||||
|
||||
wivrn_pacer pacer;
|
||||
std::optional<wivrn_foveation> foveation;
|
||||
|
||||
using base = comp_target;
|
||||
wivrn_comp_target(wivrn::wivrn_session & cnx, struct comp_compositor * c);
|
||||
~wivrn_comp_target();
|
||||
|
||||
void on_feedback(const from_headset::feedback &, const clock_offset &);
|
||||
void reset_encoders();
|
||||
|
||||
float get_requested_refresh_rate() const;
|
||||
void reset_requested_refresh_rate();
|
||||
|
||||
void pause();
|
||||
void resume();
|
||||
|
||||
void set_bitrate(uint32_t bitrate_bps);
|
||||
void set_refresh_rate(float);
|
||||
float get_refresh_rate();
|
||||
};
|
||||
|
||||
inline float get_default_rate(const from_headset::headset_info_packet & info, const from_headset::settings_changed & settings)
|
||||
{
|
||||
if (settings.preferred_refresh_rate)
|
||||
return settings.preferred_refresh_rate;
|
||||
return info.available_refresh_rates.back();
|
||||
}
|
||||
|
||||
} // namespace wivrn
|
||||
@@ -50,7 +50,7 @@ class wivrn_controller : public xrt_device
|
||||
wivrn::wivrn_session * cnx;
|
||||
|
||||
public:
|
||||
using base = xrt_device;
|
||||
using base_t = xrt_device;
|
||||
wivrn_controller(xrt_device_name name, int hand_id, xrt_device * hmd, wivrn::wivrn_session * cnx);
|
||||
|
||||
xrt_result_t update_inputs();
|
||||
|
||||
@@ -42,7 +42,7 @@ class wivrn_eye_tracker : public xrt_device
|
||||
wivrn_session & cnx;
|
||||
|
||||
public:
|
||||
using base = xrt_device;
|
||||
using base_t = xrt_device;
|
||||
wivrn_eye_tracker(wivrn_session &);
|
||||
|
||||
xrt_result_t update_inputs();
|
||||
|
||||
@@ -94,7 +94,7 @@ class wivrn_fb_face2_tracker : public xrt_device
|
||||
wivrn::wivrn_session & cnx;
|
||||
|
||||
public:
|
||||
using base = xrt_device;
|
||||
using base_t = xrt_device;
|
||||
wivrn_fb_face2_tracker(xrt_device * hmd, wivrn::wivrn_session & cnx);
|
||||
|
||||
xrt_result_t update_inputs();
|
||||
|
||||
@@ -1,477 +0,0 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2024 galister <galister@librevr.org>
|
||||
* Copyright (C) 2025 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "render/render_interface.h"
|
||||
|
||||
#include "wivrn_foveation.h"
|
||||
|
||||
#include "driver/xrt_cast.h"
|
||||
#include "utils/wivrn_vk_bundle.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include "xrt/xrt_defines.h"
|
||||
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <ranges>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
#include <vulkan/vulkan_structs.hpp>
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
extern const std::map<std::string, std::vector<uint32_t>> shaders;
|
||||
|
||||
bool render_distortion_images_ensure(struct render_resources * r,
|
||||
struct vk_bundle * vk,
|
||||
struct xrt_device * xdev,
|
||||
bool pre_rotate)
|
||||
{
|
||||
if (r->distortion.buffer == VK_NULL_HANDLE)
|
||||
r->distortion.buffer = wivrn::wivrn_foveation::instance().get_gpu_buffer();
|
||||
return true;
|
||||
}
|
||||
|
||||
void render_distortion_images_fini(struct render_resources * r)
|
||||
{
|
||||
r->distortion.buffer = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
// a, b: parameters computed by solve_foveation
|
||||
// λ: pixel ratio between full size and foveated image (in range ]0,1[)
|
||||
// c: coordinates in -1,1 range of the full size image where pixel ratio must be 1:1
|
||||
// x: coordinates in -1,1 range of the foveated image
|
||||
// result: full size image coordinates in -1,1 range
|
||||
static double defoveate(double a, double b, double λ, double c, double x)
|
||||
{
|
||||
// In order to save encoding, transmit and decoding time, only a portion of the image is encoded in full resolution.
|
||||
// on each axis, foveated coordinates are defined by the following formula.
|
||||
return λ / a * tan(a * x + b) + c;
|
||||
// a and b are defined such as:
|
||||
// edges of the image are not moved
|
||||
// f(-1) = -1
|
||||
// f( 1) = 1
|
||||
// the function also enforces pixel ratio 1:1 at fovea
|
||||
// df⁻¹(x)/dx = 1/scale for x = c
|
||||
|
||||
// We then ensure that source and destination pixel grids match by
|
||||
// rounding to integer pixel ratios: 1:1, 1:2 etc.
|
||||
// Finally, pixel spans are sorted so that we only have increasing
|
||||
// ratios going out from the center.
|
||||
}
|
||||
|
||||
static std::tuple<float, float> solve_foveation(float λ, float c)
|
||||
{
|
||||
// Compute a and b for the foveation function such that:
|
||||
// foveate(a, b, scale, c, -1) = -1 (eq. 1)
|
||||
// foveate(a, b, scale, c, 1) = 1 (eq. 2)
|
||||
//
|
||||
// Use eq. 2 to express a as function of b, then replace in eq. 1
|
||||
// equation that needs to be null is:
|
||||
auto b = [λ, c](double a) { return atan(a * (1 - c) / λ) - a; };
|
||||
auto eq = [λ, c](double a) { return atan(a * (1 - c) / λ) + atan(a * (1 + c) / λ) - 2 * a; }; // (eq. 3)
|
||||
|
||||
// function starts positive, reaches a maximum then decreases to -∞
|
||||
double a0 = 0;
|
||||
// Find a negative value by computing eq(2^n)
|
||||
double a1 = 1;
|
||||
while (eq(a1) > 0)
|
||||
a1 *= 2;
|
||||
|
||||
// last computed values for f(a0) and f(a1)
|
||||
std::optional<double> f_a0;
|
||||
double f_a1 = eq(a1);
|
||||
|
||||
int n = 0;
|
||||
double a = 0;
|
||||
while (std::abs(a1 - a0) > 0.0000001 && n++ < 100)
|
||||
{
|
||||
if (not f_a0)
|
||||
{
|
||||
// use binary search
|
||||
a = 0.5 * (a0 + a1);
|
||||
double val = eq(a);
|
||||
if (val > 0)
|
||||
{
|
||||
a0 = a;
|
||||
f_a0 = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
a1 = a;
|
||||
f_a1 = val;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// f(a1) is always defined
|
||||
// when f(a0) is defined, use secant method
|
||||
a = a1 - f_a1 * (a1 - a0) / (f_a1 - *f_a0);
|
||||
a0 = a1;
|
||||
a1 = a;
|
||||
f_a0 = f_a1;
|
||||
f_a1 = eq(a);
|
||||
}
|
||||
}
|
||||
|
||||
return {a, b(a)};
|
||||
}
|
||||
|
||||
static bool is_zero_quat(xrt_quat q)
|
||||
{
|
||||
return q.x == 0 and q.y == 0 and q.z == 0 and q.w == 0;
|
||||
}
|
||||
|
||||
static xrt_vec2 yaw_pitch(xrt_quat q)
|
||||
{
|
||||
if (is_zero_quat(q))
|
||||
return xrt_vec2{};
|
||||
|
||||
float sine_theta = std::clamp(-2.0f * (q.y * q.z - q.w * q.x), -1.0f, 1.0f);
|
||||
|
||||
float pitch = std::asin(sine_theta);
|
||||
|
||||
if (std::abs(sine_theta) > 0.99999f)
|
||||
{
|
||||
float scale = std::copysign(2.0, sine_theta);
|
||||
return {scale * std::atan2(-q.z, q.w), pitch};
|
||||
}
|
||||
|
||||
return {
|
||||
std::atan2(2.0f * (q.x * q.z + q.w * q.y),
|
||||
q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z),
|
||||
pitch};
|
||||
}
|
||||
|
||||
static float angles_to_center(float e, float l, float r)
|
||||
{
|
||||
e = tan(e);
|
||||
l = tan(l);
|
||||
r = tan(r);
|
||||
float res = std::clamp((e - l) / (r - l) * 2 - 1, -1.f, 1.f);
|
||||
// If the center isn't in the FoV, fallback to middle of image
|
||||
if (std::isnan(res))
|
||||
return 0;
|
||||
return res;
|
||||
}
|
||||
|
||||
static float convergence_angle(float distance, float eye_x, float gaze_yaw)
|
||||
{
|
||||
auto b = distance * std::sin(gaze_yaw) - eye_x;
|
||||
return std::asin(b / distance);
|
||||
}
|
||||
|
||||
static void fill_param_2d(
|
||||
float c,
|
||||
size_t foveated_dim,
|
||||
size_t source_dim,
|
||||
std::vector<uint16_t> & out)
|
||||
{
|
||||
float scale = float(foveated_dim) / source_dim;
|
||||
auto [a, b] = solve_foveation(scale, c);
|
||||
|
||||
uint16_t last = 0;
|
||||
std::vector<uint16_t> left; // index 0: 1:1 ratio, then 2:1 etc.
|
||||
std::vector<uint16_t> right;
|
||||
for (size_t i = 1; i < foveated_dim; ++i)
|
||||
{
|
||||
double u = (i * 2.) / foveated_dim - 1;
|
||||
auto f = defoveate(a, b, scale, c, u);
|
||||
uint16_t n = std::clamp<uint16_t>((f * 0.5 + 0.5) * source_dim + 0.5, 0, source_dim);
|
||||
assert(n > last);
|
||||
size_t count = n - last;
|
||||
auto & vec = u < c ? left : right;
|
||||
if (count > vec.size())
|
||||
vec.resize(count);
|
||||
vec[count - 1]++;
|
||||
last = n;
|
||||
}
|
||||
assert(last < source_dim);
|
||||
size_t count = source_dim - last;
|
||||
if (count > right.size())
|
||||
right.resize(count);
|
||||
right[count - 1]++;
|
||||
|
||||
count = std::max(left.size(), right.size());
|
||||
out.clear();
|
||||
out.resize(count - left.size());
|
||||
out.insert(out.end(), left.rbegin(), left.rend());
|
||||
if (not right.empty())
|
||||
out.back() += right.front();
|
||||
if (right.size() > 1)
|
||||
out.insert(out.end(), right.begin() + 1, right.end());
|
||||
out.resize(count * 2 - 1);
|
||||
}
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
void wivrn_foveation::compute_params(
|
||||
xrt_rect src[2],
|
||||
const xrt_fov fovs[2])
|
||||
{
|
||||
auto e = yaw_pitch(gaze);
|
||||
|
||||
if (manual_foveation.enabled)
|
||||
e.y = manual_foveation.pitch;
|
||||
|
||||
for (size_t i = 0; i < 2; ++i)
|
||||
{
|
||||
const auto & fov = fovs[i];
|
||||
|
||||
size_t extent_w = std::abs(src[i].extent.w);
|
||||
if (foveated_width < extent_w)
|
||||
{
|
||||
auto distance = manual_foveation.enabled ? manual_foveation.distance : convergence_distance;
|
||||
auto angle_x = convergence_angle(distance, eye_x[i], -e.x);
|
||||
auto center = angles_to_center(angle_x, fov.angle_left, fov.angle_right);
|
||||
fill_param_2d(center, foveated_width, extent_w, params[i].x);
|
||||
}
|
||||
else
|
||||
params[i].x = {uint16_t(src[i].extent.w)};
|
||||
|
||||
size_t extent_h = std::abs(src[i].extent.h);
|
||||
if (foveated_height < extent_h)
|
||||
{
|
||||
auto angle_y = -e.y;
|
||||
if (is_zero_quat(gaze) and not manual_foveation.enabled)
|
||||
{
|
||||
// Natural gaze is not straight forward, adjust the angle
|
||||
angle_y += angle_offset;
|
||||
}
|
||||
auto center = angles_to_center(-angle_y, fov.angle_up, fov.angle_down);
|
||||
fill_param_2d(center, foveated_height, extent_h, params[i].y);
|
||||
}
|
||||
else
|
||||
params[i].y = {uint16_t(src[i].extent.h)};
|
||||
}
|
||||
}
|
||||
|
||||
wivrn_foveation::wivrn_foveation(wivrn_vk_bundle & bundle, const xrt_hmd_parts & hmd) :
|
||||
foveated_width(hmd.screens[0].w_pixels),
|
||||
foveated_height(hmd.screens[0].h_pixels),
|
||||
// normal sight line is between 10° and 15° below horizontal
|
||||
// https://apps.dtic.mil/sti/tr/pdf/AD0758339.pdf pages 393-394
|
||||
// testing shows 10° looks better
|
||||
angle_offset(10 * M_PI / 180),
|
||||
convergence_distance(1 /* meter*/),
|
||||
command_pool(bundle.device, vk::CommandPoolCreateInfo{.queueFamilyIndex = bundle.queue_family_index}),
|
||||
cmd(std::move(bundle.device.allocateCommandBuffers({
|
||||
.commandPool = *command_pool,
|
||||
.commandBufferCount = 1,
|
||||
})[0])),
|
||||
gpu_buffer(
|
||||
bundle.device,
|
||||
{
|
||||
.size = sizeof(render_compute_distortion_foveation_data),
|
||||
.usage = vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eStorageBuffer,
|
||||
},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
},
|
||||
"foveation storage buffer")
|
||||
{
|
||||
if (not(gpu_buffer.properties() & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT))
|
||||
{
|
||||
host_buffer = buffer_allocation(
|
||||
bundle.device,
|
||||
{
|
||||
.size = gpu_buffer.info().size,
|
||||
.usage = vk::BufferUsageFlagBits::eTransferSrc,
|
||||
},
|
||||
{
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST,
|
||||
},
|
||||
"foveation staging buffer");
|
||||
}
|
||||
bundle.name(command_pool, "foveation command pool");
|
||||
bundle.name(cmd, "foveation command buffer");
|
||||
}
|
||||
|
||||
void wivrn_foveation::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
|
||||
const uint8_t orientation_ok = from_headset::tracking::orientation_valid | from_headset::tracking::orientation_tracked;
|
||||
|
||||
if (tracking.view_flags & XR_VIEW_STATE_POSITION_VALID_BIT)
|
||||
{
|
||||
eye_x[0] = tracking.views[0].pose.position.x;
|
||||
eye_x[1] = tracking.views[1].pose.position.x;
|
||||
}
|
||||
|
||||
for (const auto & pose: tracking.device_poses)
|
||||
{
|
||||
if (pose.device != device_id::EYE_GAZE)
|
||||
continue;
|
||||
|
||||
if ((pose.flags & orientation_ok) != orientation_ok)
|
||||
return;
|
||||
|
||||
gaze = xrt_cast(pose.pose.orientation);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void wivrn_foveation::update_foveation_center_override(const from_headset::override_foveation_center & center)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
manual_foveation = center;
|
||||
}
|
||||
|
||||
std::array<to_headset::foveation_parameter, 2> wivrn_foveation::get_parameters()
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
return params;
|
||||
}
|
||||
|
||||
static void fill_ubo(
|
||||
std::span<uint32_t> ubo,
|
||||
const std::vector<uint16_t> & params,
|
||||
bool flip,
|
||||
size_t offset,
|
||||
size_t size,
|
||||
[[maybe_unused]] int count)
|
||||
{
|
||||
assert(params.size() % 2 == 1);
|
||||
const int n_ratio = (params.size() - 1) / 2;
|
||||
ubo[0] = offset;
|
||||
if (flip)
|
||||
ubo[0] += size;
|
||||
for (auto [i, n]: std::ranges::enumerate_view(params))
|
||||
{
|
||||
const int n_source = std::abs(n_ratio - int(i)) + 1;
|
||||
for (size_t j = 0; j < n; ++j)
|
||||
{
|
||||
assert(count > 0);
|
||||
if (flip)
|
||||
ubo[1] = ubo[0] - n_source;
|
||||
else
|
||||
ubo[1] = ubo[0] + n_source;
|
||||
ubo = ubo.subspan(1);
|
||||
--count;
|
||||
}
|
||||
}
|
||||
if (not ubo.empty())
|
||||
std::ranges::fill(ubo, ubo[0]);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
static bool operator==(const T & a, const T & b)
|
||||
{
|
||||
static_assert(std::has_unique_object_representations_v<T>);
|
||||
return std::memcmp(&a, &b, sizeof(T)) == 0;
|
||||
}
|
||||
static bool operator==(const xrt_quat & a, const xrt_quat & b)
|
||||
{
|
||||
return a.x == b.x and a.y == b.y and a.z == b.z and a.w == b.w;
|
||||
}
|
||||
static bool operator==(const xrt_fov & a, const xrt_fov & b)
|
||||
{
|
||||
return a.angle_left == b.angle_left and a.angle_right == b.angle_right and a.angle_up == b.angle_up and a.angle_down == b.angle_down;
|
||||
}
|
||||
|
||||
vk::Buffer wivrn_foveation::get_gpu_buffer()
|
||||
{
|
||||
return gpu_buffer;
|
||||
}
|
||||
|
||||
vk::CommandBuffer wivrn_foveation::update_foveation_buffer(
|
||||
vk::Buffer target,
|
||||
bool flip_y,
|
||||
xrt_rect source[2],
|
||||
xrt_fov fovs[2])
|
||||
{
|
||||
if (not target)
|
||||
return nullptr;
|
||||
|
||||
// Check if the last value is still valid
|
||||
std::lock_guard lock(mutex);
|
||||
if (last.flip_y == flip_y //
|
||||
and last.src[0] == source[0] //
|
||||
and last.src[1] == source[1] //
|
||||
and last.fovs[0] == fovs[0] //
|
||||
and last.fovs[1] == fovs[1] //
|
||||
and (last.gaze == gaze or manual_foveation.enabled) // Ignore the gaze if foveation center is overridden
|
||||
and std::abs(last.eye_x[0] - eye_x[0]) < 0.0005 //
|
||||
and std::abs(last.eye_x[1] - eye_x[1]) < 0.0005 //
|
||||
and last.manual_foveation.enabled == manual_foveation.enabled //
|
||||
and std::abs(last.manual_foveation.pitch - manual_foveation.pitch) < 0.0005 //
|
||||
and std::abs(last.manual_foveation.distance - manual_foveation.distance) < 0.0005 //
|
||||
)
|
||||
return nullptr;
|
||||
|
||||
assert(target == gpu_buffer);
|
||||
if (host_buffer)
|
||||
{
|
||||
command_pool.reset();
|
||||
cmd.begin({});
|
||||
cmd.copyBuffer(host_buffer, target, vk::BufferCopy{.size = sizeof(render_compute_distortion_foveation_data)});
|
||||
cmd.end();
|
||||
}
|
||||
|
||||
last = {
|
||||
.gaze = gaze,
|
||||
.flip_y = flip_y,
|
||||
.src = {source[0], source[1]},
|
||||
.fovs = {fovs[0], fovs[1]},
|
||||
.eye_x = {eye_x[0], eye_x[1]},
|
||||
.manual_foveation = manual_foveation,
|
||||
};
|
||||
|
||||
compute_params(source, fovs);
|
||||
|
||||
auto ubo = host_buffer ? host_buffer.data<render_compute_distortion_foveation_data>() : gpu_buffer.data<render_compute_distortion_foveation_data>();
|
||||
for (size_t view = 0; view < 2; ++view)
|
||||
{
|
||||
bool flip = false;
|
||||
size_t offset, extent;
|
||||
|
||||
if (source[view].extent.w < 0)
|
||||
{
|
||||
flip = true;
|
||||
offset = source[view].offset.w + source[view].extent.w;
|
||||
extent = -source[view].extent.w;
|
||||
}
|
||||
else
|
||||
{
|
||||
offset = source[view].offset.w;
|
||||
extent = source[view].extent.w;
|
||||
}
|
||||
fill_ubo(std::span(ubo->x + view * RENDER_FOVEATION_BUFFER_DIMENSIONS, RENDER_FOVEATION_BUFFER_DIMENSIONS), params[view].x, flip, offset, extent, foveated_width);
|
||||
|
||||
if (source[view].extent.h < 0)
|
||||
{
|
||||
flip = not flip_y;
|
||||
offset = source[view].offset.h + source[view].extent.h;
|
||||
extent = -source[view].extent.h;
|
||||
}
|
||||
else
|
||||
{
|
||||
flip = flip_y;
|
||||
offset = source[view].offset.h;
|
||||
extent = source[view].extent.h;
|
||||
}
|
||||
fill_ubo(std::span(ubo->y + view * RENDER_FOVEATION_BUFFER_DIMENSIONS, RENDER_FOVEATION_BUFFER_DIMENSIONS), params[view].y, flip, offset, extent, foveated_height);
|
||||
}
|
||||
if (host_buffer)
|
||||
return *cmd;
|
||||
return nullptr;
|
||||
}
|
||||
} // namespace wivrn
|
||||
@@ -47,7 +47,7 @@ class wivrn_generic_tracker : public xrt_device
|
||||
wivrn_session & cnx;
|
||||
|
||||
public:
|
||||
using base = xrt_device;
|
||||
using base_t = xrt_device;
|
||||
wivrn_generic_tracker(int index, xrt_device * hmd, wivrn_session & cnx);
|
||||
|
||||
xrt_result_t update_inputs();
|
||||
|
||||
@@ -59,7 +59,7 @@ class wivrn_hmd : public xrt_device
|
||||
xrt_result_t get_visibility_mask(xrt_visibility_mask_type, uint32_t view_index, xrt_visibility_mask **);
|
||||
|
||||
public:
|
||||
using base = xrt_device;
|
||||
using base_t = xrt_device;
|
||||
wivrn_hmd(wivrn::wivrn_session * cnx,
|
||||
const from_headset::headset_info_packet & info);
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ class wivrn_htc_face_tracker : public xrt_device
|
||||
wivrn::wivrn_session & cnx;
|
||||
|
||||
public:
|
||||
using base = xrt_device;
|
||||
using base_t = xrt_device;
|
||||
wivrn_htc_face_tracker(xrt_device * hmd, wivrn::wivrn_session & cnx);
|
||||
|
||||
xrt_result_t update_inputs();
|
||||
|
||||
+38
-104
@@ -24,9 +24,6 @@
|
||||
#include "application.h"
|
||||
#include "configuration.h"
|
||||
#include "driver/app_pacer.h"
|
||||
#include "main/comp_compositor.h"
|
||||
#include "main/comp_main_interface.h"
|
||||
#include "main/comp_target.h"
|
||||
#include "server/ipc_server.h"
|
||||
#include "util/u_builders.h"
|
||||
#include "util/u_logging.h"
|
||||
@@ -37,11 +34,9 @@
|
||||
|
||||
#include "audio/audio_setup.h"
|
||||
#include "wivrn_android_face_tracker.h"
|
||||
#include "wivrn_comp_target.h"
|
||||
#include "wivrn_config.h"
|
||||
#include "wivrn_eye_tracker.h"
|
||||
#include "wivrn_fb_face2_tracker.h"
|
||||
#include "wivrn_foveation.h"
|
||||
#include "wivrn_generic_tracker.h"
|
||||
#include "wivrn_htc_face_tracker.h"
|
||||
#include "wivrn_ipc.h"
|
||||
@@ -54,6 +49,7 @@
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <magic_enum.hpp>
|
||||
#include <multi/comp_multi_interface.h>
|
||||
#include <stdexcept>
|
||||
#include <string.h>
|
||||
#include <utility>
|
||||
@@ -70,41 +66,6 @@
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
struct wivrn_comp_target_factory : public comp_target_factory
|
||||
{
|
||||
wivrn_session & session;
|
||||
|
||||
wivrn_comp_target_factory(wivrn_session & session) :
|
||||
comp_target_factory{
|
||||
.name = "WiVRn",
|
||||
.identifier = "wivrn",
|
||||
.requires_vulkan_for_create = false,
|
||||
.is_deferred = false,
|
||||
.required_instance_version = VK_MAKE_VERSION(1, 3, 0),
|
||||
.required_instance_extensions = wivrn_comp_target::wanted_instance_extensions.data(),
|
||||
.required_instance_extension_count = wivrn_comp_target::wanted_instance_extensions.size(),
|
||||
.optional_device_extensions = wivrn_comp_target::wanted_device_extensions.data(),
|
||||
.optional_device_extension_count = wivrn_comp_target::wanted_device_extensions.size(),
|
||||
.detect = wivrn_comp_target_factory::detect,
|
||||
.create_target = wivrn_comp_target_factory::create_target},
|
||||
session(session)
|
||||
{
|
||||
}
|
||||
|
||||
static bool detect(const struct comp_target_factory * ctf, struct comp_compositor * c)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool create_target(const struct comp_target_factory * ctf, struct comp_compositor * c, struct comp_target ** out_ct)
|
||||
{
|
||||
auto self = (wivrn_comp_target_factory *)ctf;
|
||||
self->session.comp_target = new wivrn_comp_target(self->session, c);
|
||||
*out_ct = self->session.comp_target;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
bool is_forced_extension(const char * ext_name)
|
||||
{
|
||||
const char * val = std::getenv("WIVRN_FORCE_EXTENSIONS");
|
||||
@@ -122,14 +83,15 @@ wivrn::wivrn_session::wivrn_session(std::unique_ptr<wivrn_connection> connection
|
||||
},
|
||||
connection(std::move(connection)),
|
||||
headset_info(this->connection->info()),
|
||||
settings(get_info().settings),
|
||||
compositor(*this),
|
||||
xrt_system(system),
|
||||
control(*this->connection),
|
||||
hmd(this, get_info()),
|
||||
left_controller(XRT_DEVICE_TOUCH_CONTROLLER, 0, &hmd, this),
|
||||
right_controller(XRT_DEVICE_TOUCH_CONTROLLER, 1, &hmd, this),
|
||||
left_hand_interaction(XRT_DEVICE_EXT_HAND_INTERACTION, 0, &hmd, this),
|
||||
right_hand_interaction(XRT_DEVICE_EXT_HAND_INTERACTION, 1, &hmd, this),
|
||||
settings(get_info().settings)
|
||||
right_hand_interaction(XRT_DEVICE_EXT_HAND_INTERACTION, 1, &hmd, this)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -318,10 +280,11 @@ xrt_result_t wivrn::wivrn_session::create_session(std::unique_ptr<wivrn_connecti
|
||||
return XRT_ERROR_DEVICE_CREATION_FAILED;
|
||||
}
|
||||
|
||||
send_to_main(self->get_info());
|
||||
const auto & info = self->get_info();
|
||||
send_to_main(info);
|
||||
|
||||
wivrn_comp_target_factory ctf(*self);
|
||||
auto xret = comp_main_create_system_compositor(&self->hmd, &ctf, &self->app_pacers, out_xsysc);
|
||||
auto sys_info{self->compositor.sys_info()};
|
||||
auto xret = comp_multi_create_system_compositor(&self->compositor.base, &self->app_pacers, &sys_info, false, out_xsysc);
|
||||
if (xret != XRT_SUCCESS)
|
||||
{
|
||||
U_LOG_E("Failed to create system compositor: %s", u_str_xrt_result(xret));
|
||||
@@ -416,11 +379,7 @@ void wivrn_session::pause_session()
|
||||
if (audio_handle)
|
||||
audio_handle->pause();
|
||||
|
||||
{
|
||||
std::shared_lock lock(comp_target_mutex);
|
||||
if (comp_target)
|
||||
comp_target->pause();
|
||||
}
|
||||
// FIXME: pause compositor
|
||||
}
|
||||
|
||||
void wivrn_session::resume_session()
|
||||
@@ -436,21 +395,18 @@ void wivrn_session::resume_session()
|
||||
send_control(to_headset::feature_control{to_headset::feature_control::hid_input, true});
|
||||
|
||||
{
|
||||
std::shared_lock lock(comp_target_mutex);
|
||||
if (comp_target)
|
||||
float target_fps = default_rate();
|
||||
auto current_fps = compositor.get_refresh_rate();
|
||||
|
||||
if (target_fps != current_fps)
|
||||
{
|
||||
float target_fps = get_default_rate(get_info(), *get_settings());
|
||||
|
||||
if (target_fps != comp_target->get_refresh_rate())
|
||||
{
|
||||
(*this)(from_headset::refresh_rate_changed{
|
||||
.from = comp_target->get_refresh_rate(),
|
||||
.to = target_fps,
|
||||
});
|
||||
}
|
||||
|
||||
comp_target->resume();
|
||||
(*this)(from_headset::refresh_rate_changed{
|
||||
.from = current_fps,
|
||||
.to = target_fps,
|
||||
});
|
||||
}
|
||||
|
||||
// FIXME: resume compositor
|
||||
}
|
||||
|
||||
if (get_info().user_presence)
|
||||
@@ -482,10 +438,12 @@ bool wivrn_session::connected()
|
||||
return connection->is_active();
|
||||
}
|
||||
|
||||
void wivrn_session::unset_comp_target()
|
||||
float wivrn_session::default_rate()
|
||||
{
|
||||
std::lock_guard lock(comp_target_mutex);
|
||||
comp_target = nullptr;
|
||||
auto s = settings.lock();
|
||||
if (s->preferred_refresh_rate)
|
||||
return s->preferred_refresh_rate;
|
||||
return headset_info.available_refresh_rates.back();
|
||||
}
|
||||
|
||||
void wivrn_session::add_tracking_request(device_id device, int64_t at_ns, int64_t produced_ns, int64_t now)
|
||||
@@ -508,11 +466,7 @@ void wivrn_session::operator()(const from_headset::settings_changed & settings)
|
||||
*this->settings.lock() = settings;
|
||||
|
||||
if (settings.bitrate_bps != 0)
|
||||
{
|
||||
std::lock_guard lock(comp_target_mutex);
|
||||
if (comp_target)
|
||||
comp_target->set_bitrate(settings.bitrate_bps);
|
||||
}
|
||||
compositor.set_bitrate(settings.bitrate_bps);
|
||||
|
||||
wivrn_ipc_socket_monado->send(std::move(settings));
|
||||
}
|
||||
@@ -654,11 +608,7 @@ void wivrn_session::operator()(const from_headset::tracking & tracking)
|
||||
|
||||
if (eye_tracker)
|
||||
eye_tracker->update_tracking(tracking, offset);
|
||||
{
|
||||
std::shared_lock lock(comp_target_mutex);
|
||||
if (comp_target)
|
||||
comp_target->foveation->update_tracking(tracking, offset);
|
||||
}
|
||||
compositor.update_tracking(tracking);
|
||||
|
||||
if (android_face_tracker)
|
||||
android_face_tracker->update_tracking(tracking, offset);
|
||||
@@ -670,9 +620,7 @@ void wivrn_session::operator()(const from_headset::tracking & tracking)
|
||||
|
||||
void wivrn_session::operator()(from_headset::override_foveation_center && foveation_center)
|
||||
{
|
||||
std::shared_lock lock(comp_target_mutex);
|
||||
if (comp_target)
|
||||
comp_target->foveation->update_foveation_center_override(foveation_center);
|
||||
compositor.update_foveation_center_override(foveation_center);
|
||||
}
|
||||
|
||||
void wivrn_session::operator()(from_headset::derived_pose && derived)
|
||||
@@ -738,11 +686,7 @@ void wivrn_session::operator()(from_headset::feedback && feedback)
|
||||
clock_offset o = offset_est.get_offset();
|
||||
if (not o)
|
||||
return;
|
||||
{
|
||||
std::shared_lock lock(comp_target_mutex);
|
||||
if (comp_target)
|
||||
comp_target->on_feedback(feedback, o);
|
||||
}
|
||||
compositor.on_feedback(feedback, o);
|
||||
|
||||
if (feedback.received_first_packet)
|
||||
dump_time("receive_begin", feedback.frame_index, o.from_headset(feedback.received_first_packet), feedback.stream_index);
|
||||
@@ -811,11 +755,7 @@ void wivrn_session::operator()(from_headset::user_presence_changed && event)
|
||||
|
||||
void wivrn_session::operator()(from_headset::refresh_rate_changed && event)
|
||||
{
|
||||
{
|
||||
std::shared_lock lock(comp_target_mutex);
|
||||
if (comp_target)
|
||||
comp_target->set_refresh_rate(event.to);
|
||||
}
|
||||
compositor.set_refresh_rate(event.to);
|
||||
push_event(
|
||||
{
|
||||
.display = {
|
||||
@@ -968,9 +908,7 @@ void wivrn_session::operator()(to_monado::disconnect &&)
|
||||
|
||||
void wivrn_session::operator()(to_monado::set_bitrate && data)
|
||||
{
|
||||
std::shared_lock lock(comp_target_mutex);
|
||||
if (comp_target)
|
||||
comp_target->set_bitrate(data.bitrate_bps);
|
||||
compositor.set_bitrate(data.bitrate_bps);
|
||||
}
|
||||
|
||||
void wivrn_session::operator()(to_headset::stream_tab_change && data)
|
||||
@@ -1080,22 +1018,18 @@ void wivrn_session::run_worker(std::stop_token stop)
|
||||
const bool do_control = control.advance(now);
|
||||
if (do_refresh or do_control)
|
||||
{
|
||||
std::shared_lock lock(comp_target_mutex);
|
||||
if (comp_target)
|
||||
if (do_refresh)
|
||||
{
|
||||
if (do_refresh)
|
||||
{
|
||||
{
|
||||
scoped_lock lock(xrt_system.sessions.mutex);
|
||||
if (xrt_system.sessions.count == 0)
|
||||
comp_target->reset_requested_refresh_rate();
|
||||
}
|
||||
if (comp_target->get_requested_refresh_rate() == 0)
|
||||
refresh.adjust(*connection);
|
||||
scoped_lock lock(xrt_system.sessions.mutex);
|
||||
if (xrt_system.sessions.count == 0)
|
||||
compositor.request_display_refresh_rate(0);
|
||||
}
|
||||
if (do_control)
|
||||
control.resolve(comp_target->pacer.get_frame_duration(), tracking_latency);
|
||||
if (compositor.get_requested_refresh_rate() == 0)
|
||||
refresh.adjust(*connection);
|
||||
}
|
||||
if (do_control)
|
||||
control.resolve(compositor.get_frame_duration(), tracking_latency);
|
||||
}
|
||||
poll_session_loss();
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
#include "app_pacer.h"
|
||||
#include "clock_offset.h"
|
||||
#include "compositor/compositor.h"
|
||||
#include "inplace_vector.hpp"
|
||||
#include "tracking_control.h"
|
||||
#include "utils/thread_safe.h"
|
||||
@@ -42,7 +43,6 @@
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <shared_mutex>
|
||||
#include <thread>
|
||||
|
||||
struct ipc_server;
|
||||
@@ -59,14 +59,15 @@ class wivrn_fb_face2_tracker;
|
||||
class wivrn_htc_face_tracker;
|
||||
class wivrn_generic_tracker;
|
||||
struct audio_device;
|
||||
struct wivrn_comp_target;
|
||||
struct wivrn_comp_target_factory;
|
||||
|
||||
class wivrn_session : public xrt_system_devices
|
||||
{
|
||||
friend wivrn_comp_target_factory;
|
||||
std::unique_ptr<wivrn_connection> connection;
|
||||
from_headset::headset_info_packet headset_info;
|
||||
// run-time editable settings
|
||||
thread_safe<from_headset::settings_changed> settings;
|
||||
|
||||
wivrn::compositor compositor;
|
||||
pacing_app_factory app_pacers;
|
||||
|
||||
u_system & xrt_system;
|
||||
@@ -100,9 +101,6 @@ class wivrn_session : public xrt_system_devices
|
||||
beman::inplace_vector::inplace_vector<wivrn_generic_tracker, from_headset::body_tracking::max_tracked_poses> generic_trackers;
|
||||
std::optional<wivrn_uinput> uinput_handler;
|
||||
|
||||
std::shared_mutex comp_target_mutex;
|
||||
wivrn_comp_target * comp_target;
|
||||
|
||||
clock_offset_estimator offset_est;
|
||||
std::atomic<XrDuration> tracking_latency; // production to reception time
|
||||
|
||||
@@ -111,9 +109,6 @@ class wivrn_session : public xrt_system_devices
|
||||
|
||||
std::unique_ptr<audio_device> audio_handle;
|
||||
|
||||
// run-time editable settings
|
||||
thread_safe<from_headset::settings_changed> settings;
|
||||
|
||||
// when sessions shall be destroyed, key is client id, value is timestamp
|
||||
thread_safe<std::map<uint32_t, int64_t>> session_loss;
|
||||
|
||||
@@ -123,7 +118,7 @@ class wivrn_session : public xrt_system_devices
|
||||
wivrn_session(std::unique_ptr<wivrn_connection> connection, u_system &);
|
||||
|
||||
public:
|
||||
using base = xrt_system_devices;
|
||||
using base_t = xrt_system_devices;
|
||||
~wivrn_session();
|
||||
|
||||
static xrt_result_t create_session(std::unique_ptr<wivrn_connection> connection,
|
||||
@@ -145,13 +140,13 @@ public:
|
||||
return headset_info;
|
||||
};
|
||||
|
||||
float default_rate();
|
||||
|
||||
locked<from_headset::settings_changed> get_settings()
|
||||
{
|
||||
return settings.lock();
|
||||
}
|
||||
|
||||
void unset_comp_target();
|
||||
|
||||
wivrn_hmd & get_hmd()
|
||||
{
|
||||
return hmd;
|
||||
|
||||
@@ -19,12 +19,12 @@
|
||||
#include "encoder_settings.h"
|
||||
|
||||
#include "driver/configuration.h"
|
||||
#include "driver/wivrn_comp_target.h"
|
||||
#include "driver/wivrn_session.h"
|
||||
#include "util/u_logging.h"
|
||||
#include "utils/wivrn_vk_bundle.h"
|
||||
#include "video_encoder.h"
|
||||
|
||||
#include "wivrn_packets.h"
|
||||
|
||||
#include <magic_enum.hpp>
|
||||
#include <string>
|
||||
#include <vulkan/vulkan.hpp>
|
||||
@@ -46,6 +46,7 @@ static const double passthrough_bitrate_factor = 0.05;
|
||||
|
||||
static void split_bitrate(std::array<wivrn::encoder_settings, 3> & encoders, uint64_t bitrate)
|
||||
{
|
||||
assert(bitrate > 0);
|
||||
double total_weight = 0;
|
||||
for (auto [i, encoder]: std::ranges::enumerate_view(encoders))
|
||||
{
|
||||
@@ -75,22 +76,13 @@ static void split_bitrate(std::array<wivrn::encoder_settings, 3> & encoders, uin
|
||||
|
||||
void print_encoders(const std::array<wivrn::encoder_settings, 3> & encoders)
|
||||
{
|
||||
int group = -1;
|
||||
std::stringstream str;
|
||||
str << "Encoder configuration:";
|
||||
for (auto & encoder: encoders)
|
||||
{
|
||||
if (encoder.group != group)
|
||||
{
|
||||
group = encoder.group;
|
||||
str << "\n\t* Group " << group << ":";
|
||||
}
|
||||
else
|
||||
str << "\n";
|
||||
|
||||
str << "\n\t\t" << encoder.encoder_name << " (" << magic_enum::enum_name(encoder.codec) << " " << encoder.bit_depth << "-bit)"
|
||||
<< "\n\t\tsize: " << encoder.width << "x" << encoder.height
|
||||
<< "\n\t\tbitrate: " << int(encoder.bitrate / 100'000) / 10. << "Mbit/s";
|
||||
str << "\n\t* " << encoder.encoder_name << " (" << magic_enum::enum_name(encoder.codec) << " " << encoder.bit_depth << "-bit)"
|
||||
<< "\n\t size: " << encoder.width << "x" << encoder.height
|
||||
<< "\n\t bitrate: " << int(encoder.bitrate / 100'000) / 10. << "Mbit/s";
|
||||
}
|
||||
U_LOG_I("%s", str.str().c_str());
|
||||
}
|
||||
@@ -111,7 +103,7 @@ namespace
|
||||
{
|
||||
class prober
|
||||
{
|
||||
wivrn_vk_bundle & vk;
|
||||
wivrn::vk_bundle & vk;
|
||||
const from_headset::headset_info_packet & info;
|
||||
const bool nvidia;
|
||||
|
||||
@@ -211,7 +203,7 @@ class prober
|
||||
#endif
|
||||
|
||||
public:
|
||||
prober(wivrn_vk_bundle & vk, const from_headset::headset_info_packet & info) :
|
||||
prober(wivrn::vk_bundle & vk, const from_headset::headset_info_packet & info) :
|
||||
vk(vk), info(info), nvidia(is_nvidia(vk.physical_device)) {}
|
||||
|
||||
std::pair<std::string, video_codec> select_encoder(const configuration::encoder & config)
|
||||
@@ -283,28 +275,23 @@ static uint16_t align(uint16_t value, uint16_t alignment)
|
||||
return ((value + alignment - 1) / alignment) * alignment;
|
||||
}
|
||||
|
||||
std::array<encoder_settings, 3> get_encoder_settings(wivrn_vk_bundle & bundle, const from_headset::headset_info_packet & info, const from_headset::settings_changed & settings)
|
||||
std::array<encoder_settings, 3> get_encoder_settings(wivrn::vk_bundle & bundle, wivrn_session & session)
|
||||
{
|
||||
configuration config;
|
||||
|
||||
std::array<wivrn::encoder_settings, 3> res;
|
||||
const auto & info = session.get_info();
|
||||
const auto settings = *session.get_settings();
|
||||
|
||||
prober prober{bundle, info};
|
||||
std::unordered_map<std::string, int> groups;
|
||||
int next_group = 0;
|
||||
|
||||
for (auto [src, dst]: std::ranges::zip_view(config.encoders, res))
|
||||
{
|
||||
dst.fps = get_default_rate(info, settings);
|
||||
dst.fps = session.default_rate();
|
||||
dst.options = src.options;
|
||||
dst.device = src.device;
|
||||
|
||||
std::tie(dst.encoder_name, dst.codec) = prober.select_encoder(src);
|
||||
|
||||
auto [it, inserted] = groups.emplace(dst.encoder_name, next_group);
|
||||
dst.group = it->second;
|
||||
if (inserted)
|
||||
++next_group;
|
||||
}
|
||||
|
||||
auto width = align(info.stream_eye_width, 64);
|
||||
|
||||
@@ -27,7 +27,8 @@
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
struct wivrn_vk_bundle;
|
||||
struct vk_bundle;
|
||||
class wivrn_session;
|
||||
|
||||
struct encoder_settings
|
||||
{
|
||||
@@ -40,13 +41,11 @@ struct encoder_settings
|
||||
uint64_t bitrate; // bit/s
|
||||
double bitrate_multiplier; // encoder bitrate / global bitrate
|
||||
std::map<std::string, std::string> options; // additional encoder-specific configuration
|
||||
// encoders in the same group are executed in sequence
|
||||
int group = 0;
|
||||
int bit_depth;
|
||||
std::optional<std::string> device;
|
||||
};
|
||||
|
||||
std::array<encoder_settings, 3> get_encoder_settings(wivrn_vk_bundle &, const from_headset::headset_info_packet & info, const from_headset::settings_changed & settings);
|
||||
std::array<encoder_settings, 3> get_encoder_settings(wivrn::vk_bundle &, wivrn_session &);
|
||||
|
||||
void print_encoders(const std::array<wivrn::encoder_settings, 3> & encoders);
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
*/
|
||||
|
||||
// must be included before vulkan_raii
|
||||
#include "vk/vk_helpers.h"
|
||||
|
||||
#include "video_encoder_va.h"
|
||||
|
||||
@@ -156,11 +155,11 @@ vk::Format drm_to_vulkan_fmt(uint32_t drm_fourcc, int bit_depth)
|
||||
|
||||
} // namespace
|
||||
|
||||
video_encoder_va::video_encoder_va(wivrn_vk_bundle & vk,
|
||||
video_encoder_va::video_encoder_va(wivrn::vk_bundle & vk,
|
||||
const wivrn::encoder_settings & settings,
|
||||
uint8_t stream_idx) :
|
||||
video_encoder_ffmpeg(stream_idx, settings),
|
||||
synchronization2(vk.vk.features.synchronization_2)
|
||||
synchronization2(std::get<vk::PhysicalDeviceVulkan13Features>(vk.feat).synchronization2)
|
||||
{
|
||||
auto drm_hw_ctx = make_drm_hw_ctx(vk.physical_device, settings.device);
|
||||
AVBufferRef * tmp;
|
||||
|
||||
@@ -29,7 +29,6 @@
|
||||
namespace wivrn
|
||||
{
|
||||
struct encoder_settings;
|
||||
struct wivrn_vk_bundle;
|
||||
|
||||
class video_encoder_va : public video_encoder_ffmpeg
|
||||
{
|
||||
@@ -46,7 +45,7 @@ class video_encoder_va : public video_encoder_ffmpeg
|
||||
bool synchronization2 = false;
|
||||
|
||||
public:
|
||||
video_encoder_va(wivrn_vk_bundle &, const wivrn::encoder_settings & settings, uint8_t stream_index);
|
||||
video_encoder_va(wivrn::vk_bundle &, const wivrn::encoder_settings & settings, uint8_t stream_index);
|
||||
|
||||
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, bool transferred, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override;
|
||||
|
||||
|
||||
@@ -101,7 +101,7 @@ std::shared_ptr<video_encoder::sender> video_encoder::sender::get()
|
||||
}
|
||||
|
||||
std::unique_ptr<video_encoder> video_encoder::create(
|
||||
wivrn_vk_bundle & wivrn_vk,
|
||||
wivrn::vk_bundle & wivrn_vk,
|
||||
const encoder_settings & settings,
|
||||
uint8_t stream_idx)
|
||||
{
|
||||
|
||||
@@ -37,7 +37,7 @@ namespace wivrn
|
||||
{
|
||||
|
||||
struct encoder_settings;
|
||||
struct wivrn_vk_bundle;
|
||||
struct vk_bundle;
|
||||
class wivrn_session;
|
||||
|
||||
inline const char * encoder_nvenc = "nvenc";
|
||||
@@ -111,7 +111,7 @@ protected:
|
||||
|
||||
public:
|
||||
static std::unique_ptr<video_encoder> create(
|
||||
wivrn_vk_bundle &,
|
||||
wivrn::vk_bundle &,
|
||||
const encoder_settings & settings,
|
||||
uint8_t stream_idx);
|
||||
|
||||
|
||||
@@ -149,7 +149,7 @@ void video_encoder_nvenc::set_init_params_fps(float framerate)
|
||||
}
|
||||
|
||||
video_encoder_nvenc::video_encoder_nvenc(
|
||||
wivrn_vk_bundle & vk,
|
||||
wivrn::vk_bundle & vk,
|
||||
const encoder_settings & settings,
|
||||
uint8_t stream_idx) :
|
||||
video_encoder(stream_idx, settings, std::make_unique<default_idr_handler>(), true),
|
||||
|
||||
@@ -33,7 +33,7 @@ namespace wivrn
|
||||
class video_encoder_nvenc : public video_encoder
|
||||
{
|
||||
private:
|
||||
wivrn_vk_bundle & vk;
|
||||
wivrn::vk_bundle & vk;
|
||||
|
||||
std::shared_ptr<video_encoder_nvenc_shared_state> shared_state;
|
||||
|
||||
@@ -58,7 +58,7 @@ private:
|
||||
void set_init_params_fps(float framerate);
|
||||
|
||||
public:
|
||||
video_encoder_nvenc(wivrn_vk_bundle & vk, const encoder_settings & settings, uint8_t stream_idx);
|
||||
video_encoder_nvenc(wivrn::vk_bundle & vk, const encoder_settings & settings, uint8_t stream_idx);
|
||||
~video_encoder_nvenc();
|
||||
|
||||
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, bool transferred, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override;
|
||||
|
||||
@@ -36,7 +36,7 @@ public:
|
||||
} // namespace
|
||||
|
||||
wivrn::video_encoder_raw::video_encoder_raw(
|
||||
wivrn_vk_bundle & vk,
|
||||
wivrn::vk_bundle & vk,
|
||||
const encoder_settings & settings,
|
||||
uint8_t stream_idx) :
|
||||
video_encoder(stream_idx, settings, std::make_unique<dummy_idr_handler>(), true)
|
||||
|
||||
@@ -31,7 +31,7 @@ class video_encoder_raw : public video_encoder
|
||||
std::array<buffer_allocation, num_slots> buffers;
|
||||
|
||||
public:
|
||||
video_encoder_raw(wivrn_vk_bundle & vk, const encoder_settings & settings, uint8_t stream_idx);
|
||||
video_encoder_raw(wivrn::vk_bundle & vk, const encoder_settings & settings, uint8_t stream_idx);
|
||||
|
||||
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, bool transferred, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override;
|
||||
|
||||
|
||||
@@ -15,13 +15,11 @@
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "vk/vk_helpers.h"
|
||||
|
||||
#include "video_encoder_vulkan.h"
|
||||
|
||||
#include "encoder/encoder_settings.h"
|
||||
#include "util/u_logging.h"
|
||||
#include "utils/scoped_lock.h"
|
||||
#include "utils/wivrn_vk_bundle.h"
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
@@ -157,7 +155,7 @@ vk::VideoFormatPropertiesKHR wivrn::video_encoder_vulkan::select_video_format(
|
||||
}
|
||||
|
||||
wivrn::video_encoder_vulkan::video_encoder_vulkan(
|
||||
wivrn_vk_bundle & vk,
|
||||
wivrn::vk_bundle & vk,
|
||||
const vk::VideoCapabilitiesKHR & video_caps,
|
||||
const vk::VideoEncodeCapabilitiesKHR & in_encode_caps,
|
||||
uint8_t stream_idx,
|
||||
@@ -378,7 +376,7 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca
|
||||
.layerCount = 1},
|
||||
};
|
||||
|
||||
if (not vk.vk.features.video_maintenance_1)
|
||||
if (not std::get<vk::PhysicalDeviceVideoMaintenance1FeaturesKHR>(vk.feat).videoMaintenance1)
|
||||
{
|
||||
image_view_template.subresourceRange.baseArrayLayer = 0;
|
||||
for (size_t i = 0; i < num_slots; ++i)
|
||||
@@ -591,7 +589,7 @@ std::optional<wivrn::video_encoder::data> wivrn::video_encoder_vulkan::encode(ui
|
||||
vk.device.resetFences(*slot_item.fence);
|
||||
|
||||
{
|
||||
wivrn::scoped_lock lock(main_queue ? vk.vk.main_queue->mutex : vk.vk.encode_queue->mutex);
|
||||
std::unique_lock lock(main_queue ? vk.queue_mutex : vk.encode_queue_mutex);
|
||||
auto & queue = main_queue ? vk.queue : vk.encode_queue;
|
||||
queue.submit(vk::SubmitInfo{
|
||||
.commandBufferCount = 1,
|
||||
@@ -961,7 +959,7 @@ void wivrn::video_encoder_vulkan::post_submit(uint8_t slot)
|
||||
};
|
||||
|
||||
{
|
||||
scoped_lock lock(vk.vk.encode_queue->mutex);
|
||||
std::unique_lock lock(vk.encode_queue_mutex);
|
||||
vk.encode_queue.submit2(vk::SubmitInfo2{
|
||||
.waitSemaphoreInfoCount = 1,
|
||||
.pWaitSemaphoreInfos = &wait_sem_info,
|
||||
|
||||
@@ -29,7 +29,7 @@ namespace wivrn
|
||||
{
|
||||
class video_encoder_vulkan : public video_encoder
|
||||
{
|
||||
wivrn_vk_bundle & vk;
|
||||
wivrn::vk_bundle & vk;
|
||||
const vk::VideoEncodeCapabilitiesKHR encode_caps;
|
||||
|
||||
vk::raii::VideoSessionKHR video_session = nullptr;
|
||||
@@ -74,7 +74,7 @@ protected:
|
||||
vk::VideoEncodeRateControlLayerInfoKHR rate_control_layer;
|
||||
std::optional<vk::VideoEncodeRateControlInfoKHR> rate_control;
|
||||
|
||||
video_encoder_vulkan(wivrn_vk_bundle & vk,
|
||||
video_encoder_vulkan(wivrn::vk_bundle & vk,
|
||||
const vk::VideoCapabilitiesKHR & video_caps,
|
||||
const vk::VideoEncodeCapabilitiesKHR & encode_caps,
|
||||
uint8_t stream_idx,
|
||||
|
||||
@@ -70,7 +70,7 @@ static StdVideoH264LevelIdc compute_level(const StdVideoH264SequenceParameterSet
|
||||
}
|
||||
|
||||
wivrn::video_encoder_vulkan_h264::video_encoder_vulkan_h264(
|
||||
wivrn_vk_bundle & vk,
|
||||
wivrn::vk_bundle & vk,
|
||||
const vk::VideoCapabilitiesKHR & video_caps,
|
||||
const vk::VideoEncodeCapabilitiesKHR & encode_caps,
|
||||
uint8_t stream_idx,
|
||||
@@ -210,7 +210,7 @@ auto get_video_caps(vk::raii::PhysicalDevice & phys_dev)
|
||||
}
|
||||
|
||||
std::unique_ptr<wivrn::video_encoder_vulkan_h264> wivrn::video_encoder_vulkan_h264::create(
|
||||
wivrn_vk_bundle & vk,
|
||||
wivrn::vk_bundle & vk,
|
||||
const encoder_settings & settings,
|
||||
uint8_t stream_idx)
|
||||
{
|
||||
|
||||
@@ -48,7 +48,7 @@ class video_encoder_vulkan_h264 : public video_encoder_vulkan
|
||||
vk::VideoEncodeH264RateControlInfoKHR rate_control_h264;
|
||||
vk::VideoEncodeH264RateControlLayerInfoKHR rate_control_layer_h264;
|
||||
|
||||
video_encoder_vulkan_h264(wivrn_vk_bundle & vk,
|
||||
video_encoder_vulkan_h264(wivrn::vk_bundle & vk,
|
||||
const vk::VideoCapabilitiesKHR & video_caps,
|
||||
const vk::VideoEncodeCapabilitiesKHR & encode_caps,
|
||||
uint8_t stream_idx,
|
||||
@@ -63,7 +63,7 @@ protected:
|
||||
void send_idr_data() override;
|
||||
|
||||
public:
|
||||
static std::unique_ptr<video_encoder_vulkan_h264> create(wivrn_vk_bundle & vk,
|
||||
static std::unique_ptr<video_encoder_vulkan_h264> create(wivrn::vk_bundle & vk,
|
||||
const encoder_settings & settings,
|
||||
uint8_t stream_idx);
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ static uint32_t find_msb(uint32_t v)
|
||||
}
|
||||
|
||||
wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265(
|
||||
wivrn_vk_bundle & vk,
|
||||
wivrn::vk_bundle & vk,
|
||||
const vk::VideoCapabilitiesKHR & video_caps,
|
||||
const vk::VideoEncodeCapabilitiesKHR & encode_caps,
|
||||
uint8_t stream_idx,
|
||||
@@ -269,7 +269,7 @@ static auto get_video_caps(vk::raii::PhysicalDevice & phys_dev, int bit_depth)
|
||||
}
|
||||
|
||||
std::unique_ptr<wivrn::video_encoder_vulkan_h265> wivrn::video_encoder_vulkan_h265::create(
|
||||
wivrn_vk_bundle & vk,
|
||||
wivrn::vk_bundle & vk,
|
||||
const encoder_settings & settings,
|
||||
uint8_t stream_idx)
|
||||
{
|
||||
|
||||
@@ -59,7 +59,7 @@ class video_encoder_vulkan_h265 : public video_encoder_vulkan
|
||||
vk::VideoEncodeH265RateControlInfoKHR rc_h265{};
|
||||
vk::VideoEncodeH265RateControlLayerInfoKHR rc_layer_h265{};
|
||||
|
||||
video_encoder_vulkan_h265(wivrn_vk_bundle & vk,
|
||||
video_encoder_vulkan_h265(wivrn::vk_bundle & vk,
|
||||
const vk::VideoCapabilitiesKHR & video_caps,
|
||||
const vk::VideoEncodeCapabilitiesKHR & encode_caps,
|
||||
uint8_t stream_idx,
|
||||
@@ -74,7 +74,7 @@ protected:
|
||||
void send_idr_data() override;
|
||||
|
||||
public:
|
||||
static std::unique_ptr<video_encoder_vulkan_h265> create(wivrn_vk_bundle & vk,
|
||||
static std::unique_ptr<video_encoder_vulkan_h265> create(wivrn::vk_bundle & vk,
|
||||
const encoder_settings & settings,
|
||||
uint8_t stream_idx);
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@ void video_encoder_x264::InsertInPendingNal(pending_nal && nal)
|
||||
}
|
||||
|
||||
video_encoder_x264::video_encoder_x264(
|
||||
wivrn_vk_bundle & vk,
|
||||
wivrn::vk_bundle & vk,
|
||||
const encoder_settings & settings,
|
||||
uint8_t stream_idx) :
|
||||
video_encoder(stream_idx, settings, std::make_unique<default_idr_handler>(), false)
|
||||
|
||||
@@ -60,7 +60,7 @@ class video_encoder_x264 : public video_encoder
|
||||
std::list<pending_nal> pending_nals;
|
||||
|
||||
public:
|
||||
video_encoder_x264(wivrn_vk_bundle & vk, const encoder_settings & settings, uint8_t stream_idx);
|
||||
video_encoder_x264(wivrn::vk_bundle & vk, const encoder_settings & settings, uint8_t stream_idx);
|
||||
|
||||
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, bool transferred, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override;
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ class ipc_server_cb : public ipc_server_callbacks
|
||||
void client_disconnected(ipc_server *, uint32_t);
|
||||
|
||||
public:
|
||||
using base = void;
|
||||
using base_t = void;
|
||||
ipc_server_cb();
|
||||
};
|
||||
} // namespace wivrn
|
||||
|
||||
@@ -39,7 +39,7 @@ class instance : public xrt_instance
|
||||
ipc_server * server = nullptr;
|
||||
|
||||
public:
|
||||
using base = xrt_instance;
|
||||
using base_t = xrt_instance;
|
||||
instance();
|
||||
void set_ipc_server(ipc_server *);
|
||||
};
|
||||
|
||||
@@ -28,11 +28,11 @@ struct method_trait
|
||||
template <auto Method, typename Result, typename Class, typename... Args>
|
||||
struct method_trait<Method, Result (Class::*)(Args...)>
|
||||
{
|
||||
static Result magic(Class::base * arg, Args... args)
|
||||
static Result magic(Class::base_t * arg, Args... args)
|
||||
{
|
||||
return std::invoke(Method, static_cast<Class *>(arg), args...);
|
||||
}
|
||||
static Result magic2(Args... args, Class::base * arg)
|
||||
static Result magic2(Args... args, Class::base_t * arg)
|
||||
{
|
||||
return std::invoke(Method, static_cast<Class *>(arg), args...);
|
||||
}
|
||||
@@ -48,7 +48,7 @@ namespace wivrn
|
||||
// Example:
|
||||
// class derived: public base_class
|
||||
// {
|
||||
// using base = base_class;
|
||||
// using base_t = base_class;
|
||||
// void foo(int x);
|
||||
// };
|
||||
//
|
||||
|
||||
+272
-136
@@ -16,21 +16,21 @@
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "vk/vk_helpers.h"
|
||||
|
||||
#include "wivrn_vk_bundle.h"
|
||||
|
||||
#include "util/u_debug.h"
|
||||
#include "util/u_logging.h"
|
||||
#include <string>
|
||||
#include "wivrn-server_shaders.h"
|
||||
#include "wivrn_config.h"
|
||||
|
||||
#include <format>
|
||||
#include <ranges>
|
||||
#include <set>
|
||||
|
||||
DEBUG_GET_ONCE_NUM_OPTION(force_gpu_index, "XRT_COMPOSITOR_FORCE_GPU_INDEX", -1)
|
||||
|
||||
namespace
|
||||
{
|
||||
[[maybe_unused]] vk::raii::Queue make_queue(vk::raii::Device & device, vk_bundle_queue * queue)
|
||||
{
|
||||
if (queue == nullptr or queue->queue == VK_NULL_HANDLE)
|
||||
return nullptr;
|
||||
return vk::raii::Queue(device, queue->family_index, queue->index);
|
||||
}
|
||||
|
||||
VkBool32 message_callback(
|
||||
#if VK_HEADER_VERSION >= 304
|
||||
@@ -63,154 +63,257 @@ VkBool32 message_callback(
|
||||
U_LOG(level, "%s", pCallbackData->pMessage);
|
||||
return false;
|
||||
}
|
||||
|
||||
vk::raii::DebugUtilsMessengerEXT register_message_callback(vk::raii::Instance & instance, vk_bundle & vk)
|
||||
struct strless
|
||||
{
|
||||
if (vk.has_EXT_debug_utils)
|
||||
return vk::raii::DebugUtilsMessengerEXT(
|
||||
instance, vk::DebugUtilsMessengerCreateInfoEXT{
|
||||
.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError,
|
||||
.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance,
|
||||
.pfnUserCallback = message_callback,
|
||||
});
|
||||
return nullptr;
|
||||
bool operator()(const char * a, const char * b) const
|
||||
{
|
||||
return strcmp(a, b) < 0;
|
||||
}
|
||||
};
|
||||
|
||||
int device_type_priority(vk::PhysicalDeviceType device_type)
|
||||
{
|
||||
switch (device_type)
|
||||
{
|
||||
case vk::PhysicalDeviceType::eDiscreteGpu:
|
||||
return 4;
|
||||
case vk::PhysicalDeviceType::eIntegratedGpu:
|
||||
return 3;
|
||||
case vk::PhysicalDeviceType::eVirtualGpu:
|
||||
return 2;
|
||||
case vk::PhysicalDeviceType::eCpu:
|
||||
return 1;
|
||||
case vk::PhysicalDeviceType::eOther:
|
||||
return 0;
|
||||
}
|
||||
assert(false);
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint32_t select_queue(const std::vector<vk::QueueFamilyProperties> & queues, vk::QueueFlags flags)
|
||||
{
|
||||
uint32_t res = vk::QueueFamilyIgnored;
|
||||
auto queue_flag_cost = [](vk::QueueFlags flags) {
|
||||
// number of bits set
|
||||
return std::popcount(VkQueueFlags(flags));
|
||||
};
|
||||
for (auto [i, prop]: std::ranges::enumerate_view(queues))
|
||||
{
|
||||
if ((prop.queueFlags & flags) == flags)
|
||||
{
|
||||
if (res == vk::QueueFamilyIgnored or
|
||||
queue_flag_cost(prop.queueFlags) < queue_flag_cost(queues[res].queueFlags))
|
||||
res = i;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
wivrn::wivrn_vk_bundle::wivrn_vk_bundle(vk_bundle & vk, std::span<const char *> requested_instance_extensions, std::span<const char *> requested_device_extensions) :
|
||||
vk(vk),
|
||||
instance(vk_ctx, vk.instance),
|
||||
physical_device(instance, vk.physical_device),
|
||||
device(physical_device, vk.device),
|
||||
allocator({
|
||||
.physicalDevice = vk.physical_device,
|
||||
.device = vk.device,
|
||||
.instance = vk.instance,
|
||||
.vulkanApiVersion = VK_MAKE_VERSION(1, 3, 0), // FIXME: sync with wivrn_session.cpp
|
||||
},
|
||||
vk.has_EXT_debug_utils),
|
||||
queue(device, vk.main_queue->family_index, vk.main_queue->index),
|
||||
queue_family_index(vk.main_queue->family_index),
|
||||
#ifdef VK_KHR_video_encode_queue
|
||||
encode_queue(make_queue(device, vk.encode_queue)),
|
||||
encode_queue_family_index(vk.encode_queue ? vk.encode_queue->family_index : vk::QueueFamilyIgnored),
|
||||
#else
|
||||
wivrn::vk_bundle::vk_bundle() :
|
||||
instance(nullptr),
|
||||
physical_device(nullptr),
|
||||
device(nullptr),
|
||||
queue(nullptr),
|
||||
queue_family_index(vk::QueueFamilyIgnored),
|
||||
encode_queue(nullptr),
|
||||
encode_queue_family_index(vk::QueueFamilyIgnored),
|
||||
#endif
|
||||
debug(register_message_callback(instance, vk))
|
||||
debug(nullptr)
|
||||
{
|
||||
// This is manually synced with monado code
|
||||
|
||||
// Instance extensions
|
||||
#ifdef VK_EXT_display_surface_counter
|
||||
if (vk.has_EXT_display_surface_counter)
|
||||
instance_extensions.push_back(VK_EXT_DISPLAY_SURFACE_COUNTER_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_EXT_swapchain_colorspace
|
||||
if (vk.has_EXT_swapchain_colorspace)
|
||||
instance_extensions.push_back(VK_EXT_SWAPCHAIN_COLORSPACE_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_EXT_debug_utils
|
||||
if (vk.has_EXT_debug_utils)
|
||||
instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
||||
#endif
|
||||
for (auto & ext: vk_ctx.enumerateInstanceExtensionProperties())
|
||||
// Create instance
|
||||
vk::ApplicationInfo app_info{
|
||||
.pApplicationName = "WiVRn server",
|
||||
.pEngineName = "WiVRn",
|
||||
.apiVersion = VK_API_VERSION_1_3,
|
||||
};
|
||||
{
|
||||
for (const char * requested: requested_instance_extensions)
|
||||
// Required extensions
|
||||
instance_extensions = {
|
||||
// promoted to 1.1, but we need the KHR name for Monado
|
||||
VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME,
|
||||
VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME,
|
||||
VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME,
|
||||
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
|
||||
};
|
||||
// Optional extensions
|
||||
std::set<const char *, strless> opt_instance_extensions = {
|
||||
VK_EXT_DEBUG_UTILS_EXTENSION_NAME,
|
||||
};
|
||||
for (auto & ext: vk_ctx.enumerateInstanceExtensionProperties())
|
||||
{
|
||||
if (std::string(requested) == ext.extensionName)
|
||||
{
|
||||
instance_extensions.push_back(requested);
|
||||
break;
|
||||
}
|
||||
if (auto it = opt_instance_extensions.find(ext.extensionName); it != opt_instance_extensions.end())
|
||||
instance_extensions.push_back(*it);
|
||||
}
|
||||
|
||||
instance = vk::raii::Instance(
|
||||
vk_ctx,
|
||||
vk::InstanceCreateInfo{
|
||||
.pApplicationInfo = &app_info,
|
||||
.enabledExtensionCount = uint32_t(instance_extensions.size()),
|
||||
.ppEnabledExtensionNames = instance_extensions.data(),
|
||||
});
|
||||
}
|
||||
|
||||
// Device extensions
|
||||
#ifdef VK_KHR_external_fence_fd
|
||||
if (vk.has_KHR_external_fence_fd)
|
||||
device_extensions.push_back(VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_KHR_external_semaphore_fd
|
||||
if (vk.has_KHR_external_semaphore_fd)
|
||||
device_extensions.push_back(VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_KHR_format_feature_flags2
|
||||
if (vk.has_KHR_format_feature_flags2)
|
||||
device_extensions.push_back(VK_KHR_FORMAT_FEATURE_FLAGS_2_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_KHR_global_priority
|
||||
if (vk.has_KHR_global_priority)
|
||||
device_extensions.push_back(VK_KHR_GLOBAL_PRIORITY_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_KHR_image_format_list
|
||||
if (vk.has_KHR_image_format_list)
|
||||
device_extensions.push_back(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_KHR_maintenance1
|
||||
if (vk.has_KHR_maintenance1)
|
||||
device_extensions.push_back(VK_KHR_MAINTENANCE_1_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_KHR_maintenance2
|
||||
if (vk.has_KHR_maintenance2)
|
||||
device_extensions.push_back(VK_KHR_MAINTENANCE_2_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_KHR_maintenance3
|
||||
if (vk.has_KHR_maintenance3)
|
||||
device_extensions.push_back(VK_KHR_MAINTENANCE_3_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_KHR_maintenance4
|
||||
if (vk.has_KHR_maintenance4)
|
||||
device_extensions.push_back(VK_KHR_MAINTENANCE_4_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_KHR_timeline_semaphore
|
||||
if (vk.has_KHR_timeline_semaphore)
|
||||
device_extensions.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_EXT_calibrated_timestamps
|
||||
if (vk.has_EXT_calibrated_timestamps)
|
||||
device_extensions.push_back(VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_EXT_display_control
|
||||
if (vk.has_EXT_display_control)
|
||||
device_extensions.push_back(VK_EXT_DISPLAY_CONTROL_EXTENSION_NAME);
|
||||
if (has_instance_ext(VK_EXT_DEBUG_UTILS_EXTENSION_NAME))
|
||||
debug = vk::raii::DebugUtilsMessengerEXT(
|
||||
instance,
|
||||
vk::DebugUtilsMessengerCreateInfoEXT{
|
||||
.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError,
|
||||
.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance,
|
||||
.pfnUserCallback = message_callback,
|
||||
});
|
||||
|
||||
// Select physical device
|
||||
|
||||
{
|
||||
auto phys_devices = instance.enumeratePhysicalDevices();
|
||||
if (phys_devices.empty())
|
||||
throw std::runtime_error("No Vulkan device");
|
||||
auto index = debug_get_num_option_force_gpu_index();
|
||||
if (index < 0)
|
||||
{
|
||||
std::vector<vk::PhysicalDeviceType> types;
|
||||
for (const auto & dev: phys_devices)
|
||||
types.push_back(dev.getProperties().deviceType);
|
||||
index = 0;
|
||||
// Select the first device of the highest priority
|
||||
for (auto [i, t]: std::ranges::enumerate_view(types))
|
||||
{
|
||||
if (device_type_priority(t) > device_type_priority(types[index]))
|
||||
index = i;
|
||||
}
|
||||
}
|
||||
else if (index > phys_devices.size())
|
||||
throw std::runtime_error(std::format("Invalid GPU index {}, must be in range 0..{}", index, phys_devices.size() - 1));
|
||||
physical_device = std::move(phys_devices[index]);
|
||||
}
|
||||
|
||||
// Select queue families
|
||||
{
|
||||
auto queues = physical_device.getQueueFamilyProperties();
|
||||
queue_family_index = select_queue(queues, vk::QueueFlagBits::eCompute);
|
||||
#if WIVRN_USE_VULKAN_ENCODE
|
||||
encode_queue_family_index = select_queue(queues, vk::QueueFlagBits::eVideoEncodeKHR);
|
||||
#endif
|
||||
// Technically allowed to have a device with only encode or decode capabilities
|
||||
if (queue_family_index == vk::QueueFamilyIgnored)
|
||||
throw std::runtime_error("GPU does not support vulkan compute");
|
||||
}
|
||||
|
||||
// Create logical device
|
||||
{
|
||||
// Required extensions
|
||||
device_extensions = {
|
||||
VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME,
|
||||
VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME,
|
||||
VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME,
|
||||
VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME,
|
||||
VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,
|
||||
VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME,
|
||||
};
|
||||
// Optional extensions
|
||||
std::set<const char *, strless> opt_device_extensions = {
|
||||
// For Monado
|
||||
VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME,
|
||||
VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME,
|
||||
VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME,
|
||||
VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME,
|
||||
VK_KHR_MAINTENANCE_1_EXTENSION_NAME,
|
||||
VK_KHR_MAINTENANCE_2_EXTENSION_NAME,
|
||||
VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME,
|
||||
VK_EXT_ROBUSTNESS_2_EXTENSION_NAME,
|
||||
VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME,
|
||||
// For FFMPEG
|
||||
#ifdef VK_EXT_external_memory_dma_buf
|
||||
if (vk.has_EXT_external_memory_dma_buf)
|
||||
device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_EXT_global_priority
|
||||
if (vk.has_EXT_global_priority)
|
||||
device_extensions.push_back(VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME);
|
||||
VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_EXT_image_drm_format_modifier
|
||||
if (vk.has_EXT_image_drm_format_modifier)
|
||||
device_extensions.push_back(VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_EXT_robustness2
|
||||
if (vk.has_EXT_robustness2)
|
||||
device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME);
|
||||
#endif
|
||||
#ifdef VK_GOOGLE_display_timing
|
||||
if (vk.has_GOOGLE_display_timing)
|
||||
device_extensions.push_back(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME);
|
||||
VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME,
|
||||
#endif
|
||||
|
||||
for (auto & ext: physical_device.enumerateDeviceExtensionProperties())
|
||||
{
|
||||
for (const char * requested: requested_device_extensions)
|
||||
// For vulkan video encode
|
||||
#ifdef VK_KHR_video_queue
|
||||
VK_KHR_VIDEO_QUEUE_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_KHR_video_encode_queue
|
||||
VK_KHR_VIDEO_ENCODE_QUEUE_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_KHR_video_maintenance1
|
||||
VK_KHR_VIDEO_MAINTENANCE_1_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_KHR_video_encode_h264
|
||||
VK_KHR_VIDEO_ENCODE_H264_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef VK_KHR_video_encode_h265
|
||||
VK_KHR_VIDEO_ENCODE_H265_EXTENSION_NAME,
|
||||
#endif
|
||||
};
|
||||
for (auto & ext: physical_device.enumerateDeviceExtensionProperties())
|
||||
{
|
||||
if (std::string(requested) == ext.extensionName)
|
||||
{
|
||||
device_extensions.push_back(requested);
|
||||
break;
|
||||
}
|
||||
if (auto it = opt_device_extensions.find(ext.extensionName); it != opt_device_extensions.end())
|
||||
device_extensions.push_back(*it);
|
||||
}
|
||||
|
||||
float prio = 1.0;
|
||||
|
||||
std::vector queues_info = {
|
||||
vk::DeviceQueueCreateInfo{
|
||||
.queueFamilyIndex = queue_family_index,
|
||||
.queueCount = 1,
|
||||
.pQueuePriorities = &prio,
|
||||
},
|
||||
};
|
||||
#if WIVRN_USE_VULKAN_ENCODE
|
||||
if (encode_queue_family_index != vk::QueueFamilyIgnored)
|
||||
{
|
||||
queues_info.push_back(
|
||||
vk::DeviceQueueCreateInfo{
|
||||
.queueFamilyIndex = encode_queue_family_index,
|
||||
.queueCount = 1,
|
||||
.pQueuePriorities = &prio,
|
||||
});
|
||||
|
||||
#ifdef VK_KHR_video_maintenance1
|
||||
auto [_, video_feat] = physical_device.getFeatures2<vk::PhysicalDeviceFeatures2, vk::PhysicalDeviceVideoMaintenance1FeaturesKHR>();
|
||||
std::get<vk::PhysicalDeviceVideoMaintenance1FeaturesKHR>(feat).videoMaintenance1 = video_feat.videoMaintenance1;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// Enable features
|
||||
auto [phys_feat, phys_feat12, phys_feat13] = physical_device.getFeatures2<vk::PhysicalDeviceFeatures2, vk::PhysicalDeviceVulkan12Features, vk::PhysicalDeviceVulkan13Features>();
|
||||
|
||||
std::get<vk::PhysicalDeviceVulkan12Features>(feat).descriptorBindingPartiallyBound = phys_feat12.descriptorBindingPartiallyBound;
|
||||
std::get<vk::PhysicalDeviceVulkan12Features>(feat).timelineSemaphore = phys_feat12.timelineSemaphore;
|
||||
std::get<vk::PhysicalDeviceVulkan13Features>(feat).synchronization2 = phys_feat13.synchronization2;
|
||||
|
||||
device = vk::raii::Device(
|
||||
physical_device,
|
||||
vk::DeviceCreateInfo{
|
||||
.pNext = &feat.get(),
|
||||
.queueCreateInfoCount = uint32_t(queues_info.size()),
|
||||
.pQueueCreateInfos = queues_info.data(),
|
||||
.enabledExtensionCount = uint32_t(device_extensions.size()),
|
||||
.ppEnabledExtensionNames = device_extensions.data(),
|
||||
});
|
||||
|
||||
queue = device.getQueue(queue_family_index, 0);
|
||||
#if WIVRN_USE_VULKAN_ENCODE
|
||||
if (encode_queue_family_index != vk::QueueFamilyIgnored)
|
||||
encode_queue = device.getQueue(encode_queue_family_index, 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
allocator.emplace(VmaAllocatorCreateInfo{
|
||||
.physicalDevice = *physical_device,
|
||||
.device = *device,
|
||||
.instance = *instance,
|
||||
.vulkanApiVersion = app_info.apiVersion,
|
||||
},
|
||||
*debug != VK_NULL_HANDLE);
|
||||
}
|
||||
|
||||
uint32_t wivrn::wivrn_vk_bundle::get_memory_type(uint32_t type_bits, vk::MemoryPropertyFlags memory_props)
|
||||
uint32_t wivrn::vk_bundle::get_memory_type(uint32_t type_bits, vk::MemoryPropertyFlags memory_props)
|
||||
{
|
||||
auto mem_prop = physical_device.getMemoryProperties();
|
||||
|
||||
@@ -226,9 +329,42 @@ uint32_t wivrn::wivrn_vk_bundle::get_memory_type(uint32_t type_bits, vk::MemoryP
|
||||
throw std::runtime_error("Failed to get memory type");
|
||||
}
|
||||
|
||||
void wivrn::wivrn_vk_bundle::name(vk::ObjectType type, uint64_t handle, const char * value)
|
||||
bool wivrn::vk_bundle::has_instance_ext(const char * ext) const
|
||||
{
|
||||
if (not vk.has_EXT_debug_utils)
|
||||
for (auto e: instance_extensions)
|
||||
{
|
||||
if (strcmp(e, ext) == 0)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool wivrn::vk_bundle::has_device_ext(const char * ext) const
|
||||
{
|
||||
for (auto e: device_extensions)
|
||||
{
|
||||
if (strcmp(e, ext) == 0)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
vk::raii::ShaderModule wivrn::vk_bundle::load_shader(const char * name)
|
||||
{
|
||||
std::span spirv{::shaders.at(name)};
|
||||
|
||||
return vk::raii::ShaderModule{
|
||||
device,
|
||||
vk::ShaderModuleCreateInfo{
|
||||
.codeSize = spirv.size_bytes(),
|
||||
.pCode = spirv.data(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
void wivrn::vk_bundle::name(vk::ObjectType type, uint64_t handle, const char * value)
|
||||
{
|
||||
if (not has_instance_ext(VK_EXT_DEBUG_UTILS_EXTENSION_NAME))
|
||||
return;
|
||||
device.setDebugUtilsObjectNameEXT(vk::DebugUtilsObjectNameInfoEXT{
|
||||
.objectType = type,
|
||||
|
||||
@@ -21,39 +21,14 @@
|
||||
|
||||
#include "vk/vk_allocator.h"
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <mutex>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
struct vk_bundle;
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
// to use vk::raii we need a vk::raii::{Instance,PhysicalDevice,Device}
|
||||
// however we don't own it, so deactivate the destructor
|
||||
struct raii_instance : public vk::raii::Instance
|
||||
{
|
||||
raii_instance(vk::raii::Context & ctx, VkInstance i) :
|
||||
vk::raii::Instance(ctx, i) {}
|
||||
raii_instance & operator=(raii_instance &&) noexcept = default;
|
||||
~raii_instance()
|
||||
{
|
||||
release();
|
||||
}
|
||||
};
|
||||
struct raii_device : public vk::raii::Device
|
||||
{
|
||||
raii_device(vk::raii::PhysicalDevice & p, VkDevice d) :
|
||||
vk::raii::Device(p, d) {}
|
||||
raii_device & operator=(raii_device &&) noexcept = default;
|
||||
~raii_device()
|
||||
{
|
||||
release();
|
||||
}
|
||||
};
|
||||
|
||||
namespace details
|
||||
{
|
||||
template <typename T, typename U = void>
|
||||
@@ -84,26 +59,38 @@ uint64_t vk_handle(const T & handle)
|
||||
return details::vk_handle<T>{}(handle);
|
||||
}
|
||||
|
||||
struct wivrn_vk_bundle
|
||||
struct vk_bundle
|
||||
{
|
||||
vk_bundle & vk;
|
||||
vk::raii::Context vk_ctx;
|
||||
raii_instance instance;
|
||||
vk::raii::Instance instance;
|
||||
vk::raii::PhysicalDevice physical_device;
|
||||
raii_device device;
|
||||
vk_allocator allocator;
|
||||
vk::raii::Device device;
|
||||
std::optional<vk_allocator> allocator;
|
||||
|
||||
std::mutex queue_mutex;
|
||||
vk::raii::Queue queue;
|
||||
uint32_t queue_family_index;
|
||||
|
||||
std::mutex encode_queue_mutex;
|
||||
vk::raii::Queue encode_queue;
|
||||
uint32_t encode_queue_family_index;
|
||||
|
||||
vk::raii::DebugUtilsMessengerEXT debug;
|
||||
|
||||
vk::StructureChain<
|
||||
vk::PhysicalDeviceFeatures2,
|
||||
vk::PhysicalDeviceVulkan12Features,
|
||||
vk::PhysicalDeviceVulkan13Features,
|
||||
#ifdef VK_KHR_video_maintenance1
|
||||
vk::PhysicalDeviceVideoMaintenance1FeaturesKHR
|
||||
#endif
|
||||
>
|
||||
feat{};
|
||||
|
||||
std::vector<const char *> instance_extensions;
|
||||
std::vector<const char *> device_extensions;
|
||||
|
||||
wivrn_vk_bundle(vk_bundle & vk, std::span<const char *> requested_instance_extensions, std::span<const char *> requested_device_extensions);
|
||||
vk_bundle();
|
||||
|
||||
uint32_t get_memory_type(uint32_t type_bits, vk::MemoryPropertyFlags memory_props);
|
||||
|
||||
@@ -113,6 +100,11 @@ struct wivrn_vk_bundle
|
||||
return name(T::objectType, vk_handle(handle), value);
|
||||
}
|
||||
|
||||
bool has_instance_ext(const char *) const;
|
||||
bool has_device_ext(const char *) const;
|
||||
|
||||
vk::raii::ShaderModule load_shader(const char * name);
|
||||
|
||||
private:
|
||||
void name(vk::ObjectType, uint64_t handle, const char * value);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user