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:
@@ -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
|
||||
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "vk/allocation.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include "xrt/xrt_defines.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
struct render_resources;
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
struct clock_offset;
|
||||
struct vk_bundle;
|
||||
|
||||
class foveation
|
||||
{
|
||||
std::mutex mutex;
|
||||
|
||||
const vk::Extent3D foveated_size; // per eye
|
||||
|
||||
// Natural vertical gaze angle
|
||||
const float angle_offset;
|
||||
// Optionally defined from environment variables
|
||||
const float convergence_distance;
|
||||
|
||||
float eye_x[2] = {}; // eye x position
|
||||
xrt_quat gaze = {};
|
||||
from_headset::override_foveation_center manual_foveation = {};
|
||||
std::array<to_headset::foveation_parameter, 2> params;
|
||||
|
||||
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
|
||||
{
|
||||
xrt_quat gaze = {};
|
||||
bool flip_y = false;
|
||||
xrt_rect src[2] = {};
|
||||
xrt_fov fovs[2] = {};
|
||||
float eye_x[2] = {};
|
||||
|
||||
from_headset::override_foveation_center manual_foveation = {};
|
||||
};
|
||||
P last;
|
||||
|
||||
// must hold lock on mutex to call it
|
||||
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:
|
||||
foveation(wivrn::vk_bundle &,
|
||||
vk::Extent3D foveated_size);
|
||||
|
||||
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> foveate(
|
||||
vk::raii::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);
|
||||
};
|
||||
} // 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
|
||||
@@ -0,0 +1,205 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2024 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 "pacer.h"
|
||||
#include "driver/clock_offset.h"
|
||||
#include "os/os_time.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
static const int64_t margin_ns = 3'000'000;
|
||||
static const int64_t slop_ns = 500'000;
|
||||
|
||||
template <typename T>
|
||||
static T lerp_mod(T a, T b, double t, T mod)
|
||||
{
|
||||
if (2 * std::abs(a - b) < mod)
|
||||
return std::lerp(a, b, t);
|
||||
if (a < b)
|
||||
a += mod;
|
||||
else
|
||||
b += mod;
|
||||
return T(std::lerp(a, b, t)) % mod;
|
||||
}
|
||||
|
||||
pacer::pacer(uint64_t frame_duration) :
|
||||
frame_duration_ns(frame_duration),
|
||||
frame_times(5000),
|
||||
frame_times_compute(frame_times),
|
||||
worker([this](std::stop_token t) {
|
||||
std::vector<XrDuration> samples;
|
||||
while (not t.stop_requested())
|
||||
{
|
||||
samples.clear();
|
||||
{
|
||||
std::unique_lock lock(compute_mutex);
|
||||
compute_cv.wait(lock);
|
||||
for (const auto & time: frame_times_compute)
|
||||
{
|
||||
if (time.decoded > time.present)
|
||||
samples.push_back(time.decoded - time.present);
|
||||
}
|
||||
}
|
||||
if (samples.empty())
|
||||
continue;
|
||||
auto it = samples.begin() + (samples.size() * 995) / 1000;
|
||||
std::ranges::nth_element(samples, it);
|
||||
|
||||
std::unique_lock lock(mutex);
|
||||
safe_present_to_decoded_ns = *it + 1'000'000;
|
||||
}
|
||||
})
|
||||
{}
|
||||
|
||||
pacer::~pacer()
|
||||
{
|
||||
worker.request_stop();
|
||||
compute_cv.notify_all();
|
||||
}
|
||||
|
||||
uint64_t pacer::get_frame_duration() const
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
return 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 pacer::predict(
|
||||
int64_t & 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)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
frame_id = this->frame_id++;
|
||||
auto now = os_monotonic_get_ns();
|
||||
|
||||
int64_t predicted_client_render = last_ns + frame_duration_ns;
|
||||
// snap to phase
|
||||
predicted_client_render = (predicted_client_render / frame_duration_ns) * frame_duration_ns + client_render_phase_ns;
|
||||
|
||||
if (now + mean_wake_up_to_present_ns + safe_present_to_decoded_ns > predicted_client_render)
|
||||
predicted_client_render += frame_duration_ns * ((now + mean_wake_up_to_present_ns + safe_present_to_decoded_ns - predicted_client_render) / frame_duration_ns);
|
||||
|
||||
out_predicted_display_time_ns = predicted_client_render + mean_render_to_display_ns;
|
||||
out_desired_present_time_ns = predicted_client_render - safe_present_to_decoded_ns;
|
||||
out_wake_up_time_ns = out_desired_present_time_ns - mean_wake_up_to_present_ns + margin_ns; // we should be awoken early by the application
|
||||
last_wake_up_ns = out_wake_up_time_ns;
|
||||
|
||||
last_ns = predicted_client_render;
|
||||
|
||||
in_flight_frames[frame_id % in_flight_frames.size()] = {
|
||||
.frame_id = frame_id,
|
||||
.present_ns = out_desired_present_time_ns,
|
||||
.predicted_display_time = out_predicted_display_time_ns,
|
||||
};
|
||||
|
||||
out_present_slop_ns = slop_ns;
|
||||
}
|
||||
|
||||
void pacer::on_feedback(const wivrn::from_headset::feedback & feedback, const clock_offset & offset)
|
||||
{
|
||||
if (feedback.times_displayed > 1 or not feedback.blitted)
|
||||
return;
|
||||
|
||||
std::lock_guard lock(mutex);
|
||||
auto & when = in_flight_frames[feedback.frame_index % in_flight_frames.size()];
|
||||
if (when.frame_id != feedback.frame_index)
|
||||
return;
|
||||
|
||||
auto & times = frame_times[feedback.frame_index % frame_times.size()];
|
||||
if (times.frame_id != feedback.frame_index)
|
||||
{
|
||||
times.frame_id = feedback.frame_index;
|
||||
times.present = when.present_ns;
|
||||
times.decoded = 0;
|
||||
}
|
||||
times.decoded = std::max(times.decoded, offset.from_headset(feedback.received_from_decoder));
|
||||
|
||||
if (feedback.stream_index == 0)
|
||||
{
|
||||
if (feedback.frame_index % 100 == 0)
|
||||
{
|
||||
std::unique_lock lock(compute_mutex);
|
||||
std::swap(frame_times, frame_times_compute);
|
||||
compute_cv.notify_all();
|
||||
}
|
||||
|
||||
client_render_phase_ns = lerp_mod<int64_t>(client_render_phase_ns, offset.from_headset(feedback.blitted) % frame_duration_ns, 0.1, frame_duration_ns);
|
||||
}
|
||||
|
||||
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 pacer::mark_timing_point(
|
||||
comp_target_timing_point point,
|
||||
int64_t frame_id,
|
||||
int64_t when_ns)
|
||||
{
|
||||
switch (point)
|
||||
{
|
||||
//! Woke up after sleeping in wait frame.
|
||||
case COMP_TARGET_TIMING_POINT_WAKE_UP:
|
||||
return;
|
||||
|
||||
//! Began CPU side work for GPU.
|
||||
case COMP_TARGET_TIMING_POINT_BEGIN:
|
||||
return;
|
||||
|
||||
//! Just before submitting work to the GPU.
|
||||
case COMP_TARGET_TIMING_POINT_SUBMIT_BEGIN:
|
||||
return;
|
||||
|
||||
//! Just after submitting work to the GPU.
|
||||
case COMP_TARGET_TIMING_POINT_SUBMIT_END:
|
||||
if (when_ns > last_wake_up_ns and when_ns < last_wake_up_ns + 100'000'000)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
mean_wake_up_to_present_ns = std::lerp(mean_wake_up_to_present_ns, when_ns - last_wake_up_ns, 0.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pacer::frame_info pacer::present_to_info(int64_t present)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
for (const auto & info: in_flight_frames)
|
||||
{
|
||||
if (info.present_ns == present)
|
||||
return info;
|
||||
}
|
||||
assert(false);
|
||||
return {};
|
||||
}
|
||||
|
||||
void pacer::reset()
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
std::ranges::fill(frame_times, frame_time{});
|
||||
}
|
||||
} // namespace wivrn
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2024 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 "wivrn_packets.h"
|
||||
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <main/comp_target.h>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace wivrn
|
||||
{
|
||||
|
||||
struct clock_offset;
|
||||
|
||||
class pacer
|
||||
{
|
||||
public:
|
||||
struct frame_info
|
||||
{
|
||||
int64_t frame_id;
|
||||
int64_t present_ns;
|
||||
int64_t predicted_display_time;
|
||||
};
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex;
|
||||
uint64_t frame_duration_ns;
|
||||
int64_t last_ns = 0;
|
||||
int64_t frame_id = 0;
|
||||
|
||||
int64_t client_render_phase_ns = 0;
|
||||
|
||||
int64_t mean_wake_up_to_present_ns = 1'000'000;
|
||||
int64_t safe_present_to_decoded_ns = 0;
|
||||
int64_t mean_render_to_display_ns = 0;
|
||||
|
||||
int64_t last_wake_up_ns = 0;
|
||||
|
||||
struct frame_time
|
||||
{
|
||||
int64_t frame_id = -1;
|
||||
XrTime present = 0;
|
||||
XrTime decoded = 0;
|
||||
};
|
||||
std::vector<frame_time> frame_times;
|
||||
|
||||
std::mutex compute_mutex;
|
||||
std::condition_variable compute_cv;
|
||||
std::vector<frame_time> frame_times_compute;
|
||||
std::jthread worker;
|
||||
|
||||
std::array<frame_info, 8> in_flight_frames;
|
||||
|
||||
public:
|
||||
pacer(uint64_t frame_duration);
|
||||
~pacer();
|
||||
|
||||
uint64_t get_frame_duration() const;
|
||||
void set_frame_duration(uint64_t frame_duration);
|
||||
|
||||
void predict(
|
||||
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 on_feedback(const wivrn::from_headset::feedback &, const clock_offset &);
|
||||
|
||||
void mark_timing_point(
|
||||
comp_target_timing_point point,
|
||||
int64_t frame_id,
|
||||
int64_t when_ns);
|
||||
|
||||
frame_info present_to_info(int64_t present);
|
||||
|
||||
void reset();
|
||||
};
|
||||
} // namespace wivrn
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user