Add server source, originally in monado
This commit is contained in:
+14
-1
@@ -10,14 +10,27 @@ endif()
|
||||
include(FetchContent)
|
||||
include(ExternalProject)
|
||||
|
||||
|
||||
option(WIVRN_USE_SYSTEM_FREETYPE "Use system FreeType" ON)
|
||||
option(WIVRN_USE_ANDROID_VALIDATION_LAYER "Download the android version of the Vulkan validation layer" OFF)
|
||||
option(WIVRN_BUILD_CLIENT "Build WiVRn client" ON)
|
||||
option(WIVRN_BUILD_SERVER "Build WiVRn server" ON)
|
||||
|
||||
find_package(PkgConfig REQUIRED)
|
||||
find_package(Vulkan REQUIRED)
|
||||
|
||||
if (WIVRN_BUILD_SERVER)
|
||||
find_package(CUDAToolkit)
|
||||
pkg_check_modules(LIBAV IMPORTED_TARGET libavcodec libavutil libswscale libavfilter)
|
||||
pkg_check_modules(X264 IMPORTED_TARGET x264)
|
||||
|
||||
if (NOT CUDAToolkit_FOUND AND NOT LIBAV_FOUND AND NOT X264_FOUND)
|
||||
message(FATAL_ERROR "No encoder found")
|
||||
endif()
|
||||
|
||||
pkg_check_modules(AVAHI IMPORTED_TARGET avahi-client)
|
||||
find_package(Eigen3 REQUIRED)
|
||||
endif()
|
||||
|
||||
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
|
||||
|
||||
if(ANDROID)
|
||||
|
||||
@@ -7,11 +7,10 @@ set(TINYGLTF_HEADER_ONLY OFF)
|
||||
set(TINYGLTF_INSTALL OFF)
|
||||
|
||||
FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/refs/tags/v1.11.0.tar.gz)
|
||||
FetchContent_Declare(boostpfr URL https://github.com/boostorg/pfr/archive/refs/tags/2.0.3.tar.gz)
|
||||
FetchContent_Declare(glm URL https://github.com/g-truc/glm/archive/refs/tags/0.9.9.8.tar.gz)
|
||||
FetchContent_Declare(tinygltf URL https://github.com/syoyo/tinygltf/archive/refs/tags/v2.6.3.tar.gz)
|
||||
|
||||
FetchContent_MakeAvailable(spdlog boostpfr glm tinygltf)
|
||||
FetchContent_MakeAvailable(spdlog glm tinygltf)
|
||||
|
||||
include(FreetypeHarfbuzz)
|
||||
include(CompileGLSL)
|
||||
@@ -65,8 +64,6 @@ else()
|
||||
target_compile_definitions(wivrn PRIVATE -DXR_USE_PLATFORM_XLIB)
|
||||
|
||||
find_package(OpenXR REQUIRED)
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET libavcodec libavutil libswscale)
|
||||
target_link_libraries(wivrn OpenXR::openxr_loader OpenXR::headers PkgConfig::LIBAV)
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
|
||||
function(compile_glsl_aux shader_stage glsl_filename output)
|
||||
|
||||
cmake_path(GET glsl_filename STEM shader_name)
|
||||
function(compile_glsl_aux shader_stage shader_name glsl_filename output)
|
||||
|
||||
string(TOUPPER ${shader_stage} shader_stage_upper)
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${output}
|
||||
COMMAND echo "{ \"${shader_name}.${shader_stage}\", {" >> ${output}
|
||||
COMMAND echo "{ \"${shader_name}\", {" >> ${output}
|
||||
COMMAND Vulkan::glslc -mfmt=num -fshader-stage=${shader_stage} -D${shader_stage_upper}_SHADER ${in_file} -o - >> ${output}
|
||||
COMMAND echo "}}," >> ${output}
|
||||
DEPENDS ${glsl_filename}
|
||||
@@ -33,10 +31,12 @@ function(compile_glsl target_name)
|
||||
foreach(in_file IN LISTS ARGN)
|
||||
if (in_file MATCHES "\.\(vert|frag|tesc|tese|geom|comp\)\.glsl$")
|
||||
set(shader_stage ${CMAKE_MATCH_1})
|
||||
compile_glsl_aux(${shader_stage} ${in_file} ${target_name}_shaders.cpp)
|
||||
cmake_path(GET in_file STEM LAST_ONLY shader_name)
|
||||
compile_glsl_aux(${shader_stage} ${shader_name} ${in_file} ${target_name}_shaders.cpp)
|
||||
else()
|
||||
compile_glsl_aux(vert ${in_file} ${target_name}_shaders.cpp)
|
||||
compile_glsl_aux(frag ${in_file} ${target_name}_shaders.cpp)
|
||||
cmake_path(GET in_file STEM LAST_ONLY shader_name)
|
||||
compile_glsl_aux(vert ${shader_name}.vert ${in_file} ${target_name}_shaders.cpp)
|
||||
compile_glsl_aux(frag ${shader_name}.frag ${in_file} ${target_name}_shaders.cpp)
|
||||
endif()
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
|
||||
FetchContent_Declare(boostpfr URL https://github.com/boostorg/pfr/archive/refs/tags/2.0.3.tar.gz)
|
||||
|
||||
FetchContent_MakeAvailable(boostpfr)
|
||||
|
||||
execute_process(COMMAND git describe --always OUTPUT_VARIABLE GIT_VERSION)
|
||||
string(STRIP ${GIT_VERSION} GIT_VERSION)
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
|
||||
set(XRT_BUILD_DRIVER_ARDUINO OFF)
|
||||
set(XRT_BUILD_DRIVER_DAYDREAM OFF)
|
||||
set(XRT_BUILD_DRIVER_EUROC OFF)
|
||||
set(XRT_BUILD_DRIVER_HDK OFF)
|
||||
set(XRT_BUILD_DRIVER_HYDRA OFF)
|
||||
set(XRT_BUILD_DRIVER_NS OFF)
|
||||
set(XRT_BUILD_DRIVER_OHMD OFF)
|
||||
set(XRT_BUILD_DRIVER_OPENGLOVES OFF)
|
||||
set(XRT_BUILD_DRIVER_PSMV OFF)
|
||||
set(XRT_BUILD_DRIVER_PSVR OFF)
|
||||
set(XRT_BUILD_DRIVER_QWERTY OFF)
|
||||
set(XRT_BUILD_DRIVER_REMOTE OFF)
|
||||
set(XRT_BUILD_DRIVER_RIFT_S OFF)
|
||||
set(XRT_BUILD_DRIVER_SIMULATED ON)
|
||||
set(XRT_BUILD_DRIVER_TWRAP OFF)
|
||||
set(XRT_BUILD_DRIVER_VF OFF)
|
||||
set(XRT_BUILD_DRIVER_VIVE OFF)
|
||||
set(XRT_BUILD_DRIVER_WMR OFF)
|
||||
set(XRT_BUILD_SAMPLES OFF)
|
||||
|
||||
set(XRT_FEATURE_COMPOSITOR_NULL OFF)
|
||||
set(XRT_FEATURE_SERVICE ON)
|
||||
set(XRT_FEATURE_SERVICE_SYSTEMD OFF)
|
||||
set(XRT_FEATURE_SLAM OFF)
|
||||
set(XRT_FEATURE_STEAMVR_PLUGIN OFF)
|
||||
set(XRT_FEATURE_WINDOW_PEEK OFF)
|
||||
set(XRT_FEATURE_STEAMVR_PLUGIN OFF)
|
||||
set(XRT_FEATURE_WINDOW_PEEK OFF)
|
||||
set(XRT_FEATURE_WINDOW_PEEK OFF)
|
||||
|
||||
set(XRT_HAVE_SDL2 OFF)
|
||||
|
||||
set(BUILD_DOC OFF)
|
||||
set(BUILD_TESTING OFF)
|
||||
|
||||
set(XRT_IPC_MSG_SOCK_FILENAME "wivrn_comp_ipc")
|
||||
|
||||
FetchContent_Declare(monado
|
||||
GIT_REPOSITORY https://gitlab.freedesktop.org/xytovl/monado
|
||||
GIT_TAG 9044e870696f39ace2293488ad5e663f366031a6
|
||||
)
|
||||
|
||||
FetchContent_MakeAvailable(monado)
|
||||
FetchContent_GetProperties(monado)
|
||||
|
||||
|
||||
add_executable(monado-wivrn
|
||||
main.cpp
|
||||
target_instance_wivrn.cpp
|
||||
hostname.cpp
|
||||
avahi_publisher.cpp
|
||||
|
||||
|
||||
driver/encoder_settings.cpp
|
||||
driver/wivrn_hmd.cpp
|
||||
driver/wivrn_comp_target.cpp
|
||||
driver/wivrn_controller.cpp
|
||||
driver/pose_list.cpp
|
||||
driver/video_encoder.cpp
|
||||
driver/view_list.cpp
|
||||
driver/wivrn_session.cpp
|
||||
driver/wivrn_connection.cpp
|
||||
driver/wivrn_sockets.cpp
|
||||
driver/xrt_cast.cpp
|
||||
driver/external/rs.c
|
||||
${WIVRN_SHADER_HEADERS}
|
||||
driver/yuv_converter.cpp
|
||||
)
|
||||
|
||||
target_include_directories(monado-wivrn SYSTEM PRIVATE ${monado_SOURCE_DIR}/src/xrt/compositor/)
|
||||
|
||||
if(CUDAToolkit_FOUND)
|
||||
target_sources(monado-wivrn PRIVATE driver/video_encoder_nvenc.cpp)
|
||||
target_link_libraries(monado-wivrn PRIVATE CUDA::cuda_driver nvidia-encode)
|
||||
endif()
|
||||
|
||||
if(LIBAV_FOUND)
|
||||
target_sources(
|
||||
monado-wivrn
|
||||
PRIVATE driver/ffmpeg/VideoEncoderFFMPEG.cpp driver/ffmpeg/VideoEncoderVA.cpp
|
||||
driver/ffmpeg/ffmpeg_helper.cpp
|
||||
)
|
||||
target_link_libraries(monado-wivrn PRIVATE PkgConfig::LIBAV)
|
||||
endif()
|
||||
|
||||
if(X264_FOUND)
|
||||
target_sources(monado-wivrn PRIVATE driver/video_encoder_x264.cpp)
|
||||
target_link_libraries(monado-wivrn PRIVATE PkgConfig::X264)
|
||||
endif()
|
||||
|
||||
|
||||
include(CompileGLSL)
|
||||
|
||||
file(GLOB VULKAN_SHADERS CONFIGURE_DEPENDS "driver/shaders/*.glsl")
|
||||
target_sources(monado-wivrn PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS})
|
||||
compile_glsl(monado-wivrn ${VULKAN_SHADERS})
|
||||
|
||||
target_link_libraries(
|
||||
monado-wivrn
|
||||
PRIVATE
|
||||
aux_os
|
||||
aux_util
|
||||
aux_vk
|
||||
comp_main
|
||||
ipc_server
|
||||
xrt-external-openxr
|
||||
xrt-interfaces
|
||||
|
||||
systemd
|
||||
Boost::pfr
|
||||
PkgConfig::AVAHI
|
||||
Eigen3::Eigen
|
||||
)
|
||||
@@ -0,0 +1,138 @@
|
||||
#include "avahi_publisher.h"
|
||||
|
||||
#include <avahi-common/simple-watch.h>
|
||||
#include <avahi-client/client.h>
|
||||
#include <avahi-common/error.h>
|
||||
#include <avahi-common/alternative.h>
|
||||
#include <avahi-common/malloc.h>
|
||||
#include <avahi-client/publish.h>
|
||||
#include <iostream>
|
||||
#include <string.h>
|
||||
|
||||
void
|
||||
avahi_publisher::alt_name()
|
||||
{
|
||||
char *new_name = avahi_alternative_service_name(name);
|
||||
avahi_free(name);
|
||||
name = new_name;
|
||||
}
|
||||
|
||||
void
|
||||
avahi_publisher::create_service(AvahiClient *client)
|
||||
{
|
||||
if (!entry_group) {
|
||||
entry_group = avahi_entry_group_new(client, avahi_entry_group_callback, nullptr);
|
||||
}
|
||||
avahi_entry_group_reset(entry_group);
|
||||
|
||||
if (!name)
|
||||
name = avahi_strdup("WiVRn");
|
||||
|
||||
int ret;
|
||||
do {
|
||||
ret = avahi_entry_group_add_service(entry_group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC,
|
||||
(AvahiPublishFlags)0, name, type.c_str(), nullptr, nullptr, port,
|
||||
nullptr);
|
||||
if (ret == AVAHI_ERR_COLLISION) {
|
||||
alt_name();
|
||||
}
|
||||
} while (ret == AVAHI_ERR_COLLISION);
|
||||
|
||||
if (ret < 0) {
|
||||
std::cerr << "Cannot add service: " << avahi_strerror(ret) << std::endl;
|
||||
}
|
||||
|
||||
ret = avahi_entry_group_commit(entry_group);
|
||||
if (ret < 0) {
|
||||
std::cerr << "Cannot commit entry group: " << avahi_strerror(ret) << std::endl;
|
||||
} else {
|
||||
std::cout << "Service published: " << name << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
avahi_publisher::avahi_entry_group_callback(
|
||||
AvahiEntryGroup *g,
|
||||
AvahiEntryGroupState state /**< The new state of the entry group */,
|
||||
void *userdata /* The arbitrary user data pointer originally passed to avahi_entry_group_new()*/)
|
||||
{
|
||||
avahi_publisher *self = (avahi_publisher *)userdata;
|
||||
|
||||
switch (state) {
|
||||
case AVAHI_ENTRY_GROUP_ESTABLISHED:
|
||||
case AVAHI_ENTRY_GROUP_FAILURE:
|
||||
case AVAHI_ENTRY_GROUP_REGISTERING:
|
||||
case AVAHI_ENTRY_GROUP_UNCOMMITED: break;
|
||||
case AVAHI_ENTRY_GROUP_COLLISION:
|
||||
self->alt_name();
|
||||
self->create_service(avahi_entry_group_get_client(g));
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
avahi_publisher::client_callback(AvahiClient *s,
|
||||
AvahiClientState state /**< The new state of the client */,
|
||||
void *userdata /**< The user data that was passed to avahi_client_new() */)
|
||||
{
|
||||
avahi_publisher *self = (avahi_publisher *)userdata;
|
||||
switch (state) {
|
||||
case AVAHI_CLIENT_CONNECTING:
|
||||
case AVAHI_CLIENT_FAILURE: break;
|
||||
|
||||
case AVAHI_CLIENT_S_COLLISION:
|
||||
case AVAHI_CLIENT_S_REGISTERING: avahi_entry_group_reset(self->entry_group); break;
|
||||
|
||||
case AVAHI_CLIENT_S_RUNNING: self->create_service(s); break;
|
||||
}
|
||||
}
|
||||
|
||||
avahi_publisher::avahi_publisher(const char *name, std::string type, int port)
|
||||
: name(avahi_strdup(name)), type(std::move(type)), port(port)
|
||||
{
|
||||
avahi_poll = avahi_simple_poll_new();
|
||||
|
||||
int error;
|
||||
avahi_client =
|
||||
avahi_client_new(avahi_simple_poll_get(avahi_poll), (AvahiClientFlags)0, &client_callback, this, &error);
|
||||
|
||||
if (!avahi_client)
|
||||
throw std::runtime_error(std::string("Cannot create avahi client: ") + avahi_strerror(error));
|
||||
}
|
||||
|
||||
avahi_publisher::~avahi_publisher()
|
||||
{
|
||||
avahi_free(name);
|
||||
avahi_client_free(avahi_client);
|
||||
avahi_simple_poll_free(avahi_poll);
|
||||
}
|
||||
|
||||
AvahiWatch *
|
||||
avahi_publisher::watch_new(int fd,
|
||||
AvahiWatchEvent event,
|
||||
void (*callback)(AvahiWatch *w, int fd, AvahiWatchEvent event, void *userdata),
|
||||
void *userdata)
|
||||
{
|
||||
AvahiWatch *watch = avahi_simple_poll_get(avahi_poll)
|
||||
->watch_new(avahi_simple_poll_get(avahi_poll), fd, event, callback, userdata);
|
||||
|
||||
return watch;
|
||||
}
|
||||
|
||||
void
|
||||
avahi_publisher::watch_free(AvahiWatch *watch)
|
||||
{
|
||||
avahi_simple_poll_get(avahi_poll)->watch_free(watch);
|
||||
}
|
||||
|
||||
bool
|
||||
avahi_publisher::iterate(int sleep_time)
|
||||
{
|
||||
int r = avahi_simple_poll_iterate(avahi_poll, sleep_time);
|
||||
|
||||
if (r < 0 && errno != EINTR)
|
||||
throw std::runtime_error(std::string("avahi_simple_poll_iterate: ") + strerror(errno));
|
||||
|
||||
return r == 0;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
|
||||
#include <avahi-common/watch.h>
|
||||
#include <avahi-client/publish.h>
|
||||
#include <avahi-common/simple-watch.h>
|
||||
#include <string>
|
||||
|
||||
class avahi_publisher
|
||||
{
|
||||
AvahiEntryGroup *entry_group{};
|
||||
char *name{};
|
||||
std::string type;
|
||||
int port;
|
||||
|
||||
AvahiSimplePoll *avahi_poll{};
|
||||
AvahiClient *avahi_client{};
|
||||
|
||||
void
|
||||
alt_name();
|
||||
|
||||
void
|
||||
create_service(AvahiClient *client);
|
||||
|
||||
static void
|
||||
avahi_entry_group_callback(
|
||||
AvahiEntryGroup *g,
|
||||
AvahiEntryGroupState state /**< The new state of the entry group */,
|
||||
void *userdata /* The arbitrary user data pointer originally passed to avahi_entry_group_new()*/);
|
||||
|
||||
static void
|
||||
client_callback(AvahiClient *s,
|
||||
AvahiClientState state /**< The new state of the client */,
|
||||
void *userdata /**< The user data that was passed to avahi_client_new() */);
|
||||
|
||||
public:
|
||||
avahi_publisher(const char *name, std::string type, int port);
|
||||
|
||||
~avahi_publisher();
|
||||
|
||||
AvahiWatch *
|
||||
watch_new(int fd,
|
||||
AvahiWatchEvent event,
|
||||
void (*callback)(AvahiWatch *w, int fd, AvahiWatchEvent event, void *userdata),
|
||||
void *userdata);
|
||||
|
||||
void
|
||||
watch_free(AvahiWatch *watch);
|
||||
|
||||
bool
|
||||
iterate(int sleep_time = -1);
|
||||
};
|
||||
@@ -0,0 +1,184 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "encoder_settings.h"
|
||||
#include "util/u_config_json.h"
|
||||
#include "video_encoder.h"
|
||||
#include "vk/vk_helpers.h"
|
||||
|
||||
#include <string>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#ifdef XRT_HAVE_FFMPEG
|
||||
#include "ffmpeg/VideoEncoderVA.h"
|
||||
#endif
|
||||
|
||||
using namespace xrt::drivers::wivrn;
|
||||
|
||||
// TODO: size independent bitrate
|
||||
static const uint64_t default_bitrate = 10'000'000;
|
||||
|
||||
static bool
|
||||
is_nvidia(vk_bundle *vk)
|
||||
{
|
||||
VkPhysicalDeviceProperties physical_device_properties;
|
||||
vk->vkGetPhysicalDeviceProperties(vk->physical_device, &physical_device_properties);
|
||||
return physical_device_properties.vendorID == 0x10DE;
|
||||
}
|
||||
|
||||
static std::vector<xrt::drivers::wivrn::encoder_settings>
|
||||
get_encoder_default_settings(vk_bundle *vk, uint16_t width, uint16_t height)
|
||||
{
|
||||
xrt::drivers::wivrn::encoder_settings settings{};
|
||||
settings.width = width;
|
||||
settings.height = height;
|
||||
settings.codec = xrt::drivers::wivrn::h265;
|
||||
settings.bitrate = default_bitrate;
|
||||
|
||||
if (is_nvidia(vk)) {
|
||||
#ifdef XRT_HAVE_CUDA
|
||||
settings.encoder_name = encoder_nvenc;
|
||||
#elif defined(XRT_HAVE_X264)
|
||||
settings.encoder_name = encoder_x264;
|
||||
settings.codec = xrt::drivers::wivrn::h264;
|
||||
U_LOG_W("nvidia GPU detected, but cuda support not compiled");
|
||||
#else
|
||||
U_LOG_E("no suitable encoder available (compile with x264 or cuda support)");
|
||||
return {};
|
||||
#endif
|
||||
} else {
|
||||
#ifdef XRT_HAVE_FFMPEG
|
||||
settings.encoder_name = encoder_vaapi;
|
||||
#elif defined(XRT_HAVE_X264)
|
||||
settings.encoder_name = encoder_x264;
|
||||
settings.codec = xrt::drivers::wivrn::h264;
|
||||
U_LOG_W("ffmpeg support not compiled, vaapi encoder not available");
|
||||
#else
|
||||
U_LOG_E("no suitable encoder available (compile with x264 or ffmpeg support)");
|
||||
return {};
|
||||
#endif
|
||||
}
|
||||
|
||||
return {settings};
|
||||
}
|
||||
|
||||
std::vector<encoder_settings>
|
||||
xrt::drivers::wivrn::get_encoder_settings(vk_bundle *vk, uint16_t width, uint16_t height)
|
||||
{
|
||||
u_config_json config_json{};
|
||||
std::unique_ptr<u_config_json, void (*)(u_config_json *)> raii(&config_json, u_config_json_close);
|
||||
|
||||
u_config_json_open_or_create_main_file(&config_json);
|
||||
if (!config_json.file_loaded) {
|
||||
U_LOG_D("no config file, using default");
|
||||
return get_encoder_default_settings(vk, width, height);
|
||||
}
|
||||
|
||||
const cJSON *config_wivrn = u_json_get(config_json.root, "config_wivrn");
|
||||
if (config_wivrn == NULL) {
|
||||
U_LOG_D("no config_wivrn entry, using default");
|
||||
return get_encoder_default_settings(vk, width, height);
|
||||
}
|
||||
|
||||
const cJSON *config_encoder = u_json_get(config_wivrn, "encoders");
|
||||
if (config_encoder == NULL) {
|
||||
U_LOG_D("no config_wivrn.encoders entry, using default");
|
||||
return get_encoder_default_settings(vk, width, height);
|
||||
}
|
||||
std::vector<xrt::drivers::wivrn::encoder_settings> res;
|
||||
int num_encoders = cJSON_GetArraySize(config_encoder);
|
||||
|
||||
int next_group = 0;
|
||||
|
||||
for (int i = 0; i < num_encoders; ++i) {
|
||||
cJSON *encoder = cJSON_GetArrayItem(config_encoder, i);
|
||||
xrt::drivers::wivrn::encoder_settings settings{};
|
||||
|
||||
auto name = u_json_get(encoder, "encoder");
|
||||
if (name && cJSON_IsString(name))
|
||||
settings.encoder_name = name->valuestring;
|
||||
else {
|
||||
U_LOG_E("missing \"encoder\" key in config_wivrn");
|
||||
continue;
|
||||
}
|
||||
|
||||
settings.width = width;
|
||||
settings.height = height;
|
||||
settings.bitrate = default_bitrate;
|
||||
settings.codec = xrt::drivers::wivrn::h264;
|
||||
settings.group = next_group;
|
||||
|
||||
auto js_width = u_json_get(encoder, "width");
|
||||
if (js_width && cJSON_IsNumber(js_width))
|
||||
settings.width = std::ceil(js_width->valuedouble * width);
|
||||
|
||||
auto js_height = u_json_get(encoder, "height");
|
||||
if (js_height && cJSON_IsNumber(js_height))
|
||||
settings.height = std::ceil(js_height->valuedouble * height);
|
||||
|
||||
auto offset_x = u_json_get(encoder, "offset_x");
|
||||
if (offset_x && cJSON_IsNumber(offset_x))
|
||||
settings.offset_x = std::floor(offset_x->valuedouble * width);
|
||||
auto offset_y = u_json_get(encoder, "offset_y");
|
||||
if (offset_y && cJSON_IsNumber(offset_y))
|
||||
settings.offset_y = std::floor(offset_y->valuedouble * height);
|
||||
|
||||
auto bitrate = u_json_get(encoder, "bitrate");
|
||||
if (bitrate && cJSON_IsNumber(bitrate))
|
||||
settings.bitrate = bitrate->valueint;
|
||||
|
||||
auto group = u_json_get(encoder, "group");
|
||||
if (group && cJSON_IsNumber(group))
|
||||
settings.group = group->valueint;
|
||||
|
||||
auto codec = u_json_get(encoder, "codec");
|
||||
if (codec && cJSON_IsString(codec)) {
|
||||
if (codec->valuestring == std::string("h264"))
|
||||
settings.codec = xrt::drivers::wivrn::h264;
|
||||
else if (codec->valuestring == std::string("h265"))
|
||||
settings.codec = xrt::drivers::wivrn::h265;
|
||||
else {
|
||||
U_LOG_E("invalid video codec %s", codec->valuestring);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
auto options = u_json_get(encoder, "options");
|
||||
if (options && cJSON_IsObject(options)) {
|
||||
for (auto child = options->child; child; child = child->next) {
|
||||
if (cJSON_IsString(child)) {
|
||||
settings.options[child->string] = child->valuestring;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
next_group = std::max(next_group, settings.group + 1);
|
||||
|
||||
res.push_back(settings);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
VkImageTiling
|
||||
xrt::drivers::wivrn::get_required_tiling(vk_bundle *vk,
|
||||
const std::vector<xrt::drivers::wivrn::encoder_settings> &settings)
|
||||
{
|
||||
|
||||
bool can_optimal = true;
|
||||
bool can_drm = vk->has_EXT_image_drm_format_modifier;
|
||||
for (const auto &item : settings) {
|
||||
#ifdef XRT_HAVE_FFMPEG
|
||||
if (item.encoder_name == encoder_vaapi) {
|
||||
can_optimal = false;
|
||||
if (not use_drm_format_modifiers)
|
||||
can_drm = false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
if (can_optimal)
|
||||
return VK_IMAGE_TILING_OPTIMAL;
|
||||
if (can_drm)
|
||||
return VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
|
||||
return VK_IMAGE_TILING_LINEAR;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "vk/vk_helpers.h"
|
||||
#include "wivrn_packets.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
struct encoder_settings : public to_headset::video_stream_description::item
|
||||
{
|
||||
// encoder identifier, such as nvenc, vaapi or x264
|
||||
std::string encoder_name;
|
||||
uint64_t bitrate; // bit/s
|
||||
std::map<std::string, std::string> options; // additional encoder-specific configuration
|
||||
// encoders in the same group are executed in sequence
|
||||
int group = 0;
|
||||
};
|
||||
|
||||
|
||||
std::vector<encoder_settings>
|
||||
get_encoder_settings(vk_bundle *vk, uint16_t width, uint16_t height);
|
||||
|
||||
|
||||
VkImageTiling
|
||||
get_required_tiling(vk_bundle *vk, const std::vector<encoder_settings> &settings);
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
Vendored
+3914
File diff suppressed because it is too large
Load Diff
Vendored
+676
@@ -0,0 +1,676 @@
|
||||
/*
|
||||
* fec.c -- forward error correction based on Vandermonde matrices
|
||||
*
|
||||
* Copyright 1997-98 Luigi Rizzo (luigi@iet.unipi.it)
|
||||
* Copyright 2001 Alain Knaff (alain@knaff.lu)
|
||||
* Copyright 2017 Iwan Timmer (irtimmer@gmail.com)
|
||||
*
|
||||
* Portions derived from code by Phil Karn (karn@ka9q.ampr.org),
|
||||
* Robert Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari
|
||||
* Thirumoorthy (harit@spectra.eng.hawaii.edu), Aug 1995
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials
|
||||
* provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
||||
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
|
||||
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
|
||||
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
|
||||
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
|
||||
* OF SUCH DAMAGE.
|
||||
*/
|
||||
// SPDX-License-Identifier: BSD-2-Clause
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <assert.h>
|
||||
#include "rs.h"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#define alloca(x) _alloca(x)
|
||||
#endif
|
||||
|
||||
typedef unsigned char gf;
|
||||
|
||||
#define GF_BITS 8
|
||||
#define GF_PP "101110001"
|
||||
#define GF_SIZE ((1 << GF_BITS) - 1)
|
||||
|
||||
#define SWAP(a, b, t) \
|
||||
{ \
|
||||
t tmp; \
|
||||
tmp = a; \
|
||||
a = b; \
|
||||
b = tmp; \
|
||||
}
|
||||
|
||||
/*
|
||||
* USE_GF_MULC, GF_MULC0(c) and GF_ADDMULC(x) can be used when multiplying
|
||||
* many numbers by the same constant. In this case the first
|
||||
* call sets the constant, and others perform the multiplications.
|
||||
* A value related to the multiplication is held in a local variable
|
||||
* declared with USE_GF_MULC . See usage in addmul1().
|
||||
*/
|
||||
#define USE_GF_MULC gf *__gf_mulc_
|
||||
#define GF_MULC0(c) __gf_mulc_ = &gf_mul_table[(c) << 8]
|
||||
#define GF_ADDMULC(dst, x) dst ^= __gf_mulc_[x]
|
||||
#define GF_MULC(dst, x) dst = __gf_mulc_[x]
|
||||
|
||||
#define gf_mul(x, y) gf_mul_table[(x << 8) + y]
|
||||
|
||||
/*
|
||||
* To speed up computations, we have tables for logarithm, exponent
|
||||
* multiplication and inverse of a number.
|
||||
*/
|
||||
static gf gf_exp[2 * GF_SIZE];
|
||||
static int gf_log[GF_SIZE + 1];
|
||||
static gf inverse[GF_SIZE + 1];
|
||||
#ifdef _MSC_VER
|
||||
static gf __declspec(align(256)) gf_mul_table[(GF_SIZE + 1) * (GF_SIZE + 1)];
|
||||
#else
|
||||
static gf gf_mul_table[(GF_SIZE + 1) * (GF_SIZE + 1)] __attribute__((aligned(256)));
|
||||
#endif
|
||||
|
||||
/*
|
||||
* modnn(x) computes x % GF_SIZE, where GF_SIZE is 2**GF_BITS - 1,
|
||||
* without a slow divide.
|
||||
*/
|
||||
static inline gf
|
||||
modnn(int x)
|
||||
{
|
||||
while (x >= GF_SIZE) {
|
||||
x -= GF_SIZE;
|
||||
x = (x >> GF_BITS) + (x & GF_SIZE);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
static void
|
||||
addmul(gf *dst1, gf *src1, gf c, int sz)
|
||||
{
|
||||
USE_GF_MULC;
|
||||
if (c != 0) {
|
||||
gf *dst = dst1, *src = src1;
|
||||
gf *lim = &dst[sz];
|
||||
|
||||
GF_MULC0(c);
|
||||
for (; dst < lim; dst++, src++)
|
||||
GF_ADDMULC(*dst, *src);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
mul(gf *dst1, gf *src1, gf c, int sz)
|
||||
{
|
||||
USE_GF_MULC;
|
||||
if (c != 0) {
|
||||
gf *dst = dst1, *src = src1;
|
||||
gf *lim = &dst[sz];
|
||||
GF_MULC0(c);
|
||||
for (; dst < lim; dst++, src++)
|
||||
GF_MULC(*dst, *src);
|
||||
} else
|
||||
memset(dst1, 0, c);
|
||||
}
|
||||
|
||||
/* y = a.dot(b) */
|
||||
static gf *
|
||||
multiply1(gf *a, int ar, int ac, gf *b, int br, int bc)
|
||||
{
|
||||
gf *new_m, tg;
|
||||
int r, c, i, ptr = 0;
|
||||
|
||||
assert(ac == br);
|
||||
new_m = (gf *)calloc(1, ar * bc);
|
||||
if (NULL != new_m) {
|
||||
|
||||
/* this multiply is slow */
|
||||
for (r = 0; r < ar; r++) {
|
||||
for (c = 0; c < bc; c++) {
|
||||
tg = 0;
|
||||
for (i = 0; i < ac; i++)
|
||||
tg ^= gf_mul(a[r * ac + i], b[i * bc + c]);
|
||||
|
||||
new_m[ptr++] = tg;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new_m;
|
||||
}
|
||||
|
||||
static void
|
||||
init_mul_table(void)
|
||||
{
|
||||
int i, j;
|
||||
for (i = 0; i < GF_SIZE + 1; i++)
|
||||
for (j = 0; j < GF_SIZE + 1; j++)
|
||||
gf_mul_table[(i << 8) + j] = gf_exp[modnn(gf_log[i] + gf_log[j])];
|
||||
|
||||
for (j = 0; j < GF_SIZE + 1; j++)
|
||||
gf_mul_table[j] = gf_mul_table[j << 8] = 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* initialize the data structures used for computations in GF.
|
||||
*/
|
||||
static void
|
||||
generate_gf(void)
|
||||
{
|
||||
int i;
|
||||
gf mask;
|
||||
|
||||
mask = 1;
|
||||
gf_exp[GF_BITS] = 0;
|
||||
/*
|
||||
* first, generate the (polynomial representation of) powers of \alpha,
|
||||
* which are stored in gf_exp[i] = \alpha ** i .
|
||||
* At the same time build gf_log[gf_exp[i]] = i .
|
||||
* The first GF_BITS powers are simply bits shifted to the left.
|
||||
*/
|
||||
for (i = 0; i < GF_BITS; i++, mask <<= 1) {
|
||||
gf_exp[i] = mask;
|
||||
gf_log[gf_exp[i]] = i;
|
||||
/*
|
||||
* If GF_PP[i] == 1 then \alpha ** i occurs in poly-repr
|
||||
* gf_exp[GF_BITS] = \alpha ** GF_BITS
|
||||
*/
|
||||
if (GF_PP[i] == '1')
|
||||
gf_exp[GF_BITS] ^= mask;
|
||||
}
|
||||
/*
|
||||
* now gf_exp[GF_BITS] = \alpha ** GF_BITS is complete, so can also
|
||||
* compute its inverse.
|
||||
*/
|
||||
gf_log[gf_exp[GF_BITS]] = GF_BITS;
|
||||
/*
|
||||
* Poly-repr of \alpha ** (i+1) is given by poly-repr of
|
||||
* \alpha ** i shifted left one-bit and accounting for any
|
||||
* \alpha ** GF_BITS term that may occur when poly-repr of
|
||||
* \alpha ** i is shifted.
|
||||
*/
|
||||
mask = 1 << (GF_BITS - 1);
|
||||
for (i = GF_BITS + 1; i < GF_SIZE; i++) {
|
||||
if (gf_exp[i - 1] >= mask)
|
||||
gf_exp[i] = gf_exp[GF_BITS] ^ ((gf_exp[i - 1] ^ mask) << 1);
|
||||
else
|
||||
gf_exp[i] = gf_exp[i - 1] << 1;
|
||||
|
||||
gf_log[gf_exp[i]] = i;
|
||||
}
|
||||
/*
|
||||
* log(0) is not defined, so use a special value
|
||||
*/
|
||||
gf_log[0] = GF_SIZE;
|
||||
/* set the extended gf_exp values for fast multiply */
|
||||
for (i = 0; i < GF_SIZE; i++)
|
||||
gf_exp[i + GF_SIZE] = gf_exp[i];
|
||||
|
||||
/*
|
||||
* again special cases. 0 has no inverse. This used to
|
||||
* be initialized to GF_SIZE, but it should make no difference
|
||||
* since no one is supposed to read from here.
|
||||
*/
|
||||
inverse[0] = 0;
|
||||
inverse[1] = 1;
|
||||
for (i = 2; i <= GF_SIZE; i++)
|
||||
inverse[i] = gf_exp[GF_SIZE - gf_log[i]];
|
||||
}
|
||||
|
||||
/*
|
||||
* invert_mat() takes a matrix and produces its inverse
|
||||
* k is the size of the matrix.
|
||||
* (Gauss-Jordan, adapted from Numerical Recipes in C)
|
||||
* Return non-zero if singular.
|
||||
*/
|
||||
static int
|
||||
invert_mat(gf *src, int k)
|
||||
{
|
||||
gf c, *p;
|
||||
int irow, icol, row, col, i, ix;
|
||||
|
||||
int error = 1;
|
||||
int *indxc = (int *)alloca(k * sizeof(int));
|
||||
int *indxr = (int *)alloca(k * sizeof(int));
|
||||
int *ipiv = (int *)alloca(k * sizeof(int));
|
||||
gf *id_row = (gf *)alloca(k * sizeof(gf));
|
||||
|
||||
memset(id_row, 0, k * sizeof(gf));
|
||||
/*
|
||||
* ipiv marks elements already used as pivots.
|
||||
*/
|
||||
for (i = 0; i < k; i++)
|
||||
ipiv[i] = 0;
|
||||
|
||||
for (col = 0; col < k; col++) {
|
||||
gf *pivot_row;
|
||||
/*
|
||||
* Zeroing column 'col', look for a non-zero element.
|
||||
* First try on the diagonal, if it fails, look elsewhere.
|
||||
*/
|
||||
irow = icol = -1;
|
||||
if (ipiv[col] != 1 && src[col * k + col] != 0) {
|
||||
irow = col;
|
||||
icol = col;
|
||||
goto found_piv;
|
||||
}
|
||||
for (row = 0; row < k; row++) {
|
||||
if (ipiv[row] != 1) {
|
||||
for (ix = 0; ix < k; ix++) {
|
||||
if (ipiv[ix] == 0) {
|
||||
if (src[row * k + ix] != 0) {
|
||||
irow = row;
|
||||
icol = ix;
|
||||
goto found_piv;
|
||||
}
|
||||
} else if (ipiv[ix] > 1) {
|
||||
fprintf(stderr, "singular matrix\n");
|
||||
goto fail;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (icol == -1) {
|
||||
fprintf(stderr, "XXX pivot not found!\n");
|
||||
goto fail;
|
||||
}
|
||||
|
||||
found_piv:
|
||||
++(ipiv[icol]);
|
||||
/*
|
||||
* swap rows irow and icol, so afterwards the diagonal
|
||||
* element will be correct. Rarely done, not worth
|
||||
* optimizing.
|
||||
*/
|
||||
if (irow != icol) {
|
||||
for (ix = 0; ix < k; ix++) {
|
||||
SWAP(src[irow * k + ix], src[icol * k + ix], gf);
|
||||
}
|
||||
}
|
||||
indxr[col] = irow;
|
||||
indxc[col] = icol;
|
||||
pivot_row = &src[icol * k];
|
||||
c = pivot_row[icol];
|
||||
if (c == 0) {
|
||||
fprintf(stderr, "singular matrix 2\n");
|
||||
goto fail;
|
||||
} else if (c != 1) {
|
||||
/*
|
||||
* this is done often , but optimizing is not so
|
||||
* fruitful, at least in the obvious ways (unrolling)
|
||||
*/
|
||||
c = inverse[c];
|
||||
pivot_row[icol] = 1;
|
||||
for (ix = 0; ix < k; ix++)
|
||||
pivot_row[ix] = gf_mul(c, pivot_row[ix]);
|
||||
}
|
||||
/*
|
||||
* from all rows, remove multiples of the selected row
|
||||
* to zero the relevant entry (in fact, the entry is not zero
|
||||
* because we know it must be zero).
|
||||
* (Here, if we know that the pivot_row is the identity,
|
||||
* we can optimize the addmul).
|
||||
*/
|
||||
id_row[icol] = 1;
|
||||
if (memcmp(pivot_row, id_row, k * sizeof(gf)) != 0) {
|
||||
for (p = src, ix = 0; ix < k; ix++, p += k) {
|
||||
if (ix != icol) {
|
||||
c = p[icol];
|
||||
p[icol] = 0;
|
||||
addmul(p, pivot_row, c, k);
|
||||
}
|
||||
}
|
||||
}
|
||||
id_row[icol] = 0;
|
||||
}
|
||||
for (col = k - 1; col >= 0; col--) {
|
||||
if (indxr[col] < 0 || indxr[col] >= k)
|
||||
fprintf(stderr, "AARGH, indxr[col] %d\n", indxr[col]);
|
||||
else if (indxc[col] < 0 || indxc[col] >= k)
|
||||
fprintf(stderr, "AARGH, indxc[col] %d\n", indxc[col]);
|
||||
else if (indxr[col] != indxc[col]) {
|
||||
for (row = 0; row < k; row++)
|
||||
SWAP(src[row * k + indxr[col]], src[row * k + indxc[col]], gf);
|
||||
}
|
||||
}
|
||||
error = 0;
|
||||
|
||||
fail:
|
||||
return error;
|
||||
}
|
||||
|
||||
/*
|
||||
* Not check for input params
|
||||
* */
|
||||
static gf *
|
||||
sub_matrix(gf *matrix, int rmin, int cmin, int rmax, int cmax, int nrows, int ncols)
|
||||
{
|
||||
(void)nrows;
|
||||
int i, j, ptr = 0;
|
||||
gf *new_m = (gf *)malloc((rmax - rmin) * (cmax - cmin));
|
||||
if (NULL != new_m) {
|
||||
for (i = rmin; i < rmax; i++) {
|
||||
for (j = cmin; j < cmax; j++) {
|
||||
new_m[ptr++] = matrix[i * ncols + j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new_m;
|
||||
}
|
||||
|
||||
/* copy from golang rs version */
|
||||
static inline int
|
||||
code_some_shards(gf *matrixRows, gf **inputs, gf **outputs, int dataShards, int outputCount, int byteCount)
|
||||
{
|
||||
gf *in;
|
||||
int iRow, c;
|
||||
for (c = 0; c < dataShards; c++) {
|
||||
in = inputs[c];
|
||||
for (iRow = 0; iRow < outputCount; iRow++) {
|
||||
if (0 == c)
|
||||
mul(outputs[iRow], in, matrixRows[iRow * dataShards + c], byteCount);
|
||||
else
|
||||
addmul(outputs[iRow], in, matrixRows[iRow * dataShards + c], byteCount);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
reed_solomon_init(void)
|
||||
{
|
||||
generate_gf();
|
||||
init_mul_table();
|
||||
}
|
||||
|
||||
reed_solomon *
|
||||
reed_solomon_new(int data_shards, int parity_shards)
|
||||
{
|
||||
gf *vm = NULL;
|
||||
gf *top = NULL;
|
||||
int err = 0;
|
||||
reed_solomon *rs = NULL;
|
||||
|
||||
do {
|
||||
rs = (reed_solomon *)malloc(sizeof(reed_solomon));
|
||||
if (NULL == rs)
|
||||
return NULL;
|
||||
|
||||
rs->data_shards = data_shards;
|
||||
rs->parity_shards = parity_shards;
|
||||
rs->shards = (data_shards + parity_shards);
|
||||
rs->m = NULL;
|
||||
rs->parity = NULL;
|
||||
|
||||
if (rs->shards > DATA_SHARDS_MAX || data_shards <= 0 || parity_shards <= 0) {
|
||||
err = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
vm = (gf *)malloc(data_shards * rs->shards);
|
||||
|
||||
if (NULL == vm) {
|
||||
err = 2;
|
||||
break;
|
||||
}
|
||||
|
||||
int ptr = 0;
|
||||
for (int row = 0; row < rs->shards; row++) {
|
||||
for (int col = 0; col < data_shards; col++)
|
||||
vm[ptr++] = row == col ? 1 : 0;
|
||||
}
|
||||
|
||||
top = sub_matrix(vm, 0, 0, data_shards, data_shards, rs->shards, data_shards);
|
||||
if (NULL == top) {
|
||||
err = 3;
|
||||
break;
|
||||
}
|
||||
|
||||
err = invert_mat(top, data_shards);
|
||||
assert(0 == err);
|
||||
|
||||
rs->m = multiply1(vm, rs->shards, data_shards, top, data_shards, data_shards);
|
||||
if (NULL == rs->m) {
|
||||
err = 4;
|
||||
break;
|
||||
}
|
||||
|
||||
for (int j = 0; j < parity_shards; j++) {
|
||||
for (int i = 0; i < data_shards; i++)
|
||||
rs->m[(data_shards + j) * data_shards + i] = inverse[(parity_shards + i) ^ j];
|
||||
}
|
||||
|
||||
rs->parity = sub_matrix(rs->m, data_shards, 0, rs->shards, data_shards, rs->shards, data_shards);
|
||||
if (NULL == rs->parity) {
|
||||
err = 5;
|
||||
break;
|
||||
}
|
||||
|
||||
free(vm);
|
||||
free(top);
|
||||
vm = NULL;
|
||||
top = NULL;
|
||||
return rs;
|
||||
|
||||
} while (0);
|
||||
|
||||
fprintf(stderr, "err=%d\n", err);
|
||||
if (NULL != vm)
|
||||
free(vm);
|
||||
|
||||
if (NULL != top)
|
||||
free(top);
|
||||
|
||||
if (NULL != rs) {
|
||||
if (NULL != rs->m)
|
||||
free(rs->m);
|
||||
|
||||
if (NULL != rs->parity)
|
||||
free(rs->parity);
|
||||
|
||||
free(rs);
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void
|
||||
reed_solomon_release(reed_solomon *rs)
|
||||
{
|
||||
if (NULL != rs) {
|
||||
if (NULL != rs->m)
|
||||
free(rs->m);
|
||||
|
||||
if (NULL != rs->parity)
|
||||
free(rs->parity);
|
||||
|
||||
free(rs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* decode one shard
|
||||
* input:
|
||||
* rs
|
||||
* gf[DATA_SHARDS_MAX*DATA_SHARDS_MAX] array for temporary data
|
||||
* original data_blocks[rs->data_shards][block_size]
|
||||
* dec_fec_blocks[nr_fec_blocks][block_size]
|
||||
* fec_block_nos: fec pos number in original fec_blocks
|
||||
* erased_blocks: erased blocks in original data_blocks
|
||||
* nr_fec_blocks: the number of erased blocks
|
||||
* */
|
||||
static int
|
||||
reed_solomon_decode(reed_solomon *rs,
|
||||
gf *dataDecodeMatrix,
|
||||
unsigned char **data_blocks,
|
||||
int block_size,
|
||||
unsigned char **dec_fec_blocks,
|
||||
unsigned int *fec_block_nos,
|
||||
unsigned int *erased_blocks,
|
||||
int nr_fec_blocks)
|
||||
{
|
||||
unsigned char *subShards[DATA_SHARDS_MAX];
|
||||
unsigned char *outputs[DATA_SHARDS_MAX];
|
||||
gf *m = rs->m;
|
||||
int i, j, c, swap, subMatrixRow, dataShards;
|
||||
|
||||
/* the erased_blocks should always sorted
|
||||
* if sorted, nr_fec_blocks times to check it
|
||||
* if not, sort it here
|
||||
* */
|
||||
for (i = 0; i < nr_fec_blocks; i++) {
|
||||
swap = 0;
|
||||
for (j = i + 1; j < nr_fec_blocks; j++) {
|
||||
if (erased_blocks[i] > erased_blocks[j]) {
|
||||
/* the prefix is bigger than the following, swap */
|
||||
c = erased_blocks[i];
|
||||
erased_blocks[i] = erased_blocks[j];
|
||||
erased_blocks[j] = c;
|
||||
|
||||
swap = 1;
|
||||
}
|
||||
}
|
||||
if (!swap)
|
||||
break;
|
||||
}
|
||||
|
||||
j = 0;
|
||||
subMatrixRow = 0;
|
||||
dataShards = rs->data_shards;
|
||||
for (i = 0; i < dataShards; i++) {
|
||||
if (j < nr_fec_blocks && i == (int)erased_blocks[j])
|
||||
j++;
|
||||
else {
|
||||
/* this row is ok */
|
||||
for (c = 0; c < dataShards; c++)
|
||||
dataDecodeMatrix[subMatrixRow * dataShards + c] = m[i * dataShards + c];
|
||||
|
||||
subShards[subMatrixRow] = data_blocks[i];
|
||||
subMatrixRow++;
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < nr_fec_blocks && subMatrixRow < dataShards; i++) {
|
||||
subShards[subMatrixRow] = dec_fec_blocks[i];
|
||||
j = dataShards + fec_block_nos[i];
|
||||
for (c = 0; c < dataShards; c++)
|
||||
dataDecodeMatrix[subMatrixRow * dataShards + c] = m[j * dataShards + c];
|
||||
|
||||
subMatrixRow++;
|
||||
}
|
||||
|
||||
if (subMatrixRow < dataShards)
|
||||
return -1;
|
||||
|
||||
invert_mat(dataDecodeMatrix, dataShards);
|
||||
|
||||
for (i = 0; i < nr_fec_blocks; i++) {
|
||||
j = erased_blocks[i];
|
||||
outputs[i] = data_blocks[j];
|
||||
memmove(dataDecodeMatrix + i * dataShards, dataDecodeMatrix + j * dataShards, dataShards);
|
||||
}
|
||||
|
||||
return code_some_shards(dataDecodeMatrix, subShards, outputs, dataShards, nr_fec_blocks, block_size);
|
||||
}
|
||||
|
||||
/**
|
||||
* encode a big size of buffer
|
||||
* input:
|
||||
* rs
|
||||
* nr_shards: assert(0 == nr_shards % rs->shards)
|
||||
* shards[nr_shards][block_size]
|
||||
* */
|
||||
int
|
||||
reed_solomon_encode(reed_solomon *rs, unsigned char **shards, int nr_shards, int block_size)
|
||||
{
|
||||
unsigned char **data_blocks;
|
||||
unsigned char **fec_blocks;
|
||||
int i, ds = rs->data_shards, ps = rs->parity_shards, ss = rs->shards;
|
||||
i = nr_shards / ss;
|
||||
data_blocks = shards;
|
||||
fec_blocks = &shards[(i * ds)];
|
||||
|
||||
for (i = 0; i < nr_shards; i += ss) {
|
||||
code_some_shards(rs->parity, data_blocks, fec_blocks, rs->data_shards, rs->parity_shards, block_size);
|
||||
data_blocks += ds;
|
||||
fec_blocks += ps;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* reconstruct a big size of buffer
|
||||
* input:
|
||||
* rs
|
||||
* nr_shards: assert(0 == nr_shards % rs->data_shards)
|
||||
* shards[nr_shards][block_size]
|
||||
* marks[nr_shards] marks as errors
|
||||
* */
|
||||
int
|
||||
reed_solomon_reconstruct(reed_solomon *rs, unsigned char **shards, unsigned char *marks, int nr_shards, int block_size)
|
||||
{
|
||||
unsigned char *dec_fec_blocks[DATA_SHARDS_MAX];
|
||||
unsigned int fec_block_nos[DATA_SHARDS_MAX];
|
||||
unsigned int erased_blocks[DATA_SHARDS_MAX];
|
||||
unsigned char *fec_marks;
|
||||
unsigned char **data_blocks, **fec_blocks;
|
||||
gf *dataDecodeMatrix = malloc(DATA_SHARDS_MAX * DATA_SHARDS_MAX * sizeof(gf));
|
||||
int i, j, dn, pn, n;
|
||||
int ds = rs->data_shards;
|
||||
int ps = rs->parity_shards;
|
||||
int err = 0;
|
||||
|
||||
data_blocks = shards;
|
||||
n = nr_shards / rs->shards;
|
||||
fec_marks = marks + n * ds; // after all data, is't fec marks
|
||||
fec_blocks = shards + n * ds;
|
||||
|
||||
for (j = 0; j < n; j++) {
|
||||
dn = 0;
|
||||
for (i = 0; i < ds; i++) {
|
||||
if (marks[i])
|
||||
erased_blocks[dn++] = i;
|
||||
}
|
||||
if (dn > 0) {
|
||||
pn = 0;
|
||||
for (i = 0; i < ps && pn < dn; i++) {
|
||||
if (!fec_marks[i]) {
|
||||
// got valid fec row
|
||||
fec_block_nos[pn] = i;
|
||||
dec_fec_blocks[pn] = fec_blocks[i];
|
||||
pn++;
|
||||
}
|
||||
}
|
||||
|
||||
if (dn == pn) {
|
||||
reed_solomon_decode(rs, dataDecodeMatrix, data_blocks, block_size, dec_fec_blocks,
|
||||
fec_block_nos, erased_blocks, dn);
|
||||
} else
|
||||
err = -1;
|
||||
}
|
||||
data_blocks += ds;
|
||||
marks += ds;
|
||||
fec_blocks += ps;
|
||||
fec_marks += ps;
|
||||
}
|
||||
|
||||
return err;
|
||||
}
|
||||
Vendored
+92
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* fec.c -- forward error correction based on Vandermonde matrices
|
||||
*
|
||||
* Copyright 1997-98 Luigi Rizzo (luigi@iet.unipi.it)
|
||||
* Copyright 2001 Alain Knaff (alain@knaff.lu)
|
||||
* Copyright 2017 Iwan Timmer (irtimmer@gmail.com)
|
||||
*
|
||||
* Portions derived from code by Phil Karn (karn@ka9q.ampr.org),
|
||||
* Robert Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari
|
||||
* Thirumoorthy (harit@spectra.eng.hawaii.edu), Aug 1995
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials
|
||||
* provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
||||
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
|
||||
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
|
||||
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
|
||||
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
|
||||
* OF SUCH DAMAGE.
|
||||
*/
|
||||
// SPDX-License-Identifier: BSD-2-Clause
|
||||
|
||||
#ifndef __RS_H_
|
||||
#define __RS_H_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* use small value to save memory */
|
||||
#define DATA_SHARDS_MAX 2048
|
||||
|
||||
typedef struct _reed_solomon
|
||||
{
|
||||
int data_shards;
|
||||
int parity_shards;
|
||||
int shards;
|
||||
unsigned char *m;
|
||||
unsigned char *parity;
|
||||
} reed_solomon;
|
||||
|
||||
/**
|
||||
* MUST initial one time
|
||||
* */
|
||||
void
|
||||
reed_solomon_init(void);
|
||||
|
||||
reed_solomon *
|
||||
reed_solomon_new(int data_shards, int parity_shards);
|
||||
void
|
||||
reed_solomon_release(reed_solomon *rs);
|
||||
|
||||
/**
|
||||
* encode a big size of buffer
|
||||
* input:
|
||||
* rs
|
||||
* nr_shards: assert(0 == nr_shards % rs->data_shards)
|
||||
* shards[nr_shards][block_size]
|
||||
* */
|
||||
int
|
||||
reed_solomon_encode(reed_solomon *rs, unsigned char **shards, int nr_shards, int block_size);
|
||||
|
||||
/**
|
||||
* reconstruct a big size of buffer
|
||||
* input:
|
||||
* rs
|
||||
* nr_shards: assert(0 == nr_shards % rs->data_shards)
|
||||
* shards[nr_shards][block_size]
|
||||
* marks[nr_shards] marks as errors
|
||||
* */
|
||||
int
|
||||
reed_solomon_reconstruct(reed_solomon *rs, unsigned char **shards, unsigned char *marks, int nr_shards, int block_size);
|
||||
|
||||
#ifdef __cplusplus
|
||||
};
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,80 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "VideoEncoderFFMPEG.h"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <stdexcept>
|
||||
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
bool
|
||||
should_keep_nal_h264(const uint8_t *header_start)
|
||||
{
|
||||
uint8_t nal_type = (header_start[2] == 0 ? header_start[4] : header_start[3]) & 0x1F;
|
||||
switch (nal_type) {
|
||||
case 6: // supplemental enhancement information
|
||||
case 9: // access unit delimiter
|
||||
return false;
|
||||
default: return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
should_keep_nal_h265(const uint8_t *header_start)
|
||||
{
|
||||
uint8_t nal_type = ((header_start[2] == 0 ? header_start[4] : header_start[3]) >> 1) & 0x3F;
|
||||
switch (nal_type) {
|
||||
case 35: // access unit delimiter
|
||||
case 39: // supplemental enhancement information
|
||||
return false;
|
||||
default: return true;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
filter_NAL(const uint8_t *input, size_t input_size, std::vector<uint8_t> &out, VideoEncoderFFMPEG::Codec codec)
|
||||
{
|
||||
if (input_size < 4)
|
||||
return;
|
||||
std::array<uint8_t, 3> header = {{0, 0, 1}};
|
||||
auto end = input + input_size;
|
||||
auto header_start = input;
|
||||
while (header_start != end) {
|
||||
auto next_header = std::search(header_start + 3, end, header.begin(), header.end());
|
||||
if (next_header != end and next_header[-1] == 0) {
|
||||
next_header--;
|
||||
}
|
||||
if (codec == VideoEncoderFFMPEG::Codec::h264 and should_keep_nal_h264(header_start))
|
||||
out.insert(out.end(), header_start, next_header);
|
||||
if (codec == VideoEncoderFFMPEG::Codec::h265 and should_keep_nal_h265(header_start))
|
||||
out.insert(out.end(), header_start, next_header);
|
||||
header_start = next_header;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
|
||||
void
|
||||
VideoEncoderFFMPEG::Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp)
|
||||
{
|
||||
PushFrame(index, idr, target_timestamp);
|
||||
AVPacket *enc_pkt = av_packet_alloc();
|
||||
int err = avcodec_receive_packet(encoder_ctx.get(), enc_pkt);
|
||||
if (err == 0) {
|
||||
SendData({enc_pkt->data, enc_pkt->data + enc_pkt->size});
|
||||
av_packet_free(&enc_pkt);
|
||||
}
|
||||
if (err == AVERROR(EAGAIN)) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
throw std::runtime_error("frame encoding failed, code " + std::to_string(err));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include "ffmpeg_helper.h"
|
||||
#include "../video_encoder.h"
|
||||
|
||||
class VideoEncoderFFMPEG : public VideoEncoder
|
||||
{
|
||||
public:
|
||||
using Codec = xrt::drivers::wivrn::video_codec;
|
||||
|
||||
void
|
||||
Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) override;
|
||||
|
||||
protected:
|
||||
virtual void
|
||||
PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts) = 0;
|
||||
|
||||
av_codec_context_ptr encoder_ctx;
|
||||
Codec codec;
|
||||
};
|
||||
@@ -0,0 +1,296 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "VideoEncoderVA.h"
|
||||
#include "ffmpeg_helper.h"
|
||||
#include "vk/vk_helpers.h"
|
||||
#include <cassert>
|
||||
#include <stdexcept>
|
||||
#include <chrono>
|
||||
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavfilter/avfilter.h>
|
||||
#include <libavfilter/buffersink.h>
|
||||
#include <libavfilter/buffersrc.h>
|
||||
#include <libavutil/hwcontext.h>
|
||||
#include <libavutil/hwcontext_drm.h>
|
||||
#include <libavutil/hwcontext_vaapi.h>
|
||||
#include <libavutil/opt.h>
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
const char *
|
||||
encoder(VideoEncoderFFMPEG::Codec codec)
|
||||
{
|
||||
switch (codec) {
|
||||
case VideoEncoderFFMPEG::Codec::h264: return "h264_vaapi";
|
||||
case VideoEncoderFFMPEG::Codec::h265: return "hevc_vaapi";
|
||||
}
|
||||
throw std::runtime_error("invalid codec " + std::to_string(int(codec)));
|
||||
}
|
||||
|
||||
void
|
||||
set_hwframe_ctx(AVCodecContext *ctx, AVBufferRef *hw_device_ctx)
|
||||
{
|
||||
av_buffer_ptr hw_frames_ref(av_hwframe_ctx_alloc(hw_device_ctx));
|
||||
int err = 0;
|
||||
|
||||
if (not hw_frames_ref) {
|
||||
throw std::runtime_error("Failed to create VAAPI frame context.");
|
||||
}
|
||||
auto frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
|
||||
frames_ctx->format = AV_PIX_FMT_VAAPI;
|
||||
frames_ctx->sw_format = AV_PIX_FMT_NV12;
|
||||
frames_ctx->width = ctx->width;
|
||||
frames_ctx->height = ctx->height;
|
||||
frames_ctx->initial_pool_size = 3;
|
||||
if ((err = av_hwframe_ctx_init(hw_frames_ref.get())) < 0) {
|
||||
throw std::system_error(err, av_error_category(), "Failed to initialize VAAPI frame context");
|
||||
}
|
||||
ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref.get());
|
||||
if (!ctx->hw_frames_ctx)
|
||||
err = AVERROR(ENOMEM);
|
||||
}
|
||||
|
||||
std::string
|
||||
get_render_device(vk_bundle *vk)
|
||||
{
|
||||
VkPhysicalDeviceDrmPropertiesEXT drmProps{};
|
||||
drmProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT;
|
||||
|
||||
VkPhysicalDeviceProperties2 props{};
|
||||
props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
|
||||
props.pNext = &drmProps;
|
||||
|
||||
vk->vkGetPhysicalDeviceProperties2(vk->physical_device, &props);
|
||||
|
||||
if (!drmProps.hasRender) {
|
||||
U_LOG_E("Failed to find render DRM device");
|
||||
throw std::runtime_error("Failed to find render DRM device");
|
||||
}
|
||||
return "/dev/dri/renderD" + std::to_string(drmProps.renderMinor);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
VideoEncoderVA::VideoEncoderVA(vk_bundle *vk, const encoder_settings &settings, float fps)
|
||||
: vk(vk), width(settings.width), height(settings.height), offset_x(settings.offset_x), offset_y(settings.offset_y)
|
||||
{
|
||||
codec = settings.codec;
|
||||
/* VAAPI Encoding pipeline
|
||||
* The encoding pipeline has 3 frame types:
|
||||
* - input vulkan frames, only used to initialize the mapped frames
|
||||
* - mapped frames, one per input frame, same format, and point to the same memory on the device
|
||||
* - encoder frame, with a format compatible with the encoder, created by the filter
|
||||
* Each frame type has a corresponding hardware frame context, the vulkan one is provided
|
||||
*
|
||||
* The pipeline is simply made of a scale_vaapi object, that does the conversion between formats
|
||||
* and the encoder that takes the converted frame and produces packets.
|
||||
*/
|
||||
|
||||
AVBufferRef *tmp;
|
||||
const std::string device = get_render_device(vk);
|
||||
int err = av_hwdevice_ctx_create(&tmp, AV_HWDEVICE_TYPE_VAAPI, device.c_str(), NULL, 0);
|
||||
if (err < 0) {
|
||||
throw std::system_error(err, av_error_category(), "Failed create a VAAPI device");
|
||||
}
|
||||
hw_ctx_vaapi.reset(tmp);
|
||||
|
||||
const char *encoder_name = encoder(codec);
|
||||
const AVCodec *codec = avcodec_find_encoder_by_name(encoder_name);
|
||||
if (codec == nullptr) {
|
||||
throw std::runtime_error(std::string("Failed to find encoder ") + encoder_name);
|
||||
}
|
||||
|
||||
encoder_ctx.reset(avcodec_alloc_context3(codec));
|
||||
if (not encoder_ctx) {
|
||||
throw std::runtime_error("failed to allocate VAAPI encoder");
|
||||
}
|
||||
|
||||
AVDictionary *opts = nullptr;
|
||||
for (auto option : settings.options) {
|
||||
av_dict_set(&opts, option.first.c_str(), option.second.c_str(), 0);
|
||||
}
|
||||
switch (this->codec) {
|
||||
case Codec::h264: encoder_ctx->profile = FF_PROFILE_H264_MAIN; break;
|
||||
case Codec::h265: encoder_ctx->profile = FF_PROFILE_HEVC_MAIN; break;
|
||||
}
|
||||
|
||||
encoder_ctx->width = width;
|
||||
encoder_ctx->height = height;
|
||||
encoder_ctx->time_base = {std::chrono::steady_clock::duration::period::num,
|
||||
std::chrono::steady_clock::duration::period::den};
|
||||
encoder_ctx->framerate = AVRational{(int)fps, 1};
|
||||
encoder_ctx->sample_aspect_ratio = AVRational{1, 1};
|
||||
encoder_ctx->pix_fmt = AV_PIX_FMT_VAAPI;
|
||||
encoder_ctx->max_b_frames = 0;
|
||||
encoder_ctx->bit_rate = settings.bitrate;
|
||||
|
||||
set_hwframe_ctx(encoder_ctx.get(), hw_ctx_vaapi.get());
|
||||
|
||||
err = avcodec_open2(encoder_ctx.get(), codec, &opts);
|
||||
av_dict_free(&opts);
|
||||
if (err < 0) {
|
||||
throw std::system_error(err, av_error_category(), "Cannot open video encoder codec");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderVA::PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts)
|
||||
{
|
||||
assert(frame_index < mapped_frames.size());
|
||||
av_frame_ptr encoder_frame = make_av_frame();
|
||||
int err = av_buffersrc_add_frame_flags(filter_in, mapped_frames[frame_index].get(),
|
||||
AV_BUFFERSRC_FLAG_PUSH | AV_BUFFERSRC_FLAG_KEEP_REF);
|
||||
if (err != 0) {
|
||||
throw std::system_error(err, av_error_category(), "av_buffersrc_add_frame failed");
|
||||
}
|
||||
err = av_buffersink_get_frame(filter_out, encoder_frame.get());
|
||||
if (err != 0) {
|
||||
throw std::system_error(err, av_error_category(), "av_buffersink_get_frame failed");
|
||||
}
|
||||
|
||||
encoder_frame->pict_type = idr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE;
|
||||
encoder_frame->pts = pts.time_since_epoch().count();
|
||||
err = avcodec_send_frame(encoder_ctx.get(), encoder_frame.get());
|
||||
if (err) {
|
||||
throw std::system_error(err, av_error_category(), "avcodec_send_frame failed");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderVA::SetImages(
|
||||
int width, int height, VkFormat format, int num_images, VkImage *images, VkImageView *views, VkDeviceMemory *memory)
|
||||
{
|
||||
mapped_frames.clear();
|
||||
av_buffer_ptr va_ctx(av_hwframe_ctx_alloc(hw_ctx_vaapi.get()));
|
||||
if (!va_ctx) {
|
||||
throw std::runtime_error("Failed to create VAAPI frame context.");
|
||||
}
|
||||
AVHWFramesContext *va_frames_ctx = (AVHWFramesContext *)(va_ctx->data);
|
||||
va_frames_ctx->format = AV_PIX_FMT_VAAPI;
|
||||
va_frames_ctx->sw_format = vk_format_to_av_format(format);
|
||||
va_frames_ctx->width = width;
|
||||
va_frames_ctx->height = height;
|
||||
va_frames_ctx->initial_pool_size = num_images;
|
||||
int err = av_hwframe_ctx_init(va_ctx.get());
|
||||
if (err) {
|
||||
throw std::system_error(err, av_error_category(), "Failed to create VAAPI frame context");
|
||||
}
|
||||
|
||||
mapped_frames.reserve(num_images);
|
||||
for (int i = 0; i < num_images; ++i) {
|
||||
VkMemoryRequirements req;
|
||||
vk->vkGetImageMemoryRequirements(vk->device, images[i], &req);
|
||||
|
||||
int fd;
|
||||
VkMemoryGetFdInfoKHR export_info{};
|
||||
export_info.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR;
|
||||
export_info.memory = memory[i];
|
||||
export_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
|
||||
vk->vkGetMemoryFdKHR(vk->device, &export_info, &fd);
|
||||
|
||||
auto drm_frame = make_av_frame();
|
||||
drm_frame->format = AV_PIX_FMT_DRM_PRIME;
|
||||
drm_frame->width = width;
|
||||
drm_frame->height = height;
|
||||
drm_frame->buf[0] = av_buffer_alloc(sizeof(AVDRMFrameDescriptor));
|
||||
drm_frame->data[0] = drm_frame->buf[0]->data;
|
||||
auto &drm_frame_desc = *(AVDRMFrameDescriptor *)drm_frame->data[0];
|
||||
drm_frame_desc.nb_objects = 1;
|
||||
drm_frame_desc.objects[0].fd = fd;
|
||||
drm_frame_desc.objects[0].size = req.size;
|
||||
drm_frame_desc.nb_layers = 1;
|
||||
drm_frame_desc.layers[0].format = vk_format_to_fourcc(format);
|
||||
drm_frame_desc.layers[0].nb_planes = 1;
|
||||
drm_frame_desc.layers[0].planes[0].object_index = 0;
|
||||
|
||||
// DRM format modifiers seem to be broken on ffmpeg or radeon, or both
|
||||
bool drm_tiling = use_drm_format_modifiers and vk->has_EXT_image_drm_format_modifier;
|
||||
if (drm_tiling) {
|
||||
VkImageDrmFormatModifierPropertiesEXT modifiers{};
|
||||
modifiers.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT;
|
||||
vk->vkGetImageDrmFormatModifierPropertiesEXT(vk->device, images[i], &modifiers);
|
||||
drm_frame_desc.objects[0].format_modifier = modifiers.drmFormatModifier;
|
||||
}
|
||||
// if we don't have modifiers, we did linear tiling
|
||||
VkImageSubresource subresource{(use_drm_format_modifiers and vk->has_EXT_image_drm_format_modifier)
|
||||
? VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT
|
||||
: VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
0, 0};
|
||||
VkSubresourceLayout layout;
|
||||
vk->vkGetImageSubresourceLayout(vk->device, images[i], &subresource, &layout);
|
||||
drm_frame_desc.layers[0].planes[0].offset = layout.offset;
|
||||
drm_frame_desc.layers[0].planes[0].pitch = layout.rowPitch;
|
||||
|
||||
auto va_frame = make_av_frame();
|
||||
err = av_hwframe_get_buffer(va_ctx.get(), va_frame.get(), 0);
|
||||
if (err)
|
||||
throw std::system_error(err, av_error_category(), "Failed to create VAAPI frame");
|
||||
err = av_hwframe_map(va_frame.get(), drm_frame.get(), AV_HWFRAME_MAP_DIRECT);
|
||||
if (err)
|
||||
throw std::system_error(err, av_error_category(), "Failed to map DRM frame to VAAPI frame");
|
||||
va_frame->crop_left = offset_x;
|
||||
va_frame->crop_right = width - this->width - offset_x;
|
||||
va_frame->crop_top = offset_y;
|
||||
va_frame->crop_bottom = height - this->height - offset_y;
|
||||
mapped_frames.push_back(std::move(va_frame));
|
||||
}
|
||||
|
||||
InitFilterGraph();
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderVA::InitFilterGraph()
|
||||
{
|
||||
assert(not mapped_frames.empty());
|
||||
|
||||
filter_graph.reset(avfilter_graph_alloc());
|
||||
|
||||
AVFilterInOut *outputs = avfilter_inout_alloc();
|
||||
AVFilterInOut *inputs = avfilter_inout_alloc();
|
||||
|
||||
filter_in = avfilter_graph_alloc_filter(filter_graph.get(), avfilter_get_by_name("buffer"), "in");
|
||||
|
||||
AVBufferSrcParameters *par = av_buffersrc_parameters_alloc();
|
||||
memset(par, 0, sizeof(*par));
|
||||
par->width = mapped_frames[0]->width;
|
||||
par->height = mapped_frames[0]->height;
|
||||
par->time_base = encoder_ctx->time_base;
|
||||
par->format = mapped_frames[0]->format;
|
||||
par->hw_frames_ctx = av_buffer_ref(mapped_frames[0]->hw_frames_ctx);
|
||||
av_buffersrc_parameters_set(filter_in, par);
|
||||
av_free(par);
|
||||
|
||||
int err;
|
||||
if ((err = avfilter_graph_create_filter(&filter_out, avfilter_get_by_name("buffersink"), "out", NULL, NULL,
|
||||
filter_graph.get()))) {
|
||||
throw std::system_error(err, av_error_category(), "filter_out creation failed");
|
||||
}
|
||||
|
||||
outputs->name = av_strdup("in");
|
||||
outputs->filter_ctx = filter_in;
|
||||
outputs->pad_idx = 0;
|
||||
outputs->next = NULL;
|
||||
|
||||
inputs->name = av_strdup("out");
|
||||
inputs->filter_ctx = filter_out;
|
||||
inputs->pad_idx = 0;
|
||||
inputs->next = NULL;
|
||||
|
||||
std::string scale_param = "scale_vaapi=format=nv12:w=" + std::to_string(encoder_ctx->width) +
|
||||
":h=" + std::to_string(encoder_ctx->height);
|
||||
err = avfilter_graph_parse_ptr(filter_graph.get(), scale_param.c_str(), &inputs, &outputs, NULL);
|
||||
avfilter_inout_free(&outputs);
|
||||
avfilter_inout_free(&inputs);
|
||||
if (err < 0) {
|
||||
throw std::system_error(err, av_error_category(), "avfilter_graph_parse_ptr failed");
|
||||
}
|
||||
|
||||
if ((err = avfilter_graph_config(filter_graph.get(), NULL))) {
|
||||
throw std::system_error(err, av_error_category(), "avfilter_graph_config failed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "VideoEncoderFFMPEG.h"
|
||||
#include "vk/vk_helpers.h"
|
||||
#include "ffmpeg_helper.h"
|
||||
|
||||
extern "C" {
|
||||
#include <libavutil/version.h>
|
||||
}
|
||||
|
||||
// DRM format modifiers are not implemented before ffmpeg 5
|
||||
inline const bool use_drm_format_modifiers = LIBAVUTIL_VERSION_MAJOR >= 57;
|
||||
|
||||
struct AVFilterContext;
|
||||
|
||||
class VideoEncoderVA : public VideoEncoderFFMPEG
|
||||
{
|
||||
public:
|
||||
VideoEncoderVA(vk_bundle *vk, const encoder_settings &settings, float fps);
|
||||
|
||||
void
|
||||
SetImages(int width,
|
||||
int height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage *images,
|
||||
VkImageView *views,
|
||||
VkDeviceMemory *memory) override;
|
||||
|
||||
void
|
||||
PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts) override;
|
||||
|
||||
private:
|
||||
void
|
||||
InitFilterGraph();
|
||||
|
||||
vk_bundle *vk;
|
||||
int width;
|
||||
int height;
|
||||
// relevant part of the input image to encode
|
||||
int offset_x;
|
||||
int offset_y;
|
||||
av_buffer_ptr hw_ctx_vaapi;
|
||||
std::vector<av_frame_ptr> mapped_frames;
|
||||
av_filter_graph_ptr filter_graph;
|
||||
AVFilterContext *filter_in = nullptr;
|
||||
AVFilterContext *filter_out = nullptr;
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "ffmpeg_helper.h"
|
||||
#include <libdrm/drm_fourcc.h>
|
||||
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavfilter/avfilter.h>
|
||||
#include <libavutil/hwcontext.h>
|
||||
#include <libavutil/hwcontext_vulkan.h>
|
||||
#include <libavutil/opt.h>
|
||||
}
|
||||
|
||||
namespace {
|
||||
struct : public std::error_category
|
||||
{
|
||||
const char *
|
||||
name() const noexcept override
|
||||
{
|
||||
return "ffmpeg";
|
||||
}
|
||||
std::string
|
||||
message(int averror) const override
|
||||
{
|
||||
char av_msg[AV_ERROR_MAX_STRING_SIZE];
|
||||
av_strerror(averror, av_msg, sizeof(av_msg));
|
||||
return av_msg;
|
||||
}
|
||||
} error_category;
|
||||
} // namespace
|
||||
|
||||
const std::error_category &
|
||||
av_error_category()
|
||||
{
|
||||
return error_category;
|
||||
};
|
||||
|
||||
// it seems that ffmpeg does not provide this mapping
|
||||
AVPixelFormat
|
||||
vk_format_to_av_format(VkFormat vk_fmt)
|
||||
{
|
||||
switch (vk_fmt) {
|
||||
case VK_FORMAT_B8G8R8A8_SRGB: return AV_PIX_FMT_BGRA;
|
||||
default: break;
|
||||
}
|
||||
for (int f = AV_PIX_FMT_NONE; f < AV_PIX_FMT_NB; ++f) {
|
||||
auto current_fmt = av_vkfmt_from_pixfmt(AVPixelFormat(f));
|
||||
if (current_fmt and *current_fmt == (VkFormat)vk_fmt)
|
||||
return AVPixelFormat(f);
|
||||
}
|
||||
throw std::runtime_error("unsupported vulkan pixel format " + std::to_string((VkFormat)vk_fmt));
|
||||
}
|
||||
|
||||
uint32_t
|
||||
vk_format_to_fourcc(VkFormat vk_fmt)
|
||||
{
|
||||
switch (vk_fmt) {
|
||||
case VK_FORMAT_B8G8R8A8_SRGB: return DRM_FORMAT_ARGB8888;
|
||||
case VK_FORMAT_B8G8R8A8_UNORM: return DRM_FORMAT_ARGB8888;
|
||||
default: break;
|
||||
}
|
||||
throw std::runtime_error("unsupported vulkan pixel format " + std::to_string((VkFormat)vk_fmt));
|
||||
}
|
||||
|
||||
void
|
||||
AvDeleter::operator()(AVBufferRef *x)
|
||||
{
|
||||
av_buffer_unref(&x);
|
||||
}
|
||||
|
||||
void
|
||||
AvDeleter::operator()(AVFrame *x)
|
||||
{
|
||||
av_frame_unref(x);
|
||||
}
|
||||
|
||||
void
|
||||
AvDeleter::operator()(AVCodecContext *x)
|
||||
{
|
||||
avcodec_free_context(&x);
|
||||
}
|
||||
|
||||
void
|
||||
AvDeleter::operator()(AVFilterGraph *x)
|
||||
{
|
||||
avfilter_graph_free(&x);
|
||||
}
|
||||
|
||||
av_frame_ptr
|
||||
make_av_frame(AVFrame *frame)
|
||||
{
|
||||
return av_frame_ptr(frame);
|
||||
}
|
||||
|
||||
av_frame_ptr
|
||||
make_av_frame()
|
||||
{
|
||||
return make_av_frame(av_frame_alloc());
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
#include "vk/vk_helpers.h"
|
||||
|
||||
struct AVBufferRef;
|
||||
struct AVFilterGraph;
|
||||
struct AVFrame;
|
||||
struct AVCodecContext;
|
||||
|
||||
extern "C" {
|
||||
#include <libavutil/avutil.h>
|
||||
}
|
||||
|
||||
const std::error_category &
|
||||
av_error_category();
|
||||
|
||||
AVPixelFormat
|
||||
vk_format_to_av_format(VkFormat vk_fmt);
|
||||
|
||||
uint32_t
|
||||
vk_format_to_fourcc(VkFormat vk_fmt);
|
||||
|
||||
struct AvDeleter
|
||||
{
|
||||
void
|
||||
operator()(AVBufferRef *);
|
||||
void
|
||||
operator()(AVFrame *);
|
||||
void
|
||||
operator()(AVCodecContext *);
|
||||
void
|
||||
operator()(AVFilterGraph *);
|
||||
};
|
||||
|
||||
using av_buffer_ptr = std::unique_ptr<AVBufferRef, AvDeleter>;
|
||||
using av_frame_ptr = std::unique_ptr<AVFrame, AvDeleter>;
|
||||
using av_codec_context_ptr = std::unique_ptr<AVCodecContext, AvDeleter>;
|
||||
using av_filter_graph_ptr = std::unique_ptr<AVFilterGraph, AvDeleter>;
|
||||
|
||||
av_buffer_ptr
|
||||
make_av_buffer(AVBufferRef *);
|
||||
|
||||
av_frame_ptr
|
||||
make_av_frame(AVFrame *);
|
||||
|
||||
av_frame_ptr
|
||||
make_av_frame();
|
||||
@@ -0,0 +1,99 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "pose_list.h"
|
||||
#include "math/m_space.h"
|
||||
#include "xrt/xrt_defines.h"
|
||||
#include "xrt_cast.h"
|
||||
#include "math/m_vec3.h"
|
||||
#include "math/m_eigen_interop.hpp"
|
||||
|
||||
using namespace xrt::auxiliary::math;
|
||||
|
||||
xrt_space_relation
|
||||
interpolate(const xrt_space_relation &a, const xrt_space_relation &b, float t)
|
||||
{
|
||||
xrt_space_relation result;
|
||||
xrt_space_relation_flags flags = xrt_space_relation_flags(a.relation_flags & b.relation_flags);
|
||||
m_space_relation_interpolate(const_cast<xrt_space_relation*>(&a), const_cast<xrt_space_relation*>(&b), t, flags, &result);
|
||||
return result;
|
||||
}
|
||||
|
||||
xrt_space_relation
|
||||
extrapolate(const xrt_space_relation &a, const xrt_space_relation &b, uint64_t ta, uint64_t tb, uint64_t t)
|
||||
{
|
||||
if (t < ta)
|
||||
return a;
|
||||
|
||||
float h = (tb - ta) / 1.e9;
|
||||
|
||||
xrt_space_relation res;
|
||||
res.relation_flags = b.relation_flags;
|
||||
|
||||
xrt_vec3 lin_acc = (b.linear_velocity - a.linear_velocity) / h;
|
||||
xrt_vec3 ang_acc = (b.angular_velocity - a.angular_velocity) / h;
|
||||
|
||||
float dt = (t - tb) / 1.e9;
|
||||
// if (dt > 0.2)
|
||||
// dt = 0.2; // saturate dt to 200ms
|
||||
|
||||
|
||||
float dt2_over_2 = dt * dt / 2;
|
||||
res.linear_velocity = b.linear_velocity + lin_acc * dt;
|
||||
res.pose.position = b.pose.position + b.linear_velocity * dt + lin_acc * dt2_over_2;
|
||||
|
||||
res.angular_velocity = b.angular_velocity + ang_acc * dt;
|
||||
xrt_vec3 dtheta = b.angular_velocity * dt + ang_acc * dt2_over_2;
|
||||
xrt_quat dq;
|
||||
math_quat_exp(&dtheta, &dq);
|
||||
|
||||
map_quat(res.pose.orientation) = map_quat(b.pose.orientation) * map_quat(dq);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
void
|
||||
pose_list::update_tracking(const from_headset::tracking &tracking, const clock_offset &offset)
|
||||
{
|
||||
for (const auto &pose : tracking.device_poses) {
|
||||
if (pose.device != device)
|
||||
continue;
|
||||
|
||||
add_sample(tracking.timestamp, convert_pose(pose), offset);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
xrt_space_relation
|
||||
pose_list::convert_pose(const from_headset::tracking::pose &pose)
|
||||
{
|
||||
xrt_space_relation res{};
|
||||
|
||||
res.pose = xrt_cast(pose.pose);
|
||||
res.angular_velocity = xrt_cast(pose.angular_velocity);
|
||||
res.linear_velocity = xrt_cast(pose.linear_velocity);
|
||||
|
||||
int flags = 0;
|
||||
if (pose.flags & from_headset::tracking::position_valid)
|
||||
flags |= XRT_SPACE_RELATION_POSITION_VALID_BIT;
|
||||
|
||||
if (pose.flags & from_headset::tracking::orientation_valid)
|
||||
flags |= XRT_SPACE_RELATION_ORIENTATION_VALID_BIT;
|
||||
|
||||
if (pose.flags & from_headset::tracking::linear_velocity_valid)
|
||||
flags |= XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT;
|
||||
|
||||
if (pose.flags & from_headset::tracking::angular_velocity_valid)
|
||||
flags |= XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT;
|
||||
|
||||
if (pose.flags & from_headset::tracking::position_tracked)
|
||||
flags |= XRT_SPACE_RELATION_POSITION_TRACKED_BIT;
|
||||
|
||||
if (pose.flags & from_headset::tracking::orientation_tracked)
|
||||
flags |= XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT;
|
||||
|
||||
res.relation_flags = (xrt_space_relation_flags)flags;
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "wivrn_session.h"
|
||||
#include <algorithm>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
template <typename Data, size_t MaxSamples = 10> class history
|
||||
{
|
||||
struct TimedData : public Data
|
||||
{
|
||||
TimedData(const Data &d, uint64_t t) : Data(d), at_timestamp_ns(t) {}
|
||||
uint64_t at_timestamp_ns;
|
||||
};
|
||||
|
||||
std::mutex mutex;
|
||||
std::vector<TimedData> data;
|
||||
|
||||
protected:
|
||||
void
|
||||
add_sample(uint64_t timestamp, const Data &sample, const clock_offset &offset)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
|
||||
uint64_t t = offset.from_headset(timestamp);
|
||||
auto it = std::lower_bound(data.begin(), data.end(), t,
|
||||
[](TimedData &sample, uint64_t t) { return sample.at_timestamp_ns < t; });
|
||||
|
||||
if (it == data.end())
|
||||
data.emplace_back(sample, t);
|
||||
else if (it->at_timestamp_ns == t)
|
||||
*it = TimedData(sample, t);
|
||||
else
|
||||
data.emplace(it, sample, t);
|
||||
|
||||
if (data.size() > MaxSamples)
|
||||
data.erase(data.begin());
|
||||
}
|
||||
|
||||
public:
|
||||
Data
|
||||
get_at(uint64_t at_timestamp_ns)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
|
||||
if (data.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (data.size() == 1) {
|
||||
return data[0];
|
||||
}
|
||||
|
||||
if (data.front().at_timestamp_ns > at_timestamp_ns) {
|
||||
return extrapolate(data[0], data[1], data[0].at_timestamp_ns, data[1].at_timestamp_ns,
|
||||
at_timestamp_ns);
|
||||
}
|
||||
|
||||
for (size_t i = 1; i < data.size(); ++i) {
|
||||
if (data[i].at_timestamp_ns > at_timestamp_ns) {
|
||||
float t = float(data[i].at_timestamp_ns - at_timestamp_ns) /
|
||||
(data[i].at_timestamp_ns - data[i - 1].at_timestamp_ns);
|
||||
return interpolate(data[i - 1], data[i], t);
|
||||
}
|
||||
}
|
||||
|
||||
const auto &d0 = data[data.size() - 2];
|
||||
const auto &d1 = data.back();
|
||||
|
||||
return extrapolate(d0, d1, d0.at_timestamp_ns, d1.at_timestamp_ns, at_timestamp_ns);
|
||||
}
|
||||
};
|
||||
|
||||
xrt_space_relation
|
||||
interpolate(const xrt_space_relation &a, const xrt_space_relation &b, float t);
|
||||
|
||||
xrt_space_relation
|
||||
extrapolate(const xrt_space_relation &a, const xrt_space_relation &b, uint64_t ta, uint64_t tb, uint64_t t);
|
||||
|
||||
class pose_list : public history<xrt_space_relation>
|
||||
{
|
||||
device_id device;
|
||||
|
||||
public:
|
||||
pose_list(device_id id) : device(id) {}
|
||||
|
||||
void
|
||||
update_tracking(const from_headset::tracking &, const clock_offset &offset);
|
||||
|
||||
static xrt_space_relation
|
||||
convert_pose(const from_headset::tracking::pose &);
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#version 450
|
||||
|
||||
layout (binding = 0) uniform sampler2D image;
|
||||
|
||||
layout (location = 0) in vec2 pos;
|
||||
|
||||
layout (location = 0) out vec2 uv;
|
||||
|
||||
float gamma(float x)
|
||||
{
|
||||
if (x <= 0.0031308)
|
||||
return 12.92 * x;
|
||||
else
|
||||
return 1.055 * pow(x, 1/2.4) - 0.055;
|
||||
}
|
||||
|
||||
vec4 gamma4(vec4 x)
|
||||
{
|
||||
return vec4(gamma(x.r), gamma(x.g), gamma(x.b), gamma(x.a));
|
||||
}
|
||||
|
||||
float reduce_range(float x)
|
||||
{
|
||||
return (128 + x * 224) / 256;
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec4 rgba = gamma4(texture(image, pos));
|
||||
uv.x = reduce_range(rgba.r * -0.1146 + rgba.g * -0.3854 + rgba.b * 0.5);
|
||||
uv.y = reduce_range(rgba.r * 0.5 + rgba.g * -0.4542 + rgba.b * -0.0458);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#version 450
|
||||
|
||||
layout (location = 0) out vec2 outUV;
|
||||
|
||||
void main() {
|
||||
outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); // [(0, 0), (2, 0), (0, 2)]
|
||||
gl_Position = vec4(outUV * 2.0f + -1.0f, 0.0f, 1.0f); // [(-1, -1), (3, -1), (-1, 3)]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#version 450
|
||||
|
||||
layout (binding = 0) uniform sampler2D image;
|
||||
|
||||
layout (location = 0) in vec2 pos;
|
||||
|
||||
layout (location = 0) out float y;
|
||||
|
||||
float gamma(float x)
|
||||
{
|
||||
if (x <= 0.0031308)
|
||||
return 12.92 * x;
|
||||
else
|
||||
return 1.055 * pow(x, 1/2.4) - 0.055;
|
||||
}
|
||||
|
||||
vec4 gamma4(vec4 x)
|
||||
{
|
||||
return vec4(gamma(x.r), gamma(x.g), gamma(x.b), gamma(x.a));
|
||||
}
|
||||
|
||||
float reduce_range(float x)
|
||||
{
|
||||
return (16 + x * 219) / 256;
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec4 rgba = gamma4(texture(image, pos));
|
||||
y = reduce_range(rgba.r * 0.2126 + rgba.g * 0.7152 + rgba.b * 0.0722);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "video_encoder.h"
|
||||
#include "external/rs.h"
|
||||
#include "util/u_logging.h"
|
||||
#include "xrt/xrt_defines.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
#ifdef XRT_HAVE_CUDA
|
||||
#include "video_encoder_nvenc.h"
|
||||
#endif
|
||||
#ifdef XRT_HAVE_FFMPEG
|
||||
#include "ffmpeg/VideoEncoderVA.h"
|
||||
#endif
|
||||
#ifdef XRT_HAVE_X264
|
||||
#include "video_encoder_x264.h"
|
||||
#endif
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
std::unique_ptr<VideoEncoder>
|
||||
VideoEncoder::Create(
|
||||
vk_bundle *vk, encoder_settings &settings, uint8_t stream_idx, int input_width, int input_height, float fps)
|
||||
{
|
||||
using namespace std::string_literals;
|
||||
std::unique_ptr<VideoEncoder> res;
|
||||
#ifdef XRT_HAVE_X264
|
||||
if (settings.encoder_name == encoder_x264) {
|
||||
res = std::make_unique<VideoEncoderX264>(vk, settings, input_width, input_height, fps);
|
||||
}
|
||||
#endif
|
||||
#ifdef XRT_HAVE_CUDA
|
||||
if (settings.encoder_name == encoder_nvenc) {
|
||||
res = std::make_unique<VideoEncoderNvenc>(vk, settings, fps);
|
||||
}
|
||||
#endif
|
||||
#ifdef XRT_HAVE_FFMPEG
|
||||
if (settings.encoder_name == encoder_vaapi) {
|
||||
res = std::make_unique<VideoEncoderVA>(vk, settings, fps);
|
||||
}
|
||||
#endif
|
||||
if (res) {
|
||||
res->stream_idx = stream_idx;
|
||||
} else {
|
||||
U_LOG_E("No video encoder %s", settings.encoder_name.c_str());
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoder::Encode(wivrn_session &cnx,
|
||||
const to_headset::video_stream_data_shard::view_info_t &view_info,
|
||||
uint64_t frame_index,
|
||||
int index,
|
||||
bool idr)
|
||||
{
|
||||
this->cnx = &cnx;
|
||||
this->frame_idx = frame_index;
|
||||
auto target_timestamp = std::chrono::steady_clock::time_point(std::chrono::nanoseconds(view_info.display_time));
|
||||
|
||||
shards.clear();
|
||||
Encode(index, idr, target_timestamp);
|
||||
if (shards.empty())
|
||||
return;
|
||||
const size_t view_info_size = sizeof(to_headset::video_stream_data_shard::view_info_t);
|
||||
if (shards.back().payload.size() + view_info_size > to_headset::video_stream_data_shard::max_payload_size) {
|
||||
// Push empty data so previous shard is sent and counters are set
|
||||
PushShard({}, to_headset::video_stream_data_shard::start_of_slice |
|
||||
to_headset::video_stream_data_shard::end_of_slice);
|
||||
}
|
||||
shards.back().view_info = view_info;
|
||||
shards.back().flags |= to_headset::video_stream_data_shard::end_of_frame;
|
||||
cnx.send_stream(shards.back());
|
||||
|
||||
// forward error correction
|
||||
std::vector<std::vector<uint8_t>> data_shards;
|
||||
data_shards.reserve(shards.size());
|
||||
size_t max_size = 0;
|
||||
for (const auto &shard : shards) {
|
||||
serialization_packet packet;
|
||||
packet.serialize(shard);
|
||||
const auto &serialized = data_shards.emplace_back(std::move(packet));
|
||||
max_size = std::max(max_size, serialized.size());
|
||||
}
|
||||
|
||||
size_t parity = std::max<size_t>(1, shards.size() * 0.05);
|
||||
std::vector<std::vector<uint8_t>> parity_shards(parity);
|
||||
|
||||
std::vector<unsigned char *> shard_pointers;
|
||||
|
||||
for (auto &shard : data_shards) {
|
||||
shard.resize(max_size, 0);
|
||||
shard_pointers.push_back(shard.data());
|
||||
}
|
||||
|
||||
for (auto &shard : parity_shards) {
|
||||
shard.resize(max_size, 0);
|
||||
shard_pointers.push_back(shard.data());
|
||||
}
|
||||
|
||||
static std::once_flag once;
|
||||
std::call_once(once, reed_solomon_init);
|
||||
|
||||
std::unique_ptr<reed_solomon, void (*)(reed_solomon *)> rs(reed_solomon_new(shards.size(), parity),
|
||||
reed_solomon_release);
|
||||
if (rs) {
|
||||
reed_solomon_encode(rs.get(), shard_pointers.data(), shard_pointers.size(), max_size);
|
||||
|
||||
for (auto &shard : parity_shards) {
|
||||
to_headset::video_stream_parity_shard packet{};
|
||||
packet.stream_item_idx = stream_idx;
|
||||
packet.frame_idx = frame_idx;
|
||||
packet.data_shard_count = data_shards.size();
|
||||
packet.num_parity_elements = parity;
|
||||
packet.payload = std::move(shard);
|
||||
cnx.send_stream(packet);
|
||||
}
|
||||
} else {
|
||||
U_LOG_W("failed to setup reed_solomon encoder with %ld data shards", data_shards.size());
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoder::SendData(std::vector<uint8_t> &&data)
|
||||
{
|
||||
auto &max_payload_size = to_headset::video_stream_data_shard::max_payload_size;
|
||||
std::lock_guard lock(mutex);
|
||||
uint8_t flags = to_headset::video_stream_data_shard::start_of_slice;
|
||||
if (data.size() <= max_payload_size) {
|
||||
PushShard(std::move(data), flags | to_headset::video_stream_data_shard::end_of_slice);
|
||||
}
|
||||
auto begin = data.begin();
|
||||
auto end = data.end();
|
||||
while (begin != end) {
|
||||
auto next = std::min(end, begin + max_payload_size);
|
||||
if (next == end) {
|
||||
flags |= to_headset::video_stream_data_shard::end_of_slice;
|
||||
}
|
||||
PushShard({begin, next}, flags);
|
||||
begin = next;
|
||||
flags = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoder::PushShard(std::vector<uint8_t> &&payload, uint8_t flags)
|
||||
{
|
||||
if (not shards.empty()) {
|
||||
cnx->send_stream(shards.back());
|
||||
}
|
||||
to_headset::video_stream_data_shard shard;
|
||||
shard.stream_item_idx = stream_idx;
|
||||
shard.frame_idx = frame_idx;
|
||||
shard.shard_idx = shards.size();
|
||||
shard.flags = flags;
|
||||
shard.payload = std::move(payload);
|
||||
shards.emplace_back(std::move(shard));
|
||||
}
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,83 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "vk/vk_helpers.h"
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#include "encoder_settings.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include "wivrn_session.h"
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
inline const char *encoder_nvenc = "nvenc";
|
||||
inline const char *encoder_vaapi = "vaapi";
|
||||
inline const char *encoder_x264 = "x264";
|
||||
|
||||
class VideoEncoder
|
||||
{
|
||||
std::mutex mutex;
|
||||
uint8_t stream_idx;
|
||||
uint64_t frame_idx;
|
||||
|
||||
// temporary data
|
||||
wivrn_session *cnx;
|
||||
|
||||
std::vector<to_headset::video_stream_data_shard> shards;
|
||||
|
||||
public:
|
||||
static std::unique_ptr<VideoEncoder>
|
||||
Create(vk_bundle *vk,
|
||||
encoder_settings &settings,
|
||||
uint8_t stream_idx,
|
||||
int input_width,
|
||||
int input_height,
|
||||
float fps);
|
||||
|
||||
virtual ~VideoEncoder() = default;
|
||||
|
||||
// set input images to be encoded.
|
||||
// later referred by index only
|
||||
virtual void
|
||||
SetImages(int width,
|
||||
int height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage *images,
|
||||
VkImageView *views,
|
||||
VkDeviceMemory *memory) = 0;
|
||||
|
||||
// optional entrypoint, called on present to submit command buffers for the image.
|
||||
virtual void
|
||||
PresentImage(int index, VkCommandBuffer *out_buffer)
|
||||
{}
|
||||
|
||||
void
|
||||
Encode(wivrn_session &cnx,
|
||||
const to_headset::video_stream_data_shard::view_info_t &view_info,
|
||||
uint64_t frame_index,
|
||||
int index,
|
||||
bool idr);
|
||||
|
||||
|
||||
protected:
|
||||
// encode the image at provided index.
|
||||
virtual void
|
||||
Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) = 0;
|
||||
|
||||
void
|
||||
SendData(std::vector<uint8_t> &&data);
|
||||
|
||||
private:
|
||||
void
|
||||
PushShard(std::vector<uint8_t> &&payload, uint8_t flags);
|
||||
};
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,269 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "video_encoder_nvenc.h"
|
||||
#include "external/nvEncodeAPI.h"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
#define NVENC_CHECK_NOENCODER(x) \
|
||||
do { \
|
||||
NVENCSTATUS status = x; \
|
||||
if (status != NV_ENC_SUCCESS) { \
|
||||
U_LOG_E("%s:%d: %d", __FILE__, __LINE__, status); \
|
||||
throw std::runtime_error("TODO"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define NVENC_CHECK(x) \
|
||||
do { \
|
||||
NVENCSTATUS status = x; \
|
||||
if (status != NV_ENC_SUCCESS) { \
|
||||
U_LOG_E("%s:%d: %d, %s", __FILE__, __LINE__, status, \
|
||||
fn.nvEncGetLastErrorString(session_handle)); \
|
||||
throw std::runtime_error("TODO"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define CU_CHECK(x) \
|
||||
do { \
|
||||
CUresult status = x; \
|
||||
if (status != CUDA_SUCCESS) { \
|
||||
const char *error_string; \
|
||||
cuGetErrorString(status, &error_string); \
|
||||
U_LOG_E("%s:%d: %s (%d)", __FILE__, __LINE__, error_string, (int)status); \
|
||||
throw std::runtime_error("TODO"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
VideoEncoderNvenc::VideoEncoderNvenc(vk_bundle *vk, const encoder_settings &settings, float fps)
|
||||
: vk(vk), offset_x(settings.offset_x), offset_y(settings.offset_y), width(settings.width), height(settings.height),
|
||||
codec(settings.codec), fps(fps), bitrate(settings.bitrate)
|
||||
{
|
||||
CU_CHECK(cuInit(0));
|
||||
|
||||
CU_CHECK(cuCtxCreate(&cuda, 0, 0));
|
||||
|
||||
fn.version = NV_ENCODE_API_FUNCTION_LIST_VER;
|
||||
NVENC_CHECK_NOENCODER(NvEncodeAPICreateInstance(&fn));
|
||||
|
||||
|
||||
NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params{};
|
||||
params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
|
||||
params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
|
||||
params.device = cuda;
|
||||
params.apiVersion = NVENCAPI_VERSION;
|
||||
|
||||
NVENC_CHECK_NOENCODER(fn.nvEncOpenEncodeSessionEx(¶ms, &session_handle));
|
||||
|
||||
uint32_t count;
|
||||
std::vector<GUID> presets;
|
||||
auto encodeGUID = codec == video_codec::h264 ? NV_ENC_CODEC_H264_GUID : NV_ENC_CODEC_HEVC_GUID;
|
||||
NVENC_CHECK(fn.nvEncGetEncodePresetCount(session_handle, encodeGUID, &count));
|
||||
presets.resize(count);
|
||||
NVENC_CHECK(fn.nvEncGetEncodePresetGUIDs(session_handle, encodeGUID, presets.data(), count, &count));
|
||||
|
||||
switch (codec) {
|
||||
case video_codec::h264: printf("%d H264 presets\n", count); break;
|
||||
|
||||
case video_codec::h265: printf("%d HEVC presets\n", count); break;
|
||||
}
|
||||
|
||||
for (GUID &i : presets) {
|
||||
printf(" Preset {%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n", i.Data1, i.Data2, i.Data3,
|
||||
i.Data4[0], i.Data4[1], i.Data4[2], i.Data4[3], i.Data4[4], i.Data4[5], i.Data4[6], i.Data4[7]);
|
||||
}
|
||||
|
||||
NV_ENC_CAPS_PARAM cap_param{};
|
||||
cap_param.version = NV_ENC_CAPS_PARAM_VER;
|
||||
cap_param.capsToQuery = NV_ENC_CAPS_SUPPORT_REF_PIC_INVALIDATION;
|
||||
int cap_value;
|
||||
NVENC_CHECK(fn.nvEncGetEncodeCaps(session_handle, encodeGUID, &cap_param, &cap_value));
|
||||
supports_frame_invalidation = cap_value;
|
||||
if (supports_frame_invalidation)
|
||||
printf("Frame invalidation supported\n");
|
||||
else
|
||||
printf("Frame invalidation not supported\n");
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderNvenc::SetImages(int full_width,
|
||||
int full_height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage *images,
|
||||
VkImageView *views,
|
||||
VkDeviceMemory *memory)
|
||||
{
|
||||
auto encodeGUID = codec == video_codec::h264 ? NV_ENC_CODEC_H264_GUID : NV_ENC_CODEC_HEVC_GUID;
|
||||
// auto presetGUID = codec == video_codec::h264 ? NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID :
|
||||
// NV_ENC_PRESET_P7_GUID;
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
|
||||
auto presetGUID = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
|
||||
#pragma GCC diagnostic pop
|
||||
NV_ENC_PRESET_CONFIG preset_config;
|
||||
preset_config.version = NV_ENC_PRESET_CONFIG_VER;
|
||||
preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
|
||||
NVENC_CHECK(fn.nvEncGetEncodePresetConfig(session_handle, encodeGUID, presetGUID, &preset_config));
|
||||
|
||||
|
||||
NV_ENC_CONFIG params = preset_config.presetCfg;
|
||||
|
||||
// Bitrate control
|
||||
params.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
|
||||
params.rcParams.averageBitRate = bitrate;
|
||||
params.rcParams.maxBitRate = bitrate;
|
||||
params.rcParams.vbvBufferSize = bitrate / fps;
|
||||
params.rcParams.vbvInitialDelay = bitrate / fps;
|
||||
|
||||
params.gopLength = NVENC_INFINITE_GOPLENGTH;
|
||||
params.frameIntervalP = 1;
|
||||
|
||||
switch (codec) {
|
||||
case video_codec::h264:
|
||||
params.encodeCodecConfig.h264Config.repeatSPSPPS = 1;
|
||||
params.encodeCodecConfig.h264Config.maxNumRefFrames = 0;
|
||||
params.encodeCodecConfig.h264Config.idrPeriod = NVENC_INFINITE_GOPLENGTH;
|
||||
break;
|
||||
case video_codec::h265:
|
||||
params.encodeCodecConfig.hevcConfig.repeatSPSPPS = 1;
|
||||
params.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = 0;
|
||||
params.encodeCodecConfig.hevcConfig.idrPeriod = NVENC_INFINITE_GOPLENGTH;
|
||||
break;
|
||||
}
|
||||
|
||||
NV_ENC_INITIALIZE_PARAMS params2{};
|
||||
params2.version = NV_ENC_INITIALIZE_PARAMS_VER;
|
||||
params2.encodeGUID = encodeGUID;
|
||||
params2.presetGUID = presetGUID;
|
||||
params2.encodeWidth = uint32_t(width);
|
||||
params2.encodeHeight = uint32_t(height);
|
||||
params2.darWidth = uint32_t(width);
|
||||
params2.darHeight = uint32_t(height);
|
||||
params2.frameRateNum = (uint32_t)fps;
|
||||
params2.frameRateDen = 1;
|
||||
params2.enableEncodeAsync = 0;
|
||||
params2.enablePTD = 1;
|
||||
params2.reportSliceOffsets = 0;
|
||||
params2.enableSubFrameWrite = 0;
|
||||
params2.enableExternalMEHints = 0;
|
||||
params2.enableMEOnlyMode = 0;
|
||||
params2.enableWeightedPrediction = 0;
|
||||
params2.enableOutputInVidmem = 0;
|
||||
params2.encodeConfig = ¶ms;
|
||||
params2.maxEncodeWidth = 0;
|
||||
params2.maxEncodeHeight = 0;
|
||||
params2.bufferFormat = NV_ENC_BUFFER_FORMAT_UNDEFINED;
|
||||
NVENC_CHECK(fn.nvEncInitializeEncoder(session_handle, ¶ms2));
|
||||
|
||||
NV_ENC_CREATE_BITSTREAM_BUFFER params3;
|
||||
params3.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
|
||||
NVENC_CHECK(fn.nvEncCreateBitstreamBuffer(session_handle, ¶ms3));
|
||||
bitstreamBuffer = params3.bitstreamBuffer;
|
||||
|
||||
// TODO: cleanup on error
|
||||
this->images.resize(num_images);
|
||||
CU_CHECK(cuCtxPushCurrent(cuda));
|
||||
for (int i = 0; i < num_images; i++) {
|
||||
VkMemoryGetFdInfoKHR getinfo{};
|
||||
getinfo.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR;
|
||||
getinfo.pNext = nullptr;
|
||||
getinfo.memory = memory[i];
|
||||
getinfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT;
|
||||
|
||||
int fd;
|
||||
VkResult res = vk->vkGetMemoryFdKHR(vk->device, &getinfo, &fd);
|
||||
vk_check_error("vkGetMemoryFdKHR", res, );
|
||||
|
||||
VkMemoryRequirements memoryreq;
|
||||
vk->vkGetImageMemoryRequirements(vk->device, images[i], &memoryreq);
|
||||
|
||||
CUexternalMemory extmem;
|
||||
CUDA_EXTERNAL_MEMORY_HANDLE_DESC param{};
|
||||
param.type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD;
|
||||
param.handle.fd = fd;
|
||||
param.size = memoryreq.size;
|
||||
param.flags = 0;
|
||||
CU_CHECK(cuImportExternalMemory(&extmem, ¶m));
|
||||
|
||||
CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC param2{};
|
||||
param2.offset = 0;
|
||||
param2.arrayDesc.Width = (size_t)full_width;
|
||||
param2.arrayDesc.Height = (size_t)full_height, param2.arrayDesc.Depth = 0;
|
||||
param2.arrayDesc.Format = CU_AD_FORMAT_UNSIGNED_INT32, param2.arrayDesc.NumChannels = 1;
|
||||
param2.arrayDesc.Flags = 0; // CUDA_ARRAY3D_SURFACE_LDST,
|
||||
param2.numLevels = 1;
|
||||
CU_CHECK(cuExternalMemoryGetMappedMipmappedArray(&this->images[i].cuda_image, extmem, ¶m2));
|
||||
CU_CHECK(cuMipmappedArrayGetLevel(&this->images[i].cuda_array, this->images[i].cuda_image, 0));
|
||||
}
|
||||
|
||||
CU_CHECK(cuMemAllocPitch(&frame, &pitch, width * 4, height, 4));
|
||||
|
||||
NV_ENC_REGISTER_RESOURCE param3{};
|
||||
param3.version = NV_ENC_REGISTER_RESOURCE_VER;
|
||||
param3.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
|
||||
param3.width = width;
|
||||
param3.height = height;
|
||||
param3.pitch = pitch;
|
||||
param3.resourceToRegister = (void *)frame;
|
||||
param3.bufferFormat = NV_ENC_BUFFER_FORMAT_ARGB;
|
||||
param3.bufferUsage = NV_ENC_INPUT_IMAGE;
|
||||
NVENC_CHECK(fn.nvEncRegisterResource(session_handle, ¶m3));
|
||||
nvenc_resource = param3.registeredResource;
|
||||
CU_CHECK(cuCtxPopCurrent(NULL));
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderNvenc::Encode(int index, bool idr, std::chrono::steady_clock::time_point pts)
|
||||
{
|
||||
CU_CHECK(cuCtxPushCurrent(cuda));
|
||||
CUDA_MEMCPY2D copy{};
|
||||
copy.srcXInBytes = offset_x * 4;
|
||||
copy.srcY = offset_y;
|
||||
copy.srcMemoryType = CU_MEMORYTYPE_ARRAY;
|
||||
copy.srcArray = images[index].cuda_array;
|
||||
copy.dstMemoryType = CU_MEMORYTYPE_DEVICE;
|
||||
copy.dstDevice = frame;
|
||||
copy.dstPitch = pitch;
|
||||
copy.WidthInBytes = width * 4;
|
||||
copy.Height = height;
|
||||
CU_CHECK(cuMemcpy2D(©));
|
||||
|
||||
NV_ENC_MAP_INPUT_RESOURCE param4{};
|
||||
param4.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
|
||||
param4.registeredResource = nvenc_resource;
|
||||
NVENC_CHECK(fn.nvEncMapInputResource(session_handle, ¶m4));
|
||||
|
||||
NV_ENC_PIC_PARAMS param{};
|
||||
param.version = NV_ENC_PIC_PARAMS_VER;
|
||||
param.inputWidth = width;
|
||||
param.inputHeight = height;
|
||||
param.inputPitch = width;
|
||||
param.encodePicFlags = idr ? (uint32_t)NV_ENC_PIC_TYPE_IDR : 0;
|
||||
param.frameIdx = 0;
|
||||
param.inputTimeStamp = 0;
|
||||
param.inputBuffer = param4.mappedResource;
|
||||
param.outputBitstream = bitstreamBuffer;
|
||||
param.bufferFmt = param4.mappedBufferFmt;
|
||||
param.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
|
||||
NVENC_CHECK(fn.nvEncEncodePicture(session_handle, ¶m));
|
||||
|
||||
NV_ENC_LOCK_BITSTREAM param2{};
|
||||
param2.version = NV_ENC_LOCK_BITSTREAM_VER;
|
||||
param2.doNotWait = 0;
|
||||
param2.outputBitstream = bitstreamBuffer;
|
||||
NVENC_CHECK(fn.nvEncLockBitstream(session_handle, ¶m2));
|
||||
|
||||
SendData(
|
||||
{(uint8_t *)param2.bitstreamBufferPtr, (uint8_t *)param2.bitstreamBufferPtr + param2.bitstreamSizeInBytes});
|
||||
|
||||
NVENC_CHECK(fn.nvEncUnlockBitstream(session_handle, bitstreamBuffer));
|
||||
|
||||
CU_CHECK(cuCtxPopCurrent(NULL));
|
||||
}
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "video_encoder.h"
|
||||
#include "external/nvEncodeAPI.h"
|
||||
#include <cuda.h>
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
class VideoEncoderNvenc : public VideoEncoder
|
||||
{
|
||||
vk_bundle *vk;
|
||||
// relevant part of the input image to encode
|
||||
int offset_x;
|
||||
int offset_y;
|
||||
int width;
|
||||
int height;
|
||||
|
||||
NV_ENCODE_API_FUNCTION_LIST fn;
|
||||
CUcontext cuda;
|
||||
void *session_handle;
|
||||
NV_ENC_OUTPUT_PTR bitstreamBuffer;
|
||||
|
||||
struct image_data
|
||||
{
|
||||
CUmipmappedArray cuda_image;
|
||||
CUarray cuda_array;
|
||||
};
|
||||
std::vector<image_data> images;
|
||||
CUdeviceptr frame;
|
||||
size_t pitch;
|
||||
NV_ENC_REGISTERED_PTR nvenc_resource;
|
||||
video_codec codec;
|
||||
float fps;
|
||||
int bitrate;
|
||||
|
||||
bool supports_frame_invalidation;
|
||||
|
||||
public:
|
||||
VideoEncoderNvenc(vk_bundle *vk, const encoder_settings &settings, float fps);
|
||||
|
||||
void
|
||||
SetImages(int width,
|
||||
int height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage *images,
|
||||
VkImageView *views,
|
||||
VkDeviceMemory *memory) override;
|
||||
|
||||
void
|
||||
Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) override;
|
||||
};
|
||||
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,157 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "video_encoder_x264.h"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
void
|
||||
VideoEncoderX264::ProcessCb(x264_t *h, x264_nal_t *nal, void *opaque)
|
||||
{
|
||||
VideoEncoderX264 *self = (VideoEncoderX264 *)opaque;
|
||||
std::vector<uint8_t> data(nal->i_payload * 3 / 2 + 5 + 64, 0);
|
||||
x264_nal_encode(h, data.data(), nal);
|
||||
data.resize(nal->i_payload);
|
||||
switch (nal->i_type) {
|
||||
case NAL_SPS:
|
||||
case NAL_PPS: self->SendData(std::move(data)); break;
|
||||
case NAL_SLICE:
|
||||
case NAL_SLICE_DPA:
|
||||
case NAL_SLICE_DPB:
|
||||
case NAL_SLICE_DPC:
|
||||
case NAL_SLICE_IDR: self->ProcessNal({nal->i_first_mb, nal->i_last_mb, std::move(data)});
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderX264::ProcessNal(pending_nal &&nal)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
if (nal.first_mb == next_mb) {
|
||||
next_mb = nal.last_mb + 1;
|
||||
SendData(std::move(nal.data));
|
||||
} else {
|
||||
InsertInPendingNal(std::move(nal));
|
||||
}
|
||||
while ((not pending_nals.empty()) and pending_nals.front().first_mb == next_mb) {
|
||||
SendData(std::move(pending_nals.front().data));
|
||||
next_mb = pending_nals.front().last_mb + 1;
|
||||
pending_nals.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderX264::InsertInPendingNal(pending_nal &&nal)
|
||||
{
|
||||
auto it = pending_nals.begin();
|
||||
auto end = pending_nals.end();
|
||||
for (; it != end; ++it) {
|
||||
if (it->first_mb > nal.last_mb) {
|
||||
pending_nals.insert(it, std::move(nal));
|
||||
return;
|
||||
}
|
||||
}
|
||||
pending_nals.push_back(std::move(nal));
|
||||
}
|
||||
|
||||
VideoEncoderX264::VideoEncoderX264(
|
||||
vk_bundle *vk, encoder_settings &settings, int input_width, int input_height, float fps)
|
||||
: vk(vk)
|
||||
{
|
||||
if (settings.codec != h264) {
|
||||
U_LOG_W("requested x264 encoder with codec != h264");
|
||||
settings.codec = h264;
|
||||
}
|
||||
|
||||
// encoder requires width and height to be even
|
||||
settings.width += settings.width % 2;
|
||||
settings.height += settings.height % 2;
|
||||
|
||||
converter =
|
||||
std::make_unique<YuvConverter>(vk, VkExtent3D{uint32_t(settings.width), uint32_t(settings.height), 1},
|
||||
settings.offset_x, settings.offset_y, input_width, input_height);
|
||||
|
||||
x264_param_default_preset(¶m, "ultrafast", "zerolatency");
|
||||
param.nalu_process = &ProcessCb;
|
||||
// param.i_slice_max_size = 1300;
|
||||
param.i_slice_count = 32;
|
||||
param.i_width = settings.width;
|
||||
param.i_height = settings.height;
|
||||
param.i_log_level = X264_LOG_WARNING;
|
||||
param.i_fps_num = fps * 1'000'000;
|
||||
param.i_fps_den = 1'000'000;
|
||||
param.b_repeat_headers = 1;
|
||||
param.b_aud = 0;
|
||||
|
||||
// colour definitions, actually ignored by decoder
|
||||
using namespace to_headset;
|
||||
param.vui.b_fullrange = 0;
|
||||
param.vui.i_colorprim = 1; // BT.709
|
||||
param.vui.i_colmatrix = 1; // BT.709
|
||||
param.vui.i_transfer = 13; // sRGB
|
||||
|
||||
param.vui.i_sar_width = settings.width;
|
||||
param.vui.i_sar_height = settings.height;
|
||||
param.rc.i_rc_method = X264_RC_ABR;
|
||||
param.rc.i_bitrate = settings.bitrate / 1000; // x264 uses kbit/s
|
||||
enc = x264_encoder_open(¶m);
|
||||
if (not enc) {
|
||||
throw std::runtime_error("failed to create x264 encoder");
|
||||
}
|
||||
|
||||
assert(x264_encoder_maximum_delayed_frames(enc) == 0);
|
||||
|
||||
|
||||
auto &pic = pic_in;
|
||||
x264_picture_init(&pic);
|
||||
pic.opaque = this;
|
||||
pic.img.i_csp = X264_CSP_NV12;
|
||||
pic.img.i_plane = 2;
|
||||
|
||||
pic.img.i_stride[0] = converter->y.stride;
|
||||
pic.img.plane[0] = (uint8_t *)converter->y.mapped_memory;
|
||||
pic.img.i_stride[1] = converter->uv.stride;
|
||||
pic.img.plane[1] = (uint8_t *)converter->uv.mapped_memory;
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderX264::SetImages(
|
||||
int width, int height, VkFormat format, int num_images, VkImage *images, VkImageView *views, VkDeviceMemory *memory)
|
||||
{
|
||||
converter->SetImages(num_images, images, views);
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderX264::PresentImage(int index, VkCommandBuffer *out_buffer)
|
||||
{
|
||||
*out_buffer = converter->command_buffers[index];
|
||||
}
|
||||
|
||||
void
|
||||
VideoEncoderX264::Encode(int index, bool idr, std::chrono::steady_clock::time_point pts)
|
||||
{
|
||||
int num_nal;
|
||||
x264_nal_t *nal;
|
||||
pic_in.i_type = idr ? X264_TYPE_IDR : X264_TYPE_AUTO;
|
||||
pic_in.i_pts = pts.time_since_epoch().count();
|
||||
next_mb = 0;
|
||||
assert(pending_nals.empty());
|
||||
int size = x264_encoder_encode(enc, &nal, &num_nal, &pic_in, &pic_out);
|
||||
if (size < 0) {
|
||||
U_LOG_W("x264_encoder_encode failed: %d", size);
|
||||
return;
|
||||
}
|
||||
if (size == 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
VideoEncoderX264::~VideoEncoderX264()
|
||||
{
|
||||
x264_encoder_close(enc);
|
||||
}
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,69 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "video_encoder.h"
|
||||
#include "x264.h"
|
||||
#include "yuv_converter.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <list>
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
class VideoEncoderX264 : public VideoEncoder
|
||||
{
|
||||
x264_param_t param = {};
|
||||
x264_t *enc;
|
||||
|
||||
vk_bundle *vk;
|
||||
x264_picture_t pic_in;
|
||||
x264_picture_t pic_out = {};
|
||||
std::unique_ptr<YuvConverter> converter;
|
||||
|
||||
struct pending_nal
|
||||
{
|
||||
int first_mb;
|
||||
int last_mb;
|
||||
std::vector<uint8_t> data;
|
||||
};
|
||||
|
||||
std::mutex mutex;
|
||||
int next_mb;
|
||||
std::list<pending_nal> pending_nals;
|
||||
|
||||
public:
|
||||
VideoEncoderX264(vk_bundle *vk, encoder_settings &settings, int input_width, int input_height, float fps);
|
||||
|
||||
void
|
||||
SetImages(int width,
|
||||
int height,
|
||||
VkFormat format,
|
||||
int num_images,
|
||||
VkImage *images,
|
||||
VkImageView *views,
|
||||
VkDeviceMemory *memory) override;
|
||||
|
||||
void
|
||||
PresentImage(int index, VkCommandBuffer *out_buffer) override;
|
||||
|
||||
void
|
||||
Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) override;
|
||||
|
||||
~VideoEncoderX264();
|
||||
|
||||
private:
|
||||
static void
|
||||
ProcessCb(x264_t *h, x264_nal_t *nal, void *opaque);
|
||||
|
||||
void
|
||||
ProcessNal(pending_nal &&nal);
|
||||
|
||||
void
|
||||
InsertInPendingNal(pending_nal &&nal);
|
||||
};
|
||||
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "view_list.h"
|
||||
#include "pose_list.h"
|
||||
#include "util/u_logging.h"
|
||||
#include "xrt_cast.h"
|
||||
|
||||
tracked_views
|
||||
interpolate(const tracked_views &a, const tracked_views &b, float t)
|
||||
{
|
||||
tracked_views result = a;
|
||||
result.relation = interpolate(a.relation, b.relation, t);
|
||||
return result;
|
||||
}
|
||||
|
||||
tracked_views
|
||||
extrapolate(const tracked_views &a, const tracked_views &b, uint64_t ta, uint64_t tb, uint64_t t)
|
||||
{
|
||||
tracked_views result = a;
|
||||
result.relation = extrapolate(a.relation, b.relation, ta, tb, t);
|
||||
return result;
|
||||
}
|
||||
|
||||
void
|
||||
view_list::update_tracking(const from_headset::tracking &tracking, const clock_offset &offset)
|
||||
{
|
||||
for (const auto &pose : tracking.device_poses) {
|
||||
if (pose.device != device_id::HEAD)
|
||||
continue;
|
||||
|
||||
tracked_views view{};
|
||||
|
||||
view.relation = pose_list::convert_pose(pose);
|
||||
view.flags = tracking.flags;
|
||||
|
||||
for (size_t eye = 0; eye < 2; ++eye) {
|
||||
view.poses[eye] = xrt_cast(tracking.views[eye].pose);
|
||||
view.fovs[eye] = xrt_cast(tracking.views[eye].fov);
|
||||
}
|
||||
|
||||
add_sample(tracking.timestamp, view, offset);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "pose_list.h"
|
||||
#include "wivrn_session.h"
|
||||
|
||||
struct tracked_views
|
||||
{
|
||||
XrViewStateFlags flags;
|
||||
xrt_space_relation relation = XRT_SPACE_RELATION_ZERO;
|
||||
std::array<xrt_pose, 2> poses;
|
||||
std::array<xrt_fov, 2> fovs;
|
||||
};
|
||||
|
||||
tracked_views
|
||||
interpolate(const tracked_views &a, const tracked_views &b, float t);
|
||||
|
||||
tracked_views
|
||||
extrapolate(const tracked_views &a, const tracked_views &b, uint64_t ta, uint64_t tb, uint64_t t);
|
||||
|
||||
class view_list : public history<tracked_views>
|
||||
{
|
||||
public:
|
||||
void
|
||||
update_tracking(const from_headset::tracking &tracking, const clock_offset &offset);
|
||||
};
|
||||
@@ -0,0 +1,742 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "wivrn_comp_target.h"
|
||||
#include "main/comp_compositor.h"
|
||||
#include "math/m_space.h"
|
||||
#include "video_encoder.h"
|
||||
#include "util/u_pacing.h"
|
||||
#include "xrt/xrt_config_have.h"
|
||||
#include "xrt_cast.h"
|
||||
#include <atomic>
|
||||
#include <list>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <condition_variable>
|
||||
|
||||
static const uint8_t image_free = 0;
|
||||
static const uint8_t image_acquired = 1;
|
||||
|
||||
struct pseudo_swapchain
|
||||
{
|
||||
|
||||
struct pseudo_swapchain_memory
|
||||
{
|
||||
VkFence fence;
|
||||
VkDeviceMemory memory;
|
||||
uint8_t status; // bitmask of consumer status, index 0 for acquired, the rest for each encoder
|
||||
uint64_t frame_index;
|
||||
to_headset::video_stream_data_shard::view_info_t view_info{};
|
||||
} * images{};
|
||||
std::mutex mutex;
|
||||
std::condition_variable cv;
|
||||
};
|
||||
|
||||
struct wivrn_comp_target : public comp_target
|
||||
{
|
||||
//! Compositor frame pacing helper
|
||||
struct u_pacing_compositor *upc{};
|
||||
|
||||
float fps;
|
||||
|
||||
int64_t current_frame_id;
|
||||
|
||||
// Monotonic counter, for video stream
|
||||
uint64_t frame_index = 0;
|
||||
|
||||
struct pseudo_swapchain psc;
|
||||
|
||||
VkColorSpaceKHR color_space;
|
||||
|
||||
struct encoder_thread
|
||||
{
|
||||
int index;
|
||||
os_thread_helper thread;
|
||||
|
||||
encoder_thread()
|
||||
{
|
||||
os_thread_helper_init(&thread);
|
||||
}
|
||||
~encoder_thread()
|
||||
{
|
||||
os_thread_helper_stop_and_wait(&thread);
|
||||
os_thread_helper_destroy(&thread);
|
||||
}
|
||||
};
|
||||
std::list<encoder_thread> encoder_threads;
|
||||
std::vector<std::shared_ptr<VideoEncoder>> encoders;
|
||||
|
||||
std::shared_ptr<xrt::drivers::wivrn::wivrn_session> cnx;
|
||||
};
|
||||
|
||||
|
||||
static void
|
||||
target_init_semaphores(struct wivrn_comp_target *cn);
|
||||
|
||||
static void
|
||||
target_fini_semaphores(struct wivrn_comp_target *cn);
|
||||
|
||||
static inline struct vk_bundle *
|
||||
get_vk(struct wivrn_comp_target *cn)
|
||||
{
|
||||
return &cn->c->base.vk;
|
||||
}
|
||||
|
||||
static void
|
||||
destroy_images(struct wivrn_comp_target *cn)
|
||||
{
|
||||
if (cn->images == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
cn->encoder_threads.clear();
|
||||
cn->encoders.clear();
|
||||
|
||||
struct vk_bundle *vk = get_vk(cn);
|
||||
|
||||
for (uint32_t i = 0; i < cn->image_count; i++) {
|
||||
if (cn->images[i].view == VK_NULL_HANDLE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
vk->vkDestroyImageView(vk->device, cn->images[i].view, NULL);
|
||||
vk->vkDestroyImage(vk->device, cn->images[i].handle, NULL);
|
||||
vk->vkFreeMemory(vk->device, cn->psc.images[i].memory, NULL);
|
||||
}
|
||||
|
||||
free(cn->images);
|
||||
free(cn->psc.images);
|
||||
cn->images = NULL;
|
||||
cn->psc.images = NULL;
|
||||
|
||||
target_fini_semaphores(cn);
|
||||
}
|
||||
|
||||
struct encoder_thread_param
|
||||
{
|
||||
wivrn_comp_target *cn;
|
||||
wivrn_comp_target::encoder_thread *thread;
|
||||
std::vector<std::shared_ptr<VideoEncoder>> encoders;
|
||||
};
|
||||
|
||||
static void *
|
||||
comp_wivrn_present_thread(void *void_param);
|
||||
|
||||
static void
|
||||
create_encoders(wivrn_comp_target *cn, std::vector<encoder_settings> &_settings)
|
||||
{
|
||||
auto vk = get_vk(cn);
|
||||
assert(cn->encoders.empty());
|
||||
assert(cn->encoder_threads.empty());
|
||||
|
||||
to_headset::video_stream_description desc{};
|
||||
desc.width = cn->width;
|
||||
desc.height = cn->height;
|
||||
desc.fps = cn->fps;
|
||||
|
||||
std::map<int, encoder_thread_param> thread_params;
|
||||
|
||||
for (auto &settings : _settings) {
|
||||
uint8_t stream_index = cn->encoders.size();
|
||||
auto &encoder = cn->encoders.emplace_back(
|
||||
VideoEncoder::Create(vk, settings, stream_index, desc.width, desc.height, desc.fps));
|
||||
desc.items.push_back(settings);
|
||||
|
||||
std::vector<VkImage> images(cn->image_count);
|
||||
std::vector<VkDeviceMemory> memory(cn->image_count);
|
||||
std::vector<VkImageView> views(cn->image_count);
|
||||
|
||||
for (size_t j = 0; j < cn->image_count; j++) {
|
||||
images[j] = cn->images[j].handle;
|
||||
memory[j] = cn->psc.images[j].memory;
|
||||
views[j] = cn->images[j].view;
|
||||
}
|
||||
encoder->SetImages(cn->width, cn->height, cn->format, cn->image_count, images.data(), views.data(),
|
||||
memory.data());
|
||||
|
||||
thread_params[settings.group].encoders.emplace_back(encoder);
|
||||
}
|
||||
|
||||
for (auto &[group, params] : thread_params) {
|
||||
auto params_ptr = new encoder_thread_param(params);
|
||||
auto &thread = cn->encoder_threads.emplace_back();
|
||||
thread.index = cn->encoder_threads.size() - 1;
|
||||
params_ptr->thread = &thread;
|
||||
params_ptr->cn = cn;
|
||||
os_thread_helper_start(&thread.thread, comp_wivrn_present_thread, params_ptr);
|
||||
std::string name = "encoder " + std::to_string(group);
|
||||
os_thread_helper_name(&thread.thread, name.c_str());
|
||||
}
|
||||
cn->cnx->send_control(desc);
|
||||
}
|
||||
|
||||
class drm_image_modifier_helper
|
||||
{
|
||||
VkImageDrmFormatModifierListCreateInfoEXT drm_info{};
|
||||
std::vector<uint64_t> modifiers;
|
||||
|
||||
public:
|
||||
void *pNext = nullptr;
|
||||
drm_image_modifier_helper(vk_bundle *vk, VkFormat format, VkImageTiling tiling)
|
||||
{
|
||||
if (tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT)
|
||||
return;
|
||||
|
||||
VkDrmFormatModifierPropertiesListEXT drm_list{};
|
||||
drm_list.sType = VK_STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT;
|
||||
|
||||
VkFormatProperties2 format_prop{};
|
||||
format_prop.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2;
|
||||
format_prop.pNext = &drm_list;
|
||||
|
||||
vk->vkGetPhysicalDeviceFormatProperties2(vk->physical_device, format, &format_prop);
|
||||
|
||||
std::vector<VkDrmFormatModifierPropertiesEXT> properties(drm_list.drmFormatModifierCount);
|
||||
drm_list.pDrmFormatModifierProperties = properties.data();
|
||||
|
||||
vk->vkGetPhysicalDeviceFormatProperties2(vk->physical_device, format, &format_prop);
|
||||
|
||||
|
||||
VkFormatFeatureFlags required_features = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
|
||||
VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT |
|
||||
VK_FORMAT_FEATURE_TRANSFER_SRC_BIT;
|
||||
for (const auto &mod : properties) {
|
||||
if ((mod.drmFormatModifierTilingFeatures & required_features) == required_features)
|
||||
modifiers.push_back(mod.drmFormatModifier);
|
||||
}
|
||||
|
||||
assert(not modifiers.empty());
|
||||
|
||||
drm_info.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT;
|
||||
drm_info.drmFormatModifierCount = modifiers.size();
|
||||
drm_info.pDrmFormatModifiers = modifiers.data();
|
||||
|
||||
pNext = &drm_info;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
static VkResult
|
||||
create_images(struct wivrn_comp_target *cn, VkImageUsageFlags flags, VkImageTiling tiling)
|
||||
{
|
||||
struct vk_bundle *vk = get_vk(cn);
|
||||
|
||||
assert(cn->image_count > 0);
|
||||
COMP_DEBUG(cn->c, "Creating %d images.", cn->image_count);
|
||||
|
||||
destroy_images(cn);
|
||||
|
||||
cn->images = U_TYPED_ARRAY_CALLOC(struct comp_target_image, cn->image_count);
|
||||
cn->psc.images = U_TYPED_ARRAY_CALLOC(pseudo_swapchain::pseudo_swapchain_memory, cn->image_count);
|
||||
|
||||
VkImageSubresourceRange subresource_range{};
|
||||
subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
subresource_range.baseMipLevel = 0;
|
||||
subresource_range.levelCount = 1;
|
||||
subresource_range.baseArrayLayer = 0;
|
||||
subresource_range.layerCount = 1;
|
||||
|
||||
flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
|
||||
|
||||
drm_image_modifier_helper drm_list(vk, cn->format, tiling);
|
||||
|
||||
for (uint32_t i = 0; i < cn->image_count; i++) {
|
||||
auto &image = cn->images[i].handle;
|
||||
auto &image_view = cn->images[i].view;
|
||||
auto &memory = cn->psc.images[i].memory;
|
||||
|
||||
VkExtent3D extent{cn->width, cn->height, 1};
|
||||
|
||||
VkImageCreateInfo image_info{};
|
||||
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
|
||||
image_info.pNext = drm_list.pNext;
|
||||
image_info.imageType = VK_IMAGE_TYPE_2D;
|
||||
image_info.format = cn->format;
|
||||
image_info.extent = extent;
|
||||
image_info.mipLevels = 1;
|
||||
image_info.arrayLayers = 1;
|
||||
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
|
||||
image_info.tiling = tiling;
|
||||
image_info.usage = flags;
|
||||
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
image_info.queueFamilyIndexCount = 0;
|
||||
image_info.pQueueFamilyIndices = NULL;
|
||||
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
|
||||
VkResult res = vk->vkCreateImage(vk->device, &image_info, NULL, &image);
|
||||
vk_check_error("vkCreateImage", res, res);
|
||||
|
||||
VkMemoryDedicatedAllocateInfoKHR dedicated_allocate_info{};
|
||||
dedicated_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
|
||||
dedicated_allocate_info.image = image;
|
||||
|
||||
VkDeviceSize size;
|
||||
res = vk_alloc_and_bind_image_memory(vk, image, -1, &dedicated_allocate_info, "wivrn_comp_target",
|
||||
&memory, &size);
|
||||
vk_check_error("vk_alloc_and_bind_image_memory", res, res);
|
||||
|
||||
res = vk_create_view( //
|
||||
vk, // vk_bundle
|
||||
image, // image
|
||||
VK_IMAGE_VIEW_TYPE_2D, // type
|
||||
cn->format, // format
|
||||
subresource_range, // subresource_range
|
||||
&image_view); // out_view
|
||||
vk_check_error("vk_create_view", res, res);
|
||||
|
||||
VkFenceCreateInfo createinfo{};
|
||||
createinfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
|
||||
createinfo.pNext = NULL;
|
||||
createinfo.flags = 0;
|
||||
|
||||
res = vk->vkCreateFence(vk->device, &createinfo, NULL, &cn->psc.images[i].fence);
|
||||
|
||||
vk_check_error("vkCreateFence", res, res);
|
||||
}
|
||||
|
||||
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static bool
|
||||
comp_wivrn_init_pre_vulkan(struct comp_target *ct)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
comp_wivrn_init_post_vulkan(struct comp_target *ct, uint32_t preferred_width, uint32_t preferred_height)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
comp_wivrn_check_ready(struct comp_target *ct)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
static void
|
||||
target_fini_semaphores(struct wivrn_comp_target *cn)
|
||||
{
|
||||
struct vk_bundle *vk = get_vk(cn);
|
||||
|
||||
if (cn->semaphores.present_complete != VK_NULL_HANDLE) {
|
||||
vk->vkDestroySemaphore(vk->device, cn->semaphores.present_complete, NULL);
|
||||
cn->semaphores.present_complete = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
if (cn->semaphores.render_complete != VK_NULL_HANDLE) {
|
||||
vk->vkDestroySemaphore(vk->device, cn->semaphores.render_complete, NULL);
|
||||
cn->semaphores.render_complete = VK_NULL_HANDLE;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
target_init_semaphores(struct wivrn_comp_target *cn)
|
||||
{
|
||||
struct vk_bundle *vk = get_vk(cn);
|
||||
VkResult ret;
|
||||
|
||||
target_fini_semaphores(cn);
|
||||
|
||||
VkSemaphoreCreateInfo info = {
|
||||
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
|
||||
};
|
||||
|
||||
ret = vk->vkCreateSemaphore(vk->device, &info, NULL, &cn->semaphores.present_complete);
|
||||
if (ret != VK_SUCCESS) {
|
||||
COMP_ERROR(cn->c, "vkCreateSemaphore: %s", vk_result_string(ret));
|
||||
}
|
||||
|
||||
cn->semaphores.render_complete_is_timeline = false;
|
||||
ret = vk->vkCreateSemaphore(vk->device, &info, NULL, &cn->semaphores.render_complete);
|
||||
if (ret != VK_SUCCESS) {
|
||||
COMP_ERROR(cn->c, "vkCreateSemaphore: %s", vk_result_string(ret));
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
comp_wivrn_create_images(struct comp_target *ct,
|
||||
uint32_t preferred_width,
|
||||
uint32_t preferred_height,
|
||||
VkFormat preferred_color_format,
|
||||
VkColorSpaceKHR preferred_color_space,
|
||||
VkImageUsageFlags image_usage,
|
||||
VkPresentModeKHR present_mode)
|
||||
{
|
||||
struct wivrn_comp_target *cn = (struct wivrn_comp_target *)ct;
|
||||
|
||||
uint64_t now_ns = os_monotonic_get_ns();
|
||||
if (cn->upc == NULL) {
|
||||
u_pc_fake_create(ct->c->settings.nominal_frame_interval_ns, now_ns, &cn->upc);
|
||||
}
|
||||
|
||||
// Free old images.
|
||||
destroy_images(cn);
|
||||
|
||||
target_init_semaphores(cn);
|
||||
|
||||
ct->format = preferred_color_format;
|
||||
ct->width = preferred_width;
|
||||
ct->height = preferred_height;
|
||||
ct->surface_transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
|
||||
|
||||
cn->image_count = 3;
|
||||
cn->format = preferred_color_format;
|
||||
cn->width = preferred_width;
|
||||
cn->height = preferred_height;
|
||||
cn->color_space = preferred_color_space;
|
||||
|
||||
auto settings = get_encoder_settings(get_vk(cn), cn->width, cn->height);
|
||||
|
||||
VkResult res = create_images(cn, image_usage, get_required_tiling(get_vk(cn), settings));
|
||||
if (vk_has_error(res, "create_images", __FILE__, __LINE__)) {
|
||||
// TODO
|
||||
abort();
|
||||
}
|
||||
|
||||
try {
|
||||
create_encoders(cn, settings);
|
||||
} catch (const std::exception &e) {
|
||||
U_LOG_E("Failed to create video encoder: %s", e.what());
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
static bool
|
||||
comp_wivrn_has_images(struct comp_target *ct)
|
||||
{
|
||||
return ct->images;
|
||||
}
|
||||
|
||||
static VkResult
|
||||
comp_wivrn_acquire(struct comp_target *ct, uint32_t *out_index)
|
||||
{
|
||||
struct wivrn_comp_target *cn = (struct wivrn_comp_target *)ct;
|
||||
struct vk_bundle *vk = get_vk(cn);
|
||||
|
||||
VkSubmitInfo submit{};
|
||||
submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
submit.pNext = NULL;
|
||||
submit.waitSemaphoreCount = 0;
|
||||
submit.pWaitSemaphores = NULL;
|
||||
submit.pWaitDstStageMask = NULL;
|
||||
submit.commandBufferCount = 0;
|
||||
submit.pCommandBuffers = NULL;
|
||||
submit.signalSemaphoreCount = 1;
|
||||
submit.pSignalSemaphores = &cn->semaphores.present_complete;
|
||||
|
||||
VkResult res = vk_locked_submit(vk, vk->queue, 1, &submit, VK_NULL_HANDLE);
|
||||
vk_check_error("vk_locked_submit", res, res);
|
||||
|
||||
res = VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
|
||||
while (res != VK_SUCCESS) {
|
||||
std::lock_guard lock(cn->psc.mutex);
|
||||
for (uint32_t i = 0; i < ct->image_count; i++) {
|
||||
if (cn->psc.images[i].status == image_free) {
|
||||
cn->psc.images[i].status = image_acquired;
|
||||
|
||||
*out_index = i;
|
||||
res = VK_SUCCESS;
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
static void *
|
||||
comp_wivrn_present_thread(void *void_param)
|
||||
{
|
||||
std::unique_ptr<encoder_thread_param> param((encoder_thread_param *)void_param);
|
||||
struct wivrn_comp_target *cn = param->cn;
|
||||
struct vk_bundle *vk = get_vk(cn);
|
||||
U_LOG_I("Starting encoder thread %d", param->thread->index);
|
||||
|
||||
uint8_t status_bit = 1 << (param->thread->index + 1);
|
||||
|
||||
std::vector<VkFence> fences(cn->image_count);
|
||||
std::vector<int> indices(cn->image_count);
|
||||
while (os_thread_helper_is_running(¶m->thread->thread)) {
|
||||
int presenting_index = -1;
|
||||
int nb_fences = 0;
|
||||
{
|
||||
std::unique_lock lock(cn->psc.mutex);
|
||||
|
||||
uint64_t timestamp = 0;
|
||||
|
||||
for (uint32_t i = 0; i < cn->image_count; i++) {
|
||||
if (cn->psc.images[i].status & status_bit) {
|
||||
if (timestamp < cn->psc.images[i].view_info.display_time) {
|
||||
presenting_index = i;
|
||||
}
|
||||
indices[nb_fences] = i;
|
||||
fences[nb_fences++] = cn->psc.images[i].fence;
|
||||
}
|
||||
}
|
||||
|
||||
if (presenting_index < 0) {
|
||||
// condition variable is not notified when we want to stop thread,
|
||||
// use a timeout, but longer than a typical frame
|
||||
cn->psc.cv.wait_for(lock, std::chrono::milliseconds(50));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
VkResult res = vk->vkWaitForFences(vk->device, nb_fences, fences.data(), VK_TRUE, UINT64_MAX);
|
||||
vk_check_error("vkWaitForFences", res, NULL);
|
||||
|
||||
const auto &psc_image = cn->psc.images[presenting_index];
|
||||
try {
|
||||
for (auto &encoder : param->encoders) {
|
||||
bool idr_requested = false;
|
||||
|
||||
encoder->Encode(*cn->cnx, psc_image.view_info, psc_image.frame_index, presenting_index,
|
||||
idr_requested);
|
||||
}
|
||||
}
|
||||
catch(...) {
|
||||
// Ignore errors
|
||||
}
|
||||
|
||||
std::lock_guard lock(cn->psc.mutex);
|
||||
for (int i = 0; i < nb_fences; i++) {
|
||||
cn->psc.images[indices[i]].status &= ~status_bit;
|
||||
}
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static VkResult
|
||||
comp_wivrn_present(struct comp_target *ct,
|
||||
VkQueue queue,
|
||||
uint32_t index,
|
||||
uint64_t timeline_semaphore_value,
|
||||
uint64_t desired_present_time_ns,
|
||||
uint64_t present_slop_ns)
|
||||
{
|
||||
struct wivrn_comp_target *cn = (struct wivrn_comp_target *)ct;
|
||||
struct vk_bundle *vk = get_vk(cn);
|
||||
|
||||
assert(index < cn->image_count);
|
||||
|
||||
if (cn->c->base.slot.layer_count == 0) {
|
||||
// TODO: Tell the headset that there is no image to display
|
||||
assert(cn->psc.images[index].status == image_acquired);
|
||||
cn->psc.images[index].status = image_free;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
assert(index < ct->image_count);
|
||||
assert(ct->images != NULL);
|
||||
|
||||
std::vector<VkCommandBuffer> cmdBuffers;
|
||||
|
||||
VkCommandBuffer cmdBuffer;
|
||||
VkResult res = vk_cmd_buffer_create_and_begin(vk, &cmdBuffer);
|
||||
vk_check_error("vk_cmd_buffer_create_and_begin", res, res);
|
||||
|
||||
VkImageSubresourceRange first_color_level_subresource_range{};
|
||||
first_color_level_subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
first_color_level_subresource_range.baseMipLevel = 0;
|
||||
first_color_level_subresource_range.levelCount = 1;
|
||||
first_color_level_subresource_range.baseArrayLayer = 0;
|
||||
first_color_level_subresource_range.layerCount = 1;
|
||||
vk_cmd_image_barrier_gpu_locked(vk, cmdBuffer, ct->images[index].handle, 0, VK_ACCESS_SHADER_READ_BIT,
|
||||
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_GENERAL,
|
||||
first_color_level_subresource_range);
|
||||
|
||||
res = vk->vkEndCommandBuffer(cmdBuffer);
|
||||
vk_check_error("vkEndCommandBuffer", res, res);
|
||||
cmdBuffers.push_back(cmdBuffer);
|
||||
|
||||
for (auto &encoder : cn->encoders) {
|
||||
VkCommandBuffer cmdBuffer = VK_NULL_HANDLE;
|
||||
encoder->PresentImage(index, &cmdBuffer);
|
||||
if (cmdBuffer != VK_NULL_HANDLE)
|
||||
cmdBuffers.push_back(cmdBuffer);
|
||||
}
|
||||
|
||||
VkPipelineStageFlags sem_flags = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
|
||||
VkSubmitInfo submit{};
|
||||
submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
submit.pNext = NULL;
|
||||
submit.waitSemaphoreCount = 1;
|
||||
submit.pWaitSemaphores = &cn->semaphores.render_complete;
|
||||
submit.pWaitDstStageMask = &sem_flags;
|
||||
submit.commandBufferCount = cmdBuffers.size();
|
||||
submit.pCommandBuffers = cmdBuffers.data();
|
||||
submit.signalSemaphoreCount = 0;
|
||||
submit.pSignalSemaphores = NULL;
|
||||
|
||||
std::lock_guard lock(cn->psc.mutex);
|
||||
res = vk->vkResetFences(vk->device, 1, &cn->psc.images[index].fence);
|
||||
vk_check_error("vkResetFences", res, res);
|
||||
res = vk_locked_submit(vk, vk->queue, 1, &submit, cn->psc.images[index].fence);
|
||||
vk_check_error("vk_locked_submit", res, res);
|
||||
|
||||
assert(cn->psc.images[index].status == image_acquired);
|
||||
cn->frame_index++;
|
||||
// set bits to 1 for index 1..num encoder threads + 1
|
||||
cn->psc.images[index].status = (1 << (cn->encoder_threads.size() + 1)) - 2;
|
||||
cn->psc.images[index].frame_index = cn->frame_index;
|
||||
|
||||
auto &view_info = cn->psc.images[index].view_info;
|
||||
view_info.display_time = cn->cnx->get_offset().to_headset(desired_present_time_ns).count();
|
||||
for (int eye = 0; eye < 2; ++eye) {
|
||||
xrt_relation_chain xrc{};
|
||||
xrt_space_relation result{};
|
||||
m_relation_chain_push_pose_if_not_identity(&xrc, &cn->c->base.slot.poses[eye]);
|
||||
m_relation_chain_push_relation(&xrc, &cn->c->base.slot.head_relation);
|
||||
m_relation_chain_resolve(&xrc, &result);
|
||||
view_info.fov[eye] = xrt_cast(cn->c->base.slot.fovs[eye]);
|
||||
view_info.pose[eye] = xrt_cast(result.pose);
|
||||
}
|
||||
cn->psc.cv.notify_all();
|
||||
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void
|
||||
comp_wivrn_flush(struct comp_target *ct)
|
||||
{
|
||||
(void)ct;
|
||||
}
|
||||
|
||||
static void
|
||||
comp_wivrn_calc_frame_pacing(struct comp_target *ct,
|
||||
int64_t *out_frame_id,
|
||||
uint64_t *out_wake_up_time_ns,
|
||||
uint64_t *out_desired_present_time_ns,
|
||||
uint64_t *out_present_slop_ns,
|
||||
uint64_t *out_predicted_display_time_ns)
|
||||
{
|
||||
struct wivrn_comp_target *cn = (struct wivrn_comp_target *)ct;
|
||||
|
||||
int64_t frame_id /*= ++cn->current_frame_id*/; //-1;
|
||||
uint64_t desired_present_time_ns /*= cn->next_frame_timestamp*/;
|
||||
uint64_t wake_up_time_ns /*= desired_present_time_ns - 5 * U_TIME_1MS_IN_NS*/;
|
||||
uint64_t present_slop_ns /*= U_TIME_HALF_MS_IN_NS*/;
|
||||
uint64_t predicted_display_time_ns /*= desired_present_time_ns + 5 * U_TIME_1MS_IN_NS*/;
|
||||
|
||||
#if 1
|
||||
uint64_t predicted_display_period_ns = U_TIME_1S_IN_NS / 60;
|
||||
uint64_t min_display_period_ns = predicted_display_period_ns;
|
||||
uint64_t now_ns = os_monotonic_get_ns();
|
||||
|
||||
u_pc_predict(cn->upc, //
|
||||
now_ns, //
|
||||
&frame_id, //
|
||||
&wake_up_time_ns, //
|
||||
&desired_present_time_ns, //
|
||||
&present_slop_ns, //
|
||||
&predicted_display_time_ns, //
|
||||
&predicted_display_period_ns, //
|
||||
&min_display_period_ns); //
|
||||
|
||||
cn->current_frame_id = frame_id;
|
||||
|
||||
#endif
|
||||
|
||||
*out_frame_id = frame_id;
|
||||
*out_wake_up_time_ns = wake_up_time_ns;
|
||||
*out_desired_present_time_ns = desired_present_time_ns;
|
||||
*out_predicted_display_time_ns = predicted_display_time_ns;
|
||||
*out_present_slop_ns = present_slop_ns;
|
||||
}
|
||||
|
||||
static void
|
||||
comp_wivrn_mark_timing_point(struct comp_target *ct,
|
||||
enum comp_target_timing_point point,
|
||||
int64_t frame_id,
|
||||
uint64_t when_ns)
|
||||
{
|
||||
struct wivrn_comp_target *cn = (struct wivrn_comp_target *)ct;
|
||||
assert(frame_id == cn->current_frame_id);
|
||||
|
||||
switch (point) {
|
||||
case COMP_TARGET_TIMING_POINT_WAKE_UP:
|
||||
u_pc_mark_point(cn->upc, U_TIMING_POINT_WAKE_UP, cn->current_frame_id, when_ns);
|
||||
break;
|
||||
case COMP_TARGET_TIMING_POINT_BEGIN:
|
||||
u_pc_mark_point(cn->upc, U_TIMING_POINT_BEGIN, cn->current_frame_id, when_ns);
|
||||
break;
|
||||
case COMP_TARGET_TIMING_POINT_SUBMIT:
|
||||
u_pc_mark_point(cn->upc, U_TIMING_POINT_SUBMIT, cn->current_frame_id, when_ns);
|
||||
break;
|
||||
default: assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
static VkResult
|
||||
comp_wivrn_update_timings(struct comp_target *ct)
|
||||
{
|
||||
// TODO
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
static void
|
||||
comp_wivrn_set_title(struct comp_target *ct, const char *title)
|
||||
{}
|
||||
|
||||
static void
|
||||
comp_wivrn_destroy(struct comp_target *ct)
|
||||
{
|
||||
struct wivrn_comp_target *cn = (struct wivrn_comp_target *)ct;
|
||||
|
||||
vk_bundle *vk = get_vk(cn);
|
||||
vk->vkDeviceWaitIdle(vk->device);
|
||||
destroy_images(cn);
|
||||
|
||||
delete cn;
|
||||
}
|
||||
|
||||
|
||||
static void
|
||||
comp_wivrn_info_gpu(
|
||||
struct comp_target *ct, int64_t frame_id, uint64_t gpu_start_ns, uint64_t gpu_end_ns, uint64_t when_ns)
|
||||
{
|
||||
COMP_TRACE_MARKER();
|
||||
|
||||
struct wivrn_comp_target *cn = (struct wivrn_comp_target *)ct;
|
||||
|
||||
u_pc_info_gpu(cn->upc, frame_id, gpu_start_ns, gpu_end_ns, when_ns);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
*
|
||||
* 'Exported' functions.
|
||||
*
|
||||
*/
|
||||
|
||||
comp_target *
|
||||
comp_target_wivrn_create(std::shared_ptr<xrt::drivers::wivrn::wivrn_session> cnx, float fps)
|
||||
{
|
||||
wivrn_comp_target *cn = new wivrn_comp_target{};
|
||||
|
||||
cn->cnx = cnx;
|
||||
cn->check_ready = comp_wivrn_check_ready;
|
||||
cn->create_images = comp_wivrn_create_images;
|
||||
cn->has_images = comp_wivrn_has_images;
|
||||
cn->acquire = comp_wivrn_acquire;
|
||||
cn->present = comp_wivrn_present;
|
||||
cn->calc_frame_pacing = comp_wivrn_calc_frame_pacing;
|
||||
cn->mark_timing_point = comp_wivrn_mark_timing_point;
|
||||
cn->update_timings = comp_wivrn_update_timings;
|
||||
cn->info_gpu = comp_wivrn_info_gpu;
|
||||
cn->destroy = comp_wivrn_destroy;
|
||||
cn->init_pre_vulkan = comp_wivrn_init_pre_vulkan;
|
||||
cn->init_post_vulkan = comp_wivrn_init_post_vulkan;
|
||||
cn->set_title = comp_wivrn_set_title;
|
||||
cn->flush = comp_wivrn_flush;
|
||||
cn->fps = fps;
|
||||
|
||||
return cn;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "main/comp_target.h"
|
||||
#include "wivrn_session.h"
|
||||
|
||||
comp_target *
|
||||
comp_target_wivrn_create(std::shared_ptr<xrt::drivers::wivrn::wivrn_session> cnx, float fps);
|
||||
@@ -0,0 +1,62 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "wivrn_connection.h"
|
||||
#include <poll.h>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
wivrn_connection::wivrn_connection(TCP&& tcp, in6_addr address) : control(std::move(tcp))
|
||||
{
|
||||
stream.bind(stream_port);
|
||||
stream.connect(address, stream_port);
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_connection::send_control(const to_headset::control_packets &packet)
|
||||
{
|
||||
control.send(packet);
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_connection::send_stream(const to_headset::stream_packets &packet)
|
||||
{
|
||||
stream.send(packet);
|
||||
}
|
||||
|
||||
std::optional<from_headset::stream_packets>
|
||||
wivrn_connection::poll_stream(int timeout)
|
||||
{
|
||||
pollfd fds{};
|
||||
fds.events = POLLIN;
|
||||
fds.fd = stream.get_fd();
|
||||
|
||||
int r = ::poll(&fds, 1, timeout);
|
||||
if (r < 0)
|
||||
throw std::system_error(errno, std::system_category());
|
||||
|
||||
if (r > 0 && (fds.revents & POLLIN)) {
|
||||
return stream.receive();
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<from_headset::control_packets>
|
||||
wivrn_connection::poll_control(int timeout)
|
||||
{
|
||||
pollfd fds{};
|
||||
fds.events = POLLIN;
|
||||
fds.fd = control.get_fd();
|
||||
|
||||
int r = ::poll(&fds, 1, timeout);
|
||||
if (r < 0)
|
||||
throw std::system_error(errno, std::system_category());
|
||||
|
||||
if (r > 0 && (fds.revents & POLLIN)) {
|
||||
return control.receive();
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "wivrn_packets.h"
|
||||
#include "wivrn_sockets.h"
|
||||
#include <optional>
|
||||
#include <poll.h>
|
||||
|
||||
using namespace xrt::drivers::wivrn;
|
||||
|
||||
class wivrn_connection
|
||||
{
|
||||
typed_socket<TCP, from_headset::control_packets, to_headset::control_packets> control;
|
||||
typed_socket<UDP, from_headset::stream_packets, to_headset::stream_packets> stream;
|
||||
|
||||
public:
|
||||
wivrn_connection(TCP &&tcp, in6_addr address);
|
||||
wivrn_connection(const wivrn_connection &) = delete;
|
||||
wivrn_connection &
|
||||
operator=(const wivrn_connection &) = delete;
|
||||
|
||||
void
|
||||
send_control(const to_headset::control_packets &packet);
|
||||
void
|
||||
send_stream(const to_headset::stream_packets &packet);
|
||||
|
||||
std::optional<from_headset::stream_packets>
|
||||
poll_stream(int timeout);
|
||||
std::optional<from_headset::control_packets>
|
||||
poll_control(int timeout);
|
||||
|
||||
template <typename T>
|
||||
int
|
||||
poll(T &&visitor, int timeout)
|
||||
{
|
||||
pollfd fds[2] = {};
|
||||
fds[0].events = POLLIN;
|
||||
fds[0].fd = stream.get_fd();
|
||||
fds[1].events = POLLIN;
|
||||
fds[1].fd = control.get_fd();
|
||||
|
||||
int r = ::poll(fds, std::size(fds), timeout);
|
||||
if (r < 0)
|
||||
throw std::system_error(errno, std::system_category());
|
||||
|
||||
if (fds[0].revents & (POLLHUP | POLLERR))
|
||||
throw std::runtime_error("Error on stream socket");
|
||||
|
||||
if (fds[1].revents & (POLLHUP | POLLERR))
|
||||
throw std::runtime_error("Error on control socket");
|
||||
|
||||
if (fds[0].revents & POLLIN) {
|
||||
auto packet = stream.receive();
|
||||
if (packet)
|
||||
std::visit(std::forward<T>(visitor), std::move(*packet));
|
||||
}
|
||||
|
||||
if (fds[1].revents & POLLIN) {
|
||||
auto packet = control.receive();
|
||||
if (packet)
|
||||
std::visit(std::forward<T>(visitor), std::move(*packet));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,305 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "wivrn_controller.h"
|
||||
|
||||
#include "util/u_logging.h"
|
||||
#include "os/os_threading.h"
|
||||
#include "util/u_device.h"
|
||||
#include <stdio.h>
|
||||
|
||||
#include "xrt/xrt_defines.h"
|
||||
|
||||
/*
|
||||
*
|
||||
* Defines & structs.
|
||||
*
|
||||
*/
|
||||
|
||||
enum wivrn_controller_input_index
|
||||
{
|
||||
WIVRN_CONTROLLER_AIM_POSE,
|
||||
WIVRN_CONTROLLER_GRIP_POSE,
|
||||
WIVRN_CONTROLLER_MENU_CLICK, // /user/hand/left/input/menu/click
|
||||
WIVRN_CONTROLLER_A_CLICK, // /user/hand/right/input/a/click
|
||||
WIVRN_CONTROLLER_A_TOUCH, // /user/hand/right/input/a/touch
|
||||
WIVRN_CONTROLLER_B_CLICK, // /user/hand/right/input/b/click
|
||||
WIVRN_CONTROLLER_B_TOUCH, // /user/hand/right/input/b/touch
|
||||
WIVRN_CONTROLLER_X_CLICK = WIVRN_CONTROLLER_A_CLICK, // /user/hand/left/input/x/click
|
||||
WIVRN_CONTROLLER_X_TOUCH = WIVRN_CONTROLLER_A_TOUCH, // /user/hand/left/input/x/touch
|
||||
WIVRN_CONTROLLER_Y_CLICK = WIVRN_CONTROLLER_B_CLICK, // /user/hand/left/input/y/click
|
||||
WIVRN_CONTROLLER_Y_TOUCH = WIVRN_CONTROLLER_B_TOUCH, // /user/hand/left/input/y/touch
|
||||
WIVRN_CONTROLLER_SQUEEZE_CLICK, // /user/hand/XXXX/input/squeeze/click
|
||||
WIVRN_CONTROLLER_SQUEEZE_VALUE, // /user/hand/XXXX/input/squeeze/value
|
||||
WIVRN_CONTROLLER_TRIGGER_CLICK, // /user/hand/XXXX/input/trigger/click
|
||||
WIVRN_CONTROLLER_TRIGGER_VALUE, // /user/hand/XXXX/input/trigger/value
|
||||
WIVRN_CONTROLLER_TRIGGER_TOUCH, // /user/hand/XXXX/input/trigger/touch
|
||||
WIVRN_CONTROLLER_THUMBSTICK, // /user/hand/XXXX/input/thumbstick/{x,y}
|
||||
WIVRN_CONTROLLER_THUMBSTICK_CLICK, // /user/hand/XXXX/input/thumbstick/click
|
||||
WIVRN_CONTROLLER_THUMBSTICK_TOUCH, // /user/hand/XXXX/input/thumbstick/touch
|
||||
WIVRN_CONTROLLER_THUMBREST_TOUCH, // /user/hand/XXXX/input/thumbrest/touch
|
||||
|
||||
WIVRN_CONTROLLER_INPUT_COUNT
|
||||
};
|
||||
|
||||
enum class wivrn_input_type
|
||||
{
|
||||
BOOL,
|
||||
FLOAT,
|
||||
VEC2_X,
|
||||
VEC2_Y
|
||||
};
|
||||
|
||||
struct wivrn_to_wivrn_controller_input
|
||||
{
|
||||
wivrn_controller_input_index input_id;
|
||||
device_id wivrn_id;
|
||||
wivrn_input_type input_type;
|
||||
};
|
||||
|
||||
// clang-format off
|
||||
static const wivrn_to_wivrn_controller_input left_hand_bindings[] = {
|
||||
{WIVRN_CONTROLLER_MENU_CLICK, device_id::MENU_CLICK, wivrn_input_type::BOOL}, // /user/hand/left/input/menu/click
|
||||
{WIVRN_CONTROLLER_X_CLICK, device_id::X_CLICK, wivrn_input_type::BOOL}, // /user/hand/left/input/x/click
|
||||
{WIVRN_CONTROLLER_X_TOUCH, device_id::X_TOUCH, wivrn_input_type::BOOL}, // /user/hand/left/input/x/touch
|
||||
{WIVRN_CONTROLLER_Y_CLICK, device_id::Y_CLICK, wivrn_input_type::BOOL}, // /user/hand/left/input/y/click
|
||||
{WIVRN_CONTROLLER_Y_TOUCH, device_id::Y_TOUCH, wivrn_input_type::BOOL}, // /user/hand/left/input/y/touch
|
||||
{WIVRN_CONTROLLER_SQUEEZE_VALUE, device_id::LEFT_SQUEEZE_VALUE, wivrn_input_type::FLOAT}, // /user/hand/left/input/squeeze/value
|
||||
{WIVRN_CONTROLLER_TRIGGER_VALUE, device_id::LEFT_TRIGGER_VALUE, wivrn_input_type::FLOAT}, // /user/hand/left/input/trigger/value
|
||||
{WIVRN_CONTROLLER_TRIGGER_TOUCH, device_id::LEFT_TRIGGER_TOUCH, wivrn_input_type::BOOL}, // /user/hand/left/input/trigger/touch
|
||||
{WIVRN_CONTROLLER_THUMBSTICK, device_id::LEFT_THUMBSTICK_X, wivrn_input_type::VEC2_X}, // /user/hand/left/input/thumbstick/x
|
||||
{WIVRN_CONTROLLER_THUMBSTICK, device_id::LEFT_THUMBSTICK_Y, wivrn_input_type::VEC2_Y}, // /user/hand/left/input/thumbstick/y
|
||||
{WIVRN_CONTROLLER_THUMBSTICK_CLICK, device_id::LEFT_THUMBSTICK_CLICK, wivrn_input_type::BOOL},// /user/hand/left/input/thumbstick/click
|
||||
{WIVRN_CONTROLLER_THUMBSTICK_TOUCH, device_id::LEFT_THUMBSTICK_TOUCH, wivrn_input_type::BOOL},// /user/hand/left/input/thumbstick/touch
|
||||
{WIVRN_CONTROLLER_THUMBREST_TOUCH, device_id::LEFT_THUMBREST_TOUCH, wivrn_input_type::BOOL}, // /user/hand/left/input/thumbrest/touch
|
||||
};
|
||||
|
||||
static const wivrn_to_wivrn_controller_input right_hand_bindings[] = {
|
||||
{WIVRN_CONTROLLER_A_CLICK, device_id::A_CLICK, wivrn_input_type::BOOL}, // /user/hand/right/input/a/click
|
||||
{WIVRN_CONTROLLER_A_TOUCH, device_id::A_TOUCH, wivrn_input_type::BOOL}, // /user/hand/right/input/a/touch
|
||||
{WIVRN_CONTROLLER_B_CLICK, device_id::B_CLICK, wivrn_input_type::BOOL}, // /user/hand/right/input/b/click
|
||||
{WIVRN_CONTROLLER_B_TOUCH, device_id::B_TOUCH, wivrn_input_type::BOOL}, // /user/hand/right/input/b/touch
|
||||
{WIVRN_CONTROLLER_SQUEEZE_VALUE, device_id::RIGHT_SQUEEZE_VALUE, wivrn_input_type::FLOAT}, // /user/hand/right/input/squeeze/value
|
||||
{WIVRN_CONTROLLER_TRIGGER_VALUE, device_id::RIGHT_TRIGGER_VALUE, wivrn_input_type::FLOAT}, // /user/hand/right/input/trigger/value
|
||||
{WIVRN_CONTROLLER_TRIGGER_TOUCH, device_id::RIGHT_TRIGGER_TOUCH, wivrn_input_type::BOOL}, // /user/hand/right/input/trigger/touch
|
||||
{WIVRN_CONTROLLER_THUMBSTICK, device_id::RIGHT_THUMBSTICK_X, wivrn_input_type::VEC2_X}, // /user/hand/right/input/thumbstick/x
|
||||
{WIVRN_CONTROLLER_THUMBSTICK, device_id::RIGHT_THUMBSTICK_Y, wivrn_input_type::VEC2_Y}, // /user/hand/right/input/thumbstick/y
|
||||
{WIVRN_CONTROLLER_THUMBSTICK_CLICK, device_id::RIGHT_THUMBSTICK_CLICK, wivrn_input_type::BOOL},// /user/hand/right/input/thumbstick/click
|
||||
{WIVRN_CONTROLLER_THUMBSTICK_TOUCH, device_id::RIGHT_THUMBSTICK_TOUCH, wivrn_input_type::BOOL},// /user/hand/right/input/thumbstick/touch
|
||||
{WIVRN_CONTROLLER_THUMBREST_TOUCH, device_id::RIGHT_THUMBREST_TOUCH, wivrn_input_type::BOOL}, // /user/hand/right/input/thumbrest/touch
|
||||
};
|
||||
// clang-format on
|
||||
|
||||
static const size_t left_hand_bindings_count = ARRAY_SIZE(left_hand_bindings);
|
||||
static const size_t right_hand_bindings_count = ARRAY_SIZE(right_hand_bindings);
|
||||
|
||||
|
||||
static void
|
||||
wivrn_controller_destroy(xrt_device *xdev);
|
||||
|
||||
static void
|
||||
wivrn_controller_get_tracked_pose(xrt_device *xdev,
|
||||
xrt_input_name name,
|
||||
uint64_t at_timestamp_ns,
|
||||
xrt_space_relation *out_relation);
|
||||
|
||||
|
||||
static void
|
||||
wivrn_controller_set_output(struct xrt_device *xdev, enum xrt_output_name name, const union xrt_output_value *value);
|
||||
|
||||
static void
|
||||
wivrn_controller_update_inputs(xrt_device *xdev);
|
||||
|
||||
|
||||
wivrn_controller::wivrn_controller(int hand_id,
|
||||
xrt_device *hmd,
|
||||
std::shared_ptr<xrt::drivers::wivrn::wivrn_session> cnx)
|
||||
: xrt_device{}, grip(hand_id == 0 ? device_id::LEFT_GRIP : device_id::RIGHT_GRIP),
|
||||
aim(hand_id == 0 ? device_id::LEFT_AIM : device_id::RIGHT_AIM), cnx(cnx)
|
||||
{
|
||||
xrt_device *base = this;
|
||||
|
||||
base->destroy = wivrn_controller_destroy;
|
||||
base->get_tracked_pose = wivrn_controller_get_tracked_pose;
|
||||
base->get_hand_tracking = NULL; // TODO
|
||||
base->set_output = wivrn_controller_set_output;
|
||||
base->update_inputs = wivrn_controller_update_inputs;
|
||||
|
||||
base->name = XRT_DEVICE_TOUCH_CONTROLLER;
|
||||
base->orientation_tracking_supported = true;
|
||||
base->hand_tracking_supported = false;
|
||||
base->position_tracking_supported = true;
|
||||
|
||||
base->tracking_origin = hmd->tracking_origin;
|
||||
|
||||
inputs_array.resize(WIVRN_CONTROLLER_INPUT_COUNT);
|
||||
inputs = inputs_array.data();
|
||||
input_count = WIVRN_CONTROLLER_INPUT_COUNT;
|
||||
|
||||
// Setup input.
|
||||
#define SET_INPUT(NAME) \
|
||||
do { \
|
||||
inputs[WIVRN_CONTROLLER_##NAME].name = XRT_INPUT_TOUCH_##NAME; \
|
||||
inputs[WIVRN_CONTROLLER_##NAME].active = true; \
|
||||
} while (0)
|
||||
|
||||
SET_INPUT(AIM_POSE);
|
||||
SET_INPUT(GRIP_POSE);
|
||||
SET_INPUT(A_CLICK);
|
||||
SET_INPUT(B_CLICK);
|
||||
SET_INPUT(A_TOUCH);
|
||||
SET_INPUT(B_TOUCH);
|
||||
SET_INPUT(SQUEEZE_VALUE);
|
||||
SET_INPUT(TRIGGER_VALUE);
|
||||
SET_INPUT(TRIGGER_TOUCH);
|
||||
SET_INPUT(THUMBSTICK);
|
||||
SET_INPUT(THUMBSTICK_CLICK);
|
||||
SET_INPUT(THUMBSTICK_TOUCH);
|
||||
SET_INPUT(THUMBREST_TOUCH);
|
||||
|
||||
output_count = 1;
|
||||
outputs = &haptic_output;
|
||||
haptic_output.name = XRT_OUTPUT_NAME_TOUCH_HAPTIC;
|
||||
|
||||
inputs_staging = inputs_array;
|
||||
|
||||
switch (hand_id) {
|
||||
case 0:
|
||||
device_type = XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER;
|
||||
SET_INPUT(MENU_CLICK);
|
||||
|
||||
// Print name.
|
||||
strcpy(str, "WiVRn HMD left hand controller");
|
||||
strcpy(serial, "WiVRn HMD left hand controller");
|
||||
|
||||
break;
|
||||
|
||||
case 1:
|
||||
device_type = XRT_DEVICE_TYPE_RIGHT_HAND_CONTROLLER;
|
||||
|
||||
// Print name.
|
||||
strcpy(str, "WiVRn HMD right hand controller");
|
||||
strcpy(serial, "WiVRn HMD right hand controller");
|
||||
|
||||
break;
|
||||
|
||||
default: throw std::runtime_error("Invalid hand ID");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_controller::update_inputs()
|
||||
{
|
||||
std::lock_guard _{mutex};
|
||||
inputs_array = inputs_staging;
|
||||
}
|
||||
void
|
||||
wivrn_controller::set_inputs(const from_headset::inputs &inputs)
|
||||
{
|
||||
std::lock_guard lock{mutex};
|
||||
for (const auto &input : inputs.values) {
|
||||
set_inputs(input.id, input.value);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_controller::set_inputs(device_id input_id, float value)
|
||||
{
|
||||
const struct wivrn_to_wivrn_controller_input *bindings;
|
||||
size_t bindings_count;
|
||||
if (device_type == XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER) {
|
||||
bindings = left_hand_bindings;
|
||||
bindings_count = left_hand_bindings_count;
|
||||
} else {
|
||||
bindings = right_hand_bindings;
|
||||
bindings_count = right_hand_bindings_count;
|
||||
}
|
||||
|
||||
const struct wivrn_to_wivrn_controller_input *binding = NULL;
|
||||
for (size_t i = 0; i < bindings_count; i++) {
|
||||
if (bindings[i].wivrn_id == input_id) {
|
||||
binding = &bindings[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (binding) {
|
||||
switch (binding->input_type) {
|
||||
case wivrn_input_type::BOOL: inputs_staging[binding->input_id].value.boolean = (value != 0); break;
|
||||
case wivrn_input_type::FLOAT: inputs_staging[binding->input_id].value.vec1.x = value; break;
|
||||
case wivrn_input_type::VEC2_X: inputs_staging[binding->input_id].value.vec2.x = value; break;
|
||||
case wivrn_input_type::VEC2_Y: inputs_staging[binding->input_id].value.vec2.y = value; break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
xrt_space_relation
|
||||
wivrn_controller::get_tracked_pose(xrt_input_name name, uint64_t at_timestamp_ns)
|
||||
{
|
||||
switch (name) {
|
||||
case XRT_INPUT_TOUCH_AIM_POSE: return aim.get_at(at_timestamp_ns);
|
||||
|
||||
case XRT_INPUT_TOUCH_GRIP_POSE: return grip.get_at(at_timestamp_ns);
|
||||
|
||||
default: U_LOG_W("Unknown input name requested"); return {};
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_controller::update_tracking(const from_headset::tracking &tracking, const clock_offset &offset)
|
||||
{
|
||||
aim.update_tracking(tracking, offset);
|
||||
grip.update_tracking(tracking, offset);
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_controller::set_output(xrt_output_name name, const xrt_output_value *value)
|
||||
{
|
||||
auto id = device_type == XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER ? device_id::LEFT_CONTROLLER_HAPTIC
|
||||
: device_id::RIGHT_CONTROLLER_HAPTIC;
|
||||
|
||||
try {
|
||||
cnx->send_stream(to_headset::haptics{id, std::chrono::nanoseconds(value->vibration.duration_ns),
|
||||
value->vibration.frequency, value->vibration.amplitude
|
||||
|
||||
});
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
// Ignore errors
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
* Functions
|
||||
*
|
||||
*/
|
||||
|
||||
static void
|
||||
wivrn_controller_destroy(xrt_device *xdev)
|
||||
{
|
||||
delete (wivrn_controller *)xdev;
|
||||
}
|
||||
|
||||
static void
|
||||
wivrn_controller_update_inputs(xrt_device *xdev)
|
||||
{
|
||||
static_cast<wivrn_controller *>(xdev)->update_inputs();
|
||||
}
|
||||
|
||||
static void
|
||||
wivrn_controller_get_tracked_pose(xrt_device *xdev,
|
||||
xrt_input_name name,
|
||||
uint64_t at_timestamp_ns,
|
||||
xrt_space_relation *out_relation)
|
||||
{
|
||||
*out_relation = static_cast<wivrn_controller *>(xdev)->get_tracked_pose(name, at_timestamp_ns);
|
||||
}
|
||||
|
||||
static void
|
||||
wivrn_controller_set_output(struct xrt_device *xdev, enum xrt_output_name name, const union xrt_output_value *value)
|
||||
{
|
||||
static_cast<wivrn_controller *>(xdev)->set_output(name, value);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "xrt/xrt_device.h"
|
||||
|
||||
#include "pose_list.h"
|
||||
#include "wivrn_session.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
class wivrn_controller : public xrt_device
|
||||
{
|
||||
std::mutex mutex;
|
||||
|
||||
pose_list grip;
|
||||
pose_list aim;
|
||||
|
||||
std::vector<xrt_input> inputs_staging;
|
||||
std::vector<xrt_input> inputs_array;
|
||||
xrt_output haptic_output;
|
||||
|
||||
std::shared_ptr<xrt::drivers::wivrn::wivrn_session> cnx;
|
||||
|
||||
public:
|
||||
wivrn_controller(int hand_id, xrt_device *hmd, std::shared_ptr<xrt::drivers::wivrn::wivrn_session> cnx);
|
||||
|
||||
void
|
||||
unregister()
|
||||
{
|
||||
cnx = nullptr;
|
||||
}
|
||||
void
|
||||
update_inputs();
|
||||
|
||||
xrt_space_relation
|
||||
get_tracked_pose(xrt_input_name name, uint64_t at_timestamp_ns);
|
||||
|
||||
void
|
||||
set_output(xrt_output_name name, const xrt_output_value *value);
|
||||
|
||||
void
|
||||
set_inputs(const from_headset::inputs &);
|
||||
|
||||
void
|
||||
update_tracking(const from_headset::tracking &, const clock_offset &);
|
||||
|
||||
private:
|
||||
void
|
||||
set_inputs(device_id input_id, float value);
|
||||
};
|
||||
@@ -0,0 +1,281 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
// Copyright 2020, Collabora, Ltd.
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
/*!
|
||||
* @file
|
||||
* @brief WiVRn HMD device.
|
||||
* @author Jakob Bornecrantz <jakob@collabora.com>
|
||||
* @ingroup drv_wivrn
|
||||
*/
|
||||
|
||||
#include "wivrn_hmd.h"
|
||||
|
||||
#include "xrt/xrt_defines.h"
|
||||
#include "xrt/xrt_device.h"
|
||||
|
||||
#include "os/os_time.h"
|
||||
|
||||
#include "math/m_api.h"
|
||||
#include "math/m_mathinclude.h"
|
||||
|
||||
#include "util/u_var.h"
|
||||
#include "util/u_misc.h"
|
||||
#include "util/u_time.h"
|
||||
#include "util/u_debug.h"
|
||||
#include "util/u_device.h"
|
||||
#include "util/u_logging.h"
|
||||
#include "util/u_distortion_mesh.h"
|
||||
|
||||
#include <openxr/openxr.h>
|
||||
#include <stdio.h>
|
||||
#include <stdatomic.h>
|
||||
|
||||
#include "wivrn_comp_target.h"
|
||||
|
||||
/*
|
||||
*
|
||||
* Structs and defines.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/*!
|
||||
* A wivrn HMD device.
|
||||
*
|
||||
* @implements xrt_device
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
*
|
||||
* Functions
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
static void
|
||||
wivrn_hmd_destroy(xrt_device *xdev);
|
||||
|
||||
static void
|
||||
wivrn_hmd_update_inputs(xrt_device *xdev);
|
||||
|
||||
static void
|
||||
wivrn_hmd_get_tracked_pose(xrt_device *xdev,
|
||||
xrt_input_name name,
|
||||
uint64_t at_timestamp_ns,
|
||||
xrt_space_relation *out_relation);
|
||||
|
||||
static void
|
||||
wivrn_hmd_get_view_poses(xrt_device *xdev,
|
||||
const xrt_vec3 *default_eye_relation,
|
||||
uint64_t at_timestamp_ns,
|
||||
uint32_t view_count,
|
||||
xrt_space_relation *out_head_relation,
|
||||
xrt_fov *out_fovs,
|
||||
xrt_pose *out_poses);
|
||||
|
||||
static void
|
||||
wivrn_hmd_create_compositor_target(struct xrt_device *xdev,
|
||||
struct comp_compositor *comp,
|
||||
struct comp_target **out_target);
|
||||
|
||||
|
||||
wivrn_hmd::wivrn_hmd(std::shared_ptr<xrt::drivers::wivrn::wivrn_session> cnx,
|
||||
const from_headset::headset_info_packet &info)
|
||||
: xrt_device{}, cnx(cnx)
|
||||
{
|
||||
xrt_device *base = this;
|
||||
|
||||
base->hmd = &hmd_parts;
|
||||
base->tracking_origin = &tracking_origin;
|
||||
tracking_origin.type = XRT_TRACKING_TYPE_NONE;
|
||||
tracking_origin.offset.orientation = xrt_quat{0, 0, 0, 1};
|
||||
strcpy(tracking_origin.name, "No tracking");
|
||||
|
||||
base->update_inputs = wivrn_hmd_update_inputs;
|
||||
base->get_tracked_pose = wivrn_hmd_get_tracked_pose;
|
||||
base->get_view_poses = wivrn_hmd_get_view_poses;
|
||||
base->create_compositor_target = wivrn_hmd_create_compositor_target;
|
||||
base->destroy = wivrn_hmd_destroy;
|
||||
name = XRT_DEVICE_GENERIC_HMD;
|
||||
device_type = XRT_DEVICE_TYPE_HMD;
|
||||
orientation_tracking_supported = true;
|
||||
// hand_tracking_supported = true;
|
||||
position_tracking_supported = true;
|
||||
|
||||
// Print name.
|
||||
strcpy(str, "WiVRn HMD");
|
||||
strcpy(serial, "WiVRn HMD");
|
||||
|
||||
// Setup input.
|
||||
pose_input.name = XRT_INPUT_GENERIC_HEAD_POSE;
|
||||
pose_input.active = true;
|
||||
inputs = &pose_input;
|
||||
input_count = 1;
|
||||
|
||||
auto eye_width = info.recommended_eye_width;
|
||||
auto eye_height = info.recommended_eye_height;
|
||||
fps = info.preferred_refresh_rate;
|
||||
|
||||
// Setup info.
|
||||
hmd->blend_modes[0] = XRT_BLEND_MODE_OPAQUE;
|
||||
hmd->blend_mode_count = 1;
|
||||
hmd->distortion.models = XRT_DISTORTION_MODEL_NONE;
|
||||
hmd->distortion.preferred = XRT_DISTORTION_MODEL_NONE;
|
||||
hmd->screens[0].w_pixels = info.recommended_eye_width * 2;
|
||||
hmd->screens[0].h_pixels = eye_height;
|
||||
hmd->screens[0].nominal_frame_interval_ns = 1000000000 / fps;
|
||||
|
||||
// Left
|
||||
hmd->views[0].display.w_pixels = eye_width;
|
||||
hmd->views[0].display.h_pixels = eye_height;
|
||||
hmd->views[0].viewport.x_pixels = 0;
|
||||
hmd->views[0].viewport.y_pixels = 0;
|
||||
hmd->views[0].viewport.w_pixels = eye_width;
|
||||
hmd->views[0].viewport.h_pixels = eye_height;
|
||||
hmd->views[0].rot = u_device_rotation_ident;
|
||||
|
||||
// Right
|
||||
hmd->views[1].display.w_pixels = eye_width;
|
||||
hmd->views[1].display.h_pixels = eye_height;
|
||||
hmd->views[1].viewport.x_pixels = eye_width;
|
||||
hmd->views[1].viewport.y_pixels = 0;
|
||||
hmd->views[1].viewport.w_pixels = eye_width;
|
||||
hmd->views[1].viewport.h_pixels = eye_height;
|
||||
hmd->views[1].rot = u_device_rotation_ident;
|
||||
|
||||
// Default FOV from Oculus Quest
|
||||
hmd->distortion.fov[0].angle_left = -52 * M_PI / 180;
|
||||
hmd->distortion.fov[0].angle_right = 42 * M_PI / 180;
|
||||
hmd->distortion.fov[0].angle_up = 47 * M_PI / 180;
|
||||
hmd->distortion.fov[0].angle_down = -53 * M_PI / 180;
|
||||
|
||||
hmd->distortion.fov[1].angle_left = -42 * M_PI / 180;
|
||||
hmd->distortion.fov[1].angle_right = 52 * M_PI / 180;
|
||||
hmd->distortion.fov[1].angle_up = 47 * M_PI / 180;
|
||||
hmd->distortion.fov[1].angle_down = -53 * M_PI / 180;
|
||||
|
||||
// Distortion information, fills in xdev->compute_distortion().
|
||||
u_distortion_mesh_set_none(this);
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_hmd::update_inputs()
|
||||
{
|
||||
// Empty
|
||||
}
|
||||
|
||||
|
||||
xrt_space_relation
|
||||
wivrn_hmd::get_tracked_pose(xrt_input_name name, uint64_t at_timestamp_ns)
|
||||
{
|
||||
if (name != XRT_INPUT_GENERIC_HEAD_POSE) {
|
||||
U_LOG_E("Unknown input name");
|
||||
return {};
|
||||
}
|
||||
|
||||
return views.get_at(at_timestamp_ns).relation;
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_hmd::update_tracking(const from_headset::tracking &tracking, const clock_offset &offset)
|
||||
{
|
||||
views.update_tracking(tracking, offset);
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_hmd::get_view_poses(const xrt_vec3 *default_eye_relation,
|
||||
uint64_t at_timestamp_ns,
|
||||
uint32_t view_count,
|
||||
xrt_space_relation *out_head_relation,
|
||||
xrt_fov *out_fovs,
|
||||
xrt_pose *out_poses)
|
||||
{
|
||||
auto view = views.get_at(at_timestamp_ns);
|
||||
|
||||
int flags = view.relation.relation_flags;
|
||||
|
||||
if (not(view.flags & XR_VIEW_STATE_POSITION_VALID_BIT))
|
||||
flags &= ~XRT_SPACE_RELATION_POSITION_VALID_BIT;
|
||||
|
||||
if (not(view.flags & XR_VIEW_STATE_ORIENTATION_VALID_BIT))
|
||||
flags &= ~XRT_SPACE_RELATION_ORIENTATION_VALID_BIT;
|
||||
|
||||
if (not(view.flags & XR_VIEW_STATE_POSITION_TRACKED_BIT))
|
||||
flags &= ~XRT_SPACE_RELATION_POSITION_TRACKED_BIT;
|
||||
|
||||
if (not(view.flags & XR_VIEW_STATE_ORIENTATION_TRACKED_BIT))
|
||||
flags &= ~XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT;
|
||||
|
||||
view.relation.relation_flags = (xrt_space_relation_flags)flags;
|
||||
*out_head_relation = view.relation;
|
||||
|
||||
assert(view_count == 2);
|
||||
for (size_t eye = 0; eye < 2; ++eye) {
|
||||
out_fovs[eye] = view.fovs[eye];
|
||||
out_poses[eye] = view.poses[eye];
|
||||
}
|
||||
}
|
||||
|
||||
comp_target *
|
||||
wivrn_hmd::create_compositor_target(struct comp_compositor *comp)
|
||||
{
|
||||
comp_target *target = comp_target_wivrn_create(cnx, fps);
|
||||
|
||||
target->c = comp;
|
||||
return target;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
*
|
||||
* Functions
|
||||
*
|
||||
*/
|
||||
|
||||
static void
|
||||
wivrn_hmd_destroy(xrt_device *xdev)
|
||||
{
|
||||
static_cast<wivrn_hmd *>(xdev)->unregister();
|
||||
}
|
||||
|
||||
static void
|
||||
wivrn_hmd_update_inputs(xrt_device *xdev)
|
||||
{
|
||||
static_cast<wivrn_hmd *>(xdev)->update_inputs();
|
||||
}
|
||||
|
||||
static void
|
||||
wivrn_hmd_get_tracked_pose(xrt_device *xdev,
|
||||
xrt_input_name name,
|
||||
uint64_t at_timestamp_ns,
|
||||
xrt_space_relation *out_relation)
|
||||
{
|
||||
*out_relation = static_cast<wivrn_hmd *>(xdev)->get_tracked_pose(name, at_timestamp_ns);
|
||||
}
|
||||
|
||||
static void
|
||||
wivrn_hmd_get_view_poses(xrt_device *xdev,
|
||||
const xrt_vec3 *default_eye_relation,
|
||||
uint64_t at_timestamp_ns,
|
||||
uint32_t view_count,
|
||||
xrt_space_relation *out_head_relation,
|
||||
xrt_fov *out_fovs,
|
||||
xrt_pose *out_poses)
|
||||
{
|
||||
static_cast<wivrn_hmd *>(xdev)->get_view_poses(default_eye_relation, at_timestamp_ns, view_count,
|
||||
out_head_relation, out_fovs, out_poses);
|
||||
}
|
||||
|
||||
static void
|
||||
wivrn_hmd_create_compositor_target(struct xrt_device *xdev,
|
||||
struct comp_compositor *comp,
|
||||
struct comp_target **out_target)
|
||||
{
|
||||
*out_target = static_cast<wivrn_hmd *>(xdev)->create_compositor_target(comp);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "xrt/xrt_device.h"
|
||||
#include "xrt/xrt_tracking.h"
|
||||
|
||||
#include "view_list.h"
|
||||
#include "wivrn_session.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
|
||||
class wivrn_hmd : public xrt_device
|
||||
{
|
||||
std::mutex mutex;
|
||||
|
||||
float fps;
|
||||
|
||||
xrt_input pose_input;
|
||||
xrt_hmd_parts hmd_parts;
|
||||
xrt_tracking_origin tracking_origin;
|
||||
|
||||
view_list views;
|
||||
|
||||
std::shared_ptr<xrt::drivers::wivrn::wivrn_session> cnx;
|
||||
|
||||
public:
|
||||
wivrn_hmd(std::shared_ptr<xrt::drivers::wivrn::wivrn_session> cnx,
|
||||
const from_headset::headset_info_packet &info);
|
||||
void
|
||||
unregister()
|
||||
{
|
||||
cnx = nullptr;
|
||||
}
|
||||
|
||||
void
|
||||
update_inputs();
|
||||
xrt_space_relation
|
||||
get_tracked_pose(xrt_input_name name, uint64_t at_timestamp_ns);
|
||||
comp_target *
|
||||
create_compositor_target(struct comp_compositor *comp);
|
||||
void
|
||||
get_view_poses(const xrt_vec3 *default_eye_relation,
|
||||
uint64_t at_timestamp_ns,
|
||||
uint32_t view_count,
|
||||
xrt_space_relation *out_head_relation,
|
||||
xrt_fov *out_fovs,
|
||||
xrt_pose *out_poses);
|
||||
|
||||
void
|
||||
update_tracking(const from_headset::tracking &, const clock_offset &);
|
||||
};
|
||||
@@ -0,0 +1,237 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <netinet/in.h>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
static const int control_port = 9757;
|
||||
static const int stream_port = 9757;
|
||||
|
||||
enum class device_id : uint8_t
|
||||
{
|
||||
HEAD, // /user/head
|
||||
LEFT_CONTROLLER_HAPTIC, // /user/hand/left/output/haptic
|
||||
RIGHT_CONTROLLER_HAPTIC, // /user/hand/right/output/haptic
|
||||
LEFT_GRIP, // /user/hand/left/input/grip/pose
|
||||
LEFT_AIM, // /user/hand/left/input/aim/pose
|
||||
RIGHT_GRIP, // /user/hand/right/input/grip/pose
|
||||
RIGHT_AIM, // /user/hand/right/input/aim/pose
|
||||
X_CLICK, // /user/hand/left/input/x/click
|
||||
X_TOUCH, // /user/hand/left/input/x/touch
|
||||
Y_CLICK, // /user/hand/left/input/y/click
|
||||
Y_TOUCH, // /user/hand/left/input/y/touch
|
||||
MENU_CLICK, // /user/hand/left/input/menu/click
|
||||
LEFT_SQUEEZE_VALUE, // /user/hand/left/input/squeeze/value
|
||||
LEFT_TRIGGER_VALUE, // /user/hand/left/input/trigger/value
|
||||
LEFT_TRIGGER_TOUCH, // /user/hand/left/input/trigger/touch
|
||||
LEFT_THUMBSTICK_X, // /user/hand/left/input/thumbstick/x
|
||||
LEFT_THUMBSTICK_Y, // /user/hand/left/input/thumbstick/y
|
||||
LEFT_THUMBSTICK_CLICK, // /user/hand/left/input/thumbstick/click
|
||||
LEFT_THUMBSTICK_TOUCH, // /user/hand/left/input/thumbstick/touch
|
||||
LEFT_THUMBREST_TOUCH, // /user/hand/left/input/thumbrest/touch
|
||||
A_CLICK, // /user/hand/right/input/a/click
|
||||
A_TOUCH, // /user/hand/right/input/a/touch
|
||||
B_CLICK, // /user/hand/right/input/b/click
|
||||
B_TOUCH, // /user/hand/right/input/b/touch
|
||||
SYSTEM_CLICK, // /user/hand/right/input/system/click
|
||||
RIGHT_SQUEEZE_VALUE, // /user/hand/right/input/squeeze/value
|
||||
RIGHT_TRIGGER_VALUE, // /user/hand/right/input/trigger/value
|
||||
RIGHT_TRIGGER_TOUCH, // /user/hand/right/input/trigger/touch
|
||||
RIGHT_THUMBSTICK_X, // /user/hand/right/input/thumbstick/x
|
||||
RIGHT_THUMBSTICK_Y, // /user/hand/right/input/thumbstick/y
|
||||
RIGHT_THUMBSTICK_CLICK, // /user/hand/right/input/thumbstick/click
|
||||
RIGHT_THUMBSTICK_TOUCH, // /user/hand/right/input/thumbstick/touch
|
||||
RIGHT_THUMBREST_TOUCH, // /user/hand/right/input/thumbrest/touch
|
||||
};
|
||||
|
||||
enum video_codec
|
||||
{
|
||||
h264,
|
||||
hevc,
|
||||
h265 = hevc,
|
||||
};
|
||||
|
||||
namespace from_headset {
|
||||
|
||||
struct headset_info_packet
|
||||
{
|
||||
// First packet sent by the HMD on the control socket, not typed
|
||||
uint32_t recommended_eye_width;
|
||||
uint32_t recommended_eye_height;
|
||||
std::vector<float> available_refresh_rates;
|
||||
float preferred_refresh_rate;
|
||||
uint32_t microphone_sample_rate;
|
||||
};
|
||||
|
||||
struct tracking
|
||||
{
|
||||
enum flags : uint8_t
|
||||
{
|
||||
orientation_valid = 1 << 0,
|
||||
position_valid = 1 << 1,
|
||||
linear_velocity_valid = 1 << 2,
|
||||
angular_velocity_valid = 1 << 3,
|
||||
orientation_tracked = 1 << 4,
|
||||
position_tracked = 1 << 5
|
||||
};
|
||||
|
||||
struct pose
|
||||
{
|
||||
device_id device;
|
||||
XrPosef pose;
|
||||
XrVector3f linear_velocity;
|
||||
XrVector3f angular_velocity;
|
||||
uint8_t flags;
|
||||
};
|
||||
|
||||
struct view
|
||||
{
|
||||
// Relative to XR_REFERENCE_SPACE_TYPE_VIEW
|
||||
XrPosef pose;
|
||||
XrFovf fov;
|
||||
};
|
||||
|
||||
uint64_t timestamp;
|
||||
XrViewStateFlags flags;
|
||||
|
||||
std::array<view, 2> views;
|
||||
std::vector<pose> device_poses;
|
||||
};
|
||||
|
||||
struct inputs
|
||||
{
|
||||
struct input_value
|
||||
{
|
||||
device_id id;
|
||||
float value;
|
||||
};
|
||||
std::vector<input_value> values;
|
||||
};
|
||||
|
||||
struct timesync_response
|
||||
{
|
||||
std::chrono::nanoseconds query;
|
||||
uint64_t response;
|
||||
};
|
||||
|
||||
struct feedback
|
||||
{
|
||||
uint64_t frame_index;
|
||||
uint8_t stream_index;
|
||||
|
||||
// Timestamps
|
||||
uint64_t received_first_packet;
|
||||
uint64_t received_last_packet;
|
||||
uint64_t reconstructed;
|
||||
uint64_t sent_to_decoder;
|
||||
uint64_t received_from_decoder;
|
||||
uint64_t blitted;
|
||||
uint64_t displayed;
|
||||
|
||||
std::array<XrPosef, 2> received_pose;
|
||||
std::array<XrPosef, 2> real_pose;
|
||||
|
||||
uint8_t data_packets;
|
||||
uint8_t parity_packets;
|
||||
uint8_t received_data_packets;
|
||||
uint8_t received_parity_packets;
|
||||
};
|
||||
|
||||
using control_packets = std::variant<headset_info_packet, feedback>;
|
||||
using stream_packets = std::variant<tracking, inputs, timesync_response>;
|
||||
} // namespace from_headset
|
||||
|
||||
namespace to_headset {
|
||||
|
||||
struct video_stream_description
|
||||
{
|
||||
struct item
|
||||
{
|
||||
uint16_t width;
|
||||
uint16_t height;
|
||||
uint16_t offset_x;
|
||||
uint16_t offset_y;
|
||||
video_codec codec;
|
||||
};
|
||||
uint16_t width;
|
||||
uint16_t height;
|
||||
float fps;
|
||||
std::vector<item> items;
|
||||
};
|
||||
|
||||
struct video_stream_data_shard
|
||||
{
|
||||
|
||||
inline static const size_t max_payload_size = 1400;
|
||||
enum flags : uint8_t
|
||||
{
|
||||
start_of_slice = 1,
|
||||
end_of_slice = 1 << 1,
|
||||
end_of_frame = 1 << 2,
|
||||
};
|
||||
// Identifier of stream in video_stream_description
|
||||
uint8_t stream_item_idx;
|
||||
// Counter increased for each frame
|
||||
uint64_t frame_idx;
|
||||
// Identifier of the shard within the frame
|
||||
uint16_t shard_idx;
|
||||
uint8_t flags;
|
||||
|
||||
// Actual video data, may contain multiple NAL units
|
||||
std::vector<uint8_t> payload;
|
||||
|
||||
// Position information, must be present on last video shard
|
||||
struct view_info_t
|
||||
{
|
||||
// ns in headset time referential
|
||||
uint64_t display_time;
|
||||
|
||||
std::array<XrPosef, 2> pose;
|
||||
std::array<XrFovf, 2> fov;
|
||||
};
|
||||
std::optional<view_info_t> view_info;
|
||||
};
|
||||
|
||||
struct video_stream_parity_shard
|
||||
{
|
||||
uint8_t stream_item_idx;
|
||||
uint64_t frame_idx;
|
||||
uint16_t data_shard_count;
|
||||
uint8_t num_parity_elements;
|
||||
uint8_t parity_element;
|
||||
// Parity data
|
||||
std::vector<uint8_t> payload;
|
||||
};
|
||||
|
||||
struct haptics
|
||||
{
|
||||
device_id id;
|
||||
std::chrono::nanoseconds duration;
|
||||
float frequency;
|
||||
float amplitude;
|
||||
};
|
||||
|
||||
struct timesync_query
|
||||
{
|
||||
std::chrono::nanoseconds query;
|
||||
};
|
||||
|
||||
using stream_packets =
|
||||
std::variant<video_stream_data_shard, video_stream_parity_shard, haptics, timesync_query>;
|
||||
using control_packets = std::variant<video_stream_description>;
|
||||
|
||||
} // namespace to_headset
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,522 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "boost/pfr/core.hpp"
|
||||
#include "boost/pfr/tuple_size.hpp"
|
||||
#include <array>
|
||||
#include <boost/pfr.hpp>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
namespace details {
|
||||
struct hash_context
|
||||
{
|
||||
// FNV1a hash
|
||||
static const uint64_t fnv_prime = 0x100000001b3;
|
||||
static const uint64_t fnv_offset_basis = 0xcbf29ce484222325;
|
||||
uint64_t hash = fnv_offset_basis;
|
||||
|
||||
constexpr uint64_t
|
||||
feed(std::string_view s)
|
||||
{
|
||||
for (const char c : s)
|
||||
hash = (hash ^ c) * fnv_prime;
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
constexpr uint64_t
|
||||
feed_unsigned(uint64_t n)
|
||||
{
|
||||
if (n >= 10)
|
||||
feed(n / 10);
|
||||
|
||||
char digit[] = "0";
|
||||
digit[0] += n % 10;
|
||||
feed(digit);
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
constexpr uint64_t
|
||||
feed(int64_t n)
|
||||
{
|
||||
if (n < 0) {
|
||||
feed("-");
|
||||
feed_unsigned(static_cast<uint64_t>(-n));
|
||||
} else {
|
||||
feed_unsigned(static_cast<uint64_t>(n));
|
||||
}
|
||||
|
||||
return hash;
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
|
||||
template <typename T, typename Enable = void> struct serialization_traits;
|
||||
|
||||
class deserialization_error : public std::runtime_error
|
||||
{
|
||||
public:
|
||||
deserialization_error() : std::runtime_error("Deserialization error") {}
|
||||
};
|
||||
|
||||
class serialization_packet
|
||||
{
|
||||
std::vector<uint8_t> buffer;
|
||||
|
||||
public:
|
||||
serialization_packet() = default;
|
||||
|
||||
void
|
||||
write(const void *data, size_t size)
|
||||
{
|
||||
size_t index = buffer.size();
|
||||
buffer.resize(index + size);
|
||||
memcpy(&buffer[index], data, size);
|
||||
}
|
||||
|
||||
const uint8_t *
|
||||
data() const
|
||||
{
|
||||
return buffer.data();
|
||||
}
|
||||
size_t
|
||||
size() const
|
||||
{
|
||||
return buffer.size();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void
|
||||
serialize(const T &value)
|
||||
{
|
||||
serialization_traits<T>::serialize(value, *this);
|
||||
}
|
||||
|
||||
operator std::vector<uint8_t> &&() &&
|
||||
{
|
||||
return std::move(buffer);
|
||||
}
|
||||
};
|
||||
|
||||
class deserialization_packet
|
||||
{
|
||||
std::vector<uint8_t> buffer;
|
||||
size_t read_index;
|
||||
|
||||
public:
|
||||
deserialization_packet() : read_index(0) {}
|
||||
explicit deserialization_packet(std::vector<uint8_t> buffer, size_t skip = 0)
|
||||
: buffer(std::move(buffer)), read_index(skip)
|
||||
{}
|
||||
|
||||
void
|
||||
read(void *data, size_t size)
|
||||
{
|
||||
check_remaining_size(size);
|
||||
|
||||
memcpy(data, &buffer[read_index], size);
|
||||
read_index += size;
|
||||
}
|
||||
|
||||
size_t
|
||||
remaining() const
|
||||
{
|
||||
return buffer.size() - read_index;
|
||||
}
|
||||
|
||||
bool
|
||||
empty() const
|
||||
{
|
||||
return buffer.size() <= read_index;
|
||||
}
|
||||
|
||||
void
|
||||
check_remaining_size(size_t min_size) const
|
||||
{
|
||||
if (min_size > remaining())
|
||||
throw deserialization_error();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T
|
||||
deserialize()
|
||||
{
|
||||
return serialization_traits<T>::deserialize(*this);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> struct serialization_traits<T, std::enable_if_t<std::is_arithmetic_v<T>>>
|
||||
{
|
||||
static constexpr void
|
||||
type_hash(details::hash_context &h)
|
||||
{
|
||||
if constexpr (std::is_floating_point_v<T>)
|
||||
h.feed("float");
|
||||
else if constexpr (std::is_integral_v<T>) {
|
||||
if constexpr (std::is_unsigned_v<T>)
|
||||
h.feed("uint");
|
||||
else
|
||||
h.feed("int");
|
||||
}
|
||||
|
||||
h.feed(sizeof(T) * 8);
|
||||
}
|
||||
|
||||
static void
|
||||
serialize(T value, serialization_packet &packet)
|
||||
{
|
||||
packet.write(&value, sizeof(value));
|
||||
}
|
||||
|
||||
static T
|
||||
deserialize(deserialization_packet &packet)
|
||||
{
|
||||
T value;
|
||||
packet.read((char *)&value, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> struct serialization_traits<T, std::enable_if_t<std::is_enum_v<T>>>
|
||||
{
|
||||
static constexpr void
|
||||
type_hash(details::hash_context &h)
|
||||
{
|
||||
h.feed("enum");
|
||||
h.feed(sizeof(T) * 8);
|
||||
}
|
||||
|
||||
static void
|
||||
serialize(T value, serialization_packet &packet)
|
||||
{
|
||||
packet.write(&value, sizeof(value));
|
||||
}
|
||||
|
||||
static T
|
||||
deserialize(deserialization_packet &packet)
|
||||
{
|
||||
T value;
|
||||
packet.read((char *)&value, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <class> struct is_stdarray : public std::false_type
|
||||
{
|
||||
};
|
||||
|
||||
template <class T, size_t N> struct is_stdarray<std::array<T, N>> : public std::true_type
|
||||
{
|
||||
};
|
||||
|
||||
template <typename T> inline constexpr bool is_stdarray_v = is_stdarray<T>::value;
|
||||
|
||||
template <typename T> struct serialization_traits<T, std::enable_if_t<std::is_aggregate_v<T> && !is_stdarray_v<T>>>
|
||||
{
|
||||
template <size_t I>
|
||||
static constexpr void
|
||||
aux2(details::hash_context &h)
|
||||
{
|
||||
if constexpr (I > 0)
|
||||
h.feed(",");
|
||||
serialization_traits<boost::pfr::tuple_element_t<I, T>>::type_hash(h);
|
||||
}
|
||||
|
||||
template <size_t... I>
|
||||
static constexpr void
|
||||
aux1(details::hash_context &h, std::index_sequence<I...>)
|
||||
{
|
||||
(aux2<I>(h), ...);
|
||||
}
|
||||
|
||||
static constexpr void
|
||||
type_hash(details::hash_context &h)
|
||||
{
|
||||
h.feed("structure{");
|
||||
aux1(h, std::make_index_sequence<boost::pfr::tuple_size_v<T>>());
|
||||
h.feed("}");
|
||||
}
|
||||
|
||||
static void
|
||||
serialize(const T &value, serialization_packet &packet)
|
||||
{
|
||||
boost::pfr::for_each_field(value, [&](const auto &x) { packet.serialize(x); });
|
||||
}
|
||||
|
||||
static T
|
||||
deserialize(deserialization_packet &packet)
|
||||
{
|
||||
T value;
|
||||
|
||||
boost::pfr::for_each_field(
|
||||
value, [&](auto &x) { x = packet.deserialize<std::remove_reference_t<decltype(x)>>(); });
|
||||
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <> struct serialization_traits<std::string>
|
||||
{
|
||||
static constexpr void
|
||||
type_hash(details::hash_context &h)
|
||||
{
|
||||
h.feed("string");
|
||||
}
|
||||
|
||||
static void
|
||||
serialize(const std::string &value, serialization_packet &packet)
|
||||
{
|
||||
packet.serialize<uint64_t>(value.size());
|
||||
packet.write(value.data(), value.size());
|
||||
}
|
||||
|
||||
static std::string
|
||||
deserialize(deserialization_packet &packet)
|
||||
{
|
||||
std::string value;
|
||||
size_t size = packet.deserialize<uint64_t>();
|
||||
|
||||
packet.check_remaining_size(size);
|
||||
|
||||
value.resize(size);
|
||||
packet.read(value.data(), size);
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> struct serialization_traits<std::vector<T>>
|
||||
{
|
||||
static constexpr void
|
||||
type_hash(details::hash_context &h)
|
||||
{
|
||||
h.feed("vector<");
|
||||
serialization_traits<T>::type_hash(h);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void
|
||||
serialize(const std::vector<T> &value, serialization_packet &packet)
|
||||
{
|
||||
packet.serialize<uint64_t>(value.size());
|
||||
|
||||
for (const T &i : value)
|
||||
packet.serialize<T>(i);
|
||||
}
|
||||
|
||||
static std::vector<T>
|
||||
deserialize(deserialization_packet &packet)
|
||||
{
|
||||
std::vector<T> value;
|
||||
size_t size = packet.deserialize<uint64_t>();
|
||||
|
||||
packet.check_remaining_size(size);
|
||||
|
||||
value.reserve(size);
|
||||
for (size_t i = 0; i < size; i++) {
|
||||
value.emplace_back(packet.deserialize<T>());
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> struct serialization_traits<std::optional<T>>
|
||||
{
|
||||
static constexpr void
|
||||
type_hash(details::hash_context &h)
|
||||
{
|
||||
h.feed("optional<");
|
||||
serialization_traits<T>::type_hash(h);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void
|
||||
serialize(const std::optional<T> &value, serialization_packet &packet)
|
||||
{
|
||||
if (value) {
|
||||
packet.serialize<bool>(true);
|
||||
packet.serialize<T>(*value);
|
||||
} else {
|
||||
packet.serialize<bool>(false);
|
||||
}
|
||||
}
|
||||
|
||||
static std::optional<T>
|
||||
deserialize(deserialization_packet &packet)
|
||||
{
|
||||
if (packet.deserialize<bool>())
|
||||
return packet.deserialize<T>();
|
||||
else
|
||||
return std::nullopt;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, size_t N> struct serialization_traits<std::array<T, N>>
|
||||
{
|
||||
static constexpr void
|
||||
type_hash(details::hash_context &h)
|
||||
{
|
||||
h.feed("array<");
|
||||
serialization_traits<T>::type_hash(h);
|
||||
h.feed(",");
|
||||
h.feed(N);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void
|
||||
serialize(const std::array<T, N> &value, serialization_packet &packet)
|
||||
{
|
||||
for (const T &i : value)
|
||||
packet.serialize<T>(i);
|
||||
}
|
||||
|
||||
static std::array<T, N>
|
||||
deserialize(deserialization_packet &packet)
|
||||
{
|
||||
std::array<T, N> value;
|
||||
|
||||
for (size_t i = 0; i < N; i++) {
|
||||
value[i] = packet.deserialize<T>();
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename... T> struct serialization_traits<std::variant<T...>>
|
||||
{
|
||||
template <typename U, typename... V>
|
||||
static constexpr void
|
||||
type_list_hash(details::hash_context &h)
|
||||
{
|
||||
serialization_traits<U>::type_hash(h);
|
||||
|
||||
if constexpr (sizeof...(V) > 0) {
|
||||
h.feed(",");
|
||||
type_list_hash<V...>(h);
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr void
|
||||
type_hash(details::hash_context &h)
|
||||
{
|
||||
h.feed("variant<");
|
||||
type_list_hash<T...>(h);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void
|
||||
serialize(const std::variant<T...> &value, serialization_packet &packet)
|
||||
{
|
||||
packet.serialize<uint32_t>(value.index());
|
||||
std::visit([&](const auto &x) { packet.serialize(x); }, value);
|
||||
}
|
||||
|
||||
template <size_t I> using i_th_type = std::tuple_element_t<I, std::tuple<T...>>;
|
||||
|
||||
template <size_t... I>
|
||||
static std::variant<T...>
|
||||
deserialize_aux(deserialization_packet &packet, size_t type_index, std::index_sequence<I...>)
|
||||
{
|
||||
std::variant<T...> value;
|
||||
((I == type_index ? (void)(value = packet.deserialize<i_th_type<I>>()) : (void)0), ...);
|
||||
return value;
|
||||
}
|
||||
|
||||
static std::variant<T...>
|
||||
deserialize(deserialization_packet &packet)
|
||||
{
|
||||
uint32_t type_index = packet.deserialize<uint32_t>();
|
||||
if (type_index >= sizeof...(T))
|
||||
throw deserialization_error();
|
||||
|
||||
return deserialize_aux(packet, type_index, std::make_index_sequence<sizeof...(T)>());
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Rep, typename Period> struct serialization_traits<std::chrono::duration<Rep, Period>>
|
||||
{
|
||||
static constexpr void
|
||||
type_hash(details::hash_context &h)
|
||||
{
|
||||
h.feed("duration<");
|
||||
serialization_traits<Rep>::type_hash(h);
|
||||
h.feed(",");
|
||||
h.feed(Period::num);
|
||||
h.feed("/");
|
||||
h.feed(Period::den);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void
|
||||
serialize(const std::chrono::duration<Rep, Period> &value, serialization_packet &packet)
|
||||
{
|
||||
packet.serialize<Rep>(value.count());
|
||||
}
|
||||
|
||||
static std::chrono::duration<Rep, Period>
|
||||
deserialize(deserialization_packet &packet)
|
||||
{
|
||||
Rep nsec = packet.deserialize<Rep>();
|
||||
return std::chrono::duration<Rep, Period>{nsec};
|
||||
}
|
||||
};
|
||||
|
||||
namespace unit_tests {
|
||||
template <typename T>
|
||||
constexpr uint64_t
|
||||
hash(T s)
|
||||
{
|
||||
return details::hash_context{}.feed(s);
|
||||
}
|
||||
|
||||
static_assert(hash("test") == 0xf9e6e6ef197c2b25);
|
||||
static_assert(hash(1234) == 0x1fabbdf10314a21d);
|
||||
static_assert(hash(-1234) == 0x77fa1c9653db5a84);
|
||||
static_assert(hash(0) == 0xaf63ad4c86019caf);
|
||||
|
||||
template <typename T>
|
||||
constexpr uint64_t
|
||||
serialization_type_hash()
|
||||
{
|
||||
details::hash_context h;
|
||||
serialization_traits<T>::type_hash(h);
|
||||
return h.hash;
|
||||
}
|
||||
|
||||
static_assert(serialization_type_hash<bool>() == hash("uint8"));
|
||||
static_assert(serialization_type_hash<int>() == hash("int32"));
|
||||
static_assert(serialization_type_hash<float>() == hash("float32"));
|
||||
static_assert(serialization_type_hash<double>() == hash("float64"));
|
||||
static_assert(serialization_type_hash<std::chrono::nanoseconds>() == hash("duration<int64,1/1000000000>"));
|
||||
static_assert(serialization_type_hash<std::optional<int>>() == hash("optional<int32>"));
|
||||
static_assert(serialization_type_hash<std::vector<int>>() == hash("vector<int32>"));
|
||||
static_assert(serialization_type_hash<std::array<int, 42>>() == hash("array<int32,42>"));
|
||||
static_assert(serialization_type_hash<std::string>() == hash("string"));
|
||||
static_assert(serialization_type_hash<std::variant<int, float>>() == hash("variant<int32,float32>"));
|
||||
|
||||
struct test
|
||||
{
|
||||
int x;
|
||||
float y;
|
||||
};
|
||||
static_assert(serialization_type_hash<test>() == hash("structure{int32,float32}"));
|
||||
} // namespace unit_tests
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,187 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "wivrn_session.h"
|
||||
#include "os/os_time.h"
|
||||
#include "util/u_logging.h"
|
||||
|
||||
#include "wivrn_controller.h"
|
||||
#include "wivrn_hmd.h"
|
||||
|
||||
xrt::drivers::wivrn::wivrn_session::wivrn_session(xrt::drivers::wivrn::TCP &&tcp, in6_addr &address) : connection(std::move(tcp), address)
|
||||
{
|
||||
}
|
||||
|
||||
xrt_system_devices *
|
||||
xrt::drivers::wivrn::wivrn_session::create_session(xrt::drivers::wivrn::TCP &&tcp)
|
||||
{
|
||||
sockaddr_in6 address;
|
||||
socklen_t address_len = sizeof(address);
|
||||
if (getpeername(tcp.get_fd(), (sockaddr*)&address, &address_len) < 0)
|
||||
{
|
||||
U_LOG_E("Cannot get peer address: %s", strerror(errno));
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::shared_ptr<wivrn_session> self;
|
||||
std::optional<xrt::drivers::wivrn::from_headset::control_packets> control;
|
||||
try
|
||||
{
|
||||
self = std::shared_ptr<wivrn_session>(new wivrn_session(std::move(tcp), address.sin6_addr));
|
||||
control = self->connection.poll_control(-1);
|
||||
}
|
||||
catch(std::exception& e)
|
||||
{
|
||||
U_LOG_E("Error creating WiVRn session: %s", e.what());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (control) {
|
||||
const auto &info = std::get<from_headset::headset_info_packet>(*control);
|
||||
self->hmd = std::make_unique<wivrn_hmd>(self, info);
|
||||
self->left_hand = std::make_unique<wivrn_controller>(0, self->hmd.get(), self);
|
||||
self->right_hand = std::make_unique<wivrn_controller>(1, self->hmd.get(), self);
|
||||
} else {
|
||||
throw std::runtime_error("no packet received from headset, failed to initialise");
|
||||
}
|
||||
|
||||
xrt_system_devices * devices = new xrt_system_devices{};
|
||||
|
||||
int n = 0;
|
||||
if (self->hmd)
|
||||
devices->roles.head = devices->xdevs[n++] = self->hmd.get();
|
||||
if (self->left_hand)
|
||||
devices->roles.left = devices->xdevs[n++] = self->left_hand.get();
|
||||
if (self->right_hand)
|
||||
devices->roles.right = devices->xdevs[n++] = self->right_hand.get();
|
||||
|
||||
devices->xdev_count = n;
|
||||
devices->destroy = [](xrt_system_devices * xsd){
|
||||
// TODO
|
||||
};
|
||||
|
||||
#if 0
|
||||
// For debugging purposes
|
||||
self->feedback_csv.open("feedback.csv");
|
||||
#endif
|
||||
|
||||
self->thread = std::thread(&wivrn_session::run, self);
|
||||
return devices;
|
||||
}
|
||||
|
||||
|
||||
clock_offset
|
||||
wivrn_session::get_offset()
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
return offset;
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_session::operator()(from_headset::headset_info_packet &&)
|
||||
{
|
||||
U_LOG_W("unexpected headset info packet, ignoring");
|
||||
}
|
||||
void
|
||||
wivrn_session::operator()(from_headset::tracking &&tracking)
|
||||
{
|
||||
if (offset.epoch_offset.count() == 0)
|
||||
return;
|
||||
|
||||
hmd->update_tracking(tracking, offset);
|
||||
left_hand->update_tracking(tracking, offset);
|
||||
right_hand->update_tracking(tracking, offset);
|
||||
}
|
||||
void
|
||||
wivrn_session::operator()(from_headset::inputs &&inputs)
|
||||
{
|
||||
left_hand->set_inputs(inputs);
|
||||
right_hand->set_inputs(inputs);
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_session::operator()(from_headset::timesync_response &×ync)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
offset.epoch_offset = std::chrono::nanoseconds(timesync.response) - timesync.query;
|
||||
offset_age = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_session::operator()(from_headset::feedback &&feedback)
|
||||
{
|
||||
if (feedback_csv) {
|
||||
feedback_csv << feedback.frame_index << "," << feedback.received_first_packet << ","
|
||||
<< feedback.received_last_packet << "," << feedback.reconstructed << ","
|
||||
<< feedback.sent_to_decoder << "," << feedback.received_from_decoder << ","
|
||||
<< feedback.blitted << "," << feedback.displayed << ",";
|
||||
|
||||
XrQuaternionf q;
|
||||
XrVector3f x;
|
||||
|
||||
q = feedback.received_pose[0].orientation;
|
||||
feedback_csv << q.x << "," << q.y << "," << q.z << "," << q.w << ",";
|
||||
x = feedback.received_pose[0].position;
|
||||
feedback_csv << x.x << "," << x.y << "," << x.z << ",";
|
||||
|
||||
q = feedback.received_pose[1].orientation;
|
||||
feedback_csv << q.x << "," << q.y << "," << q.z << "," << q.w << ",";
|
||||
x = feedback.received_pose[1].position;
|
||||
feedback_csv << x.x << "," << x.y << "," << x.z << ",";
|
||||
|
||||
q = feedback.real_pose[0].orientation;
|
||||
feedback_csv << q.x << "," << q.y << "," << q.z << "," << q.w << ",";
|
||||
x = feedback.real_pose[0].position;
|
||||
feedback_csv << x.x << "," << x.y << "," << x.z << ",";
|
||||
|
||||
q = feedback.real_pose[1].orientation;
|
||||
feedback_csv << q.x << "," << q.y << "," << q.z << "," << q.w << ",";
|
||||
x = feedback.real_pose[1].position;
|
||||
feedback_csv << x.x << "," << x.y << "," << x.z << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t
|
||||
clock_offset::from_headset(uint64_t ts) const
|
||||
{
|
||||
return ts - epoch_offset.count();
|
||||
}
|
||||
|
||||
std::chrono::nanoseconds
|
||||
clock_offset::to_headset(uint64_t timestamp_ns) const
|
||||
{
|
||||
return std::chrono::nanoseconds(timestamp_ns) + epoch_offset;
|
||||
}
|
||||
|
||||
void
|
||||
wivrn_session::run(std::weak_ptr<wivrn_session> weak_self)
|
||||
{
|
||||
while (true) {
|
||||
try {
|
||||
auto self = weak_self.lock();
|
||||
if (self and not self->quit) {
|
||||
{
|
||||
std::lock_guard lock(self->mutex);
|
||||
if (std::chrono::steady_clock::now() - self->offset_age >
|
||||
std::chrono::seconds(5)) {
|
||||
to_headset::timesync_query timesync{};
|
||||
timesync.query = std::chrono::nanoseconds(os_monotonic_get_ns());
|
||||
self->connection.send_stream(timesync);
|
||||
}
|
||||
}
|
||||
self->connection.poll(*self, 20);
|
||||
} else
|
||||
return;
|
||||
} catch (const std::exception &e) {
|
||||
U_LOG_E("Exception in network thread: %s", e.what());
|
||||
auto self = weak_self.lock();
|
||||
if (self)
|
||||
{
|
||||
self->quit = true;
|
||||
exit(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "wivrn_packets.h"
|
||||
#include "wivrn_connection.h"
|
||||
#include "xrt/xrt_system.h"
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <fstream>
|
||||
|
||||
class wivrn_hmd;
|
||||
class wivrn_controller;
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
|
||||
struct clock_offset
|
||||
{
|
||||
std::chrono::nanoseconds epoch_offset{};
|
||||
|
||||
uint64_t from_headset(uint64_t) const;
|
||||
|
||||
std::chrono::nanoseconds
|
||||
to_headset(uint64_t timestamp_ns) const;
|
||||
};
|
||||
|
||||
class wivrn_session : public std::enable_shared_from_this<wivrn_session>
|
||||
{
|
||||
wivrn_connection connection;
|
||||
|
||||
std::atomic<bool> quit = false;
|
||||
std::thread thread;
|
||||
std::mutex mutex;
|
||||
|
||||
std::unique_ptr<wivrn_hmd> hmd;
|
||||
std::unique_ptr<wivrn_controller> left_hand;
|
||||
std::unique_ptr<wivrn_controller> right_hand;
|
||||
|
||||
clock_offset offset;
|
||||
std::chrono::steady_clock::time_point offset_age{};
|
||||
|
||||
std::ofstream feedback_csv;
|
||||
|
||||
wivrn_session(TCP&& tcp, in6_addr &address);
|
||||
|
||||
public:
|
||||
static xrt_system_devices *
|
||||
create_session(TCP&& tcp);
|
||||
|
||||
clock_offset
|
||||
get_offset();
|
||||
|
||||
void
|
||||
operator()(from_headset::headset_info_packet &&);
|
||||
void
|
||||
operator()(from_headset::tracking &&);
|
||||
void
|
||||
operator()(from_headset::inputs &&);
|
||||
void
|
||||
operator()(from_headset::timesync_response &&);
|
||||
void
|
||||
operator()(from_headset::feedback &&);
|
||||
|
||||
template <typename T>
|
||||
void
|
||||
send_stream(const T &packet)
|
||||
{
|
||||
connection.send_stream(packet);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void
|
||||
send_control(const T &packet)
|
||||
{
|
||||
connection.send_control(packet);
|
||||
}
|
||||
|
||||
private:
|
||||
static void run(std::weak_ptr<wivrn_session>);
|
||||
};
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,315 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "wivrn_sockets.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <cassert>
|
||||
#include <netdb.h>
|
||||
#include <netinet/ip.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <system_error>
|
||||
#include <unistd.h>
|
||||
#include <netinet/tcp.h>
|
||||
|
||||
const char *
|
||||
xrt::drivers::wivrn::invalid_packet::what() const noexcept
|
||||
{
|
||||
return "Invalid packet";
|
||||
}
|
||||
|
||||
const char *
|
||||
xrt::drivers::wivrn::socket_shutdown::what() const noexcept
|
||||
{
|
||||
return "Socket shutdown";
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::socket_base::socket_base(xrt::drivers::wivrn::socket_base &&other) : fd(other.fd)
|
||||
{
|
||||
other.fd = -1;
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::socket_base::~socket_base()
|
||||
{
|
||||
if (fd >= 0) {
|
||||
::close(fd);
|
||||
}
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::UDP::UDP()
|
||||
{
|
||||
fd = socket(AF_INET6, SOCK_DGRAM, 0);
|
||||
|
||||
if (fd < 0) {
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
xrt::drivers::wivrn::UDP::bind(int port)
|
||||
{
|
||||
sockaddr_in6 bind_addr{};
|
||||
bind_addr.sin6_family = AF_INET6;
|
||||
bind_addr.sin6_addr = IN6ADDR_ANY_INIT;
|
||||
bind_addr.sin6_port = htons(port);
|
||||
|
||||
if (::bind(fd, (sockaddr *)&bind_addr, sizeof(bind_addr)) < 0) {
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
xrt::drivers::wivrn::UDP::connect(in6_addr address, int port)
|
||||
{
|
||||
sockaddr_in6 sa;
|
||||
sa.sin6_family = AF_INET6;
|
||||
sa.sin6_addr = address;
|
||||
sa.sin6_port = htons(port);
|
||||
|
||||
if (::connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0) {
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
xrt::drivers::wivrn::UDP::connect(in_addr address, int port)
|
||||
{
|
||||
sockaddr_in sa;
|
||||
sa.sin_family = AF_INET;
|
||||
sa.sin_addr = address;
|
||||
sa.sin_port = htons(port);
|
||||
|
||||
if (::connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
void
|
||||
xrt::drivers::wivrn::UDP::subscribe_multicast(in6_addr address)
|
||||
{
|
||||
assert(IN6_IS_ADDR_MULTICAST(&address));
|
||||
|
||||
ipv6_mreq subscribe{};
|
||||
subscribe.ipv6mr_multiaddr = address;
|
||||
|
||||
if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &subscribe, sizeof(subscribe)) < 0) {
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
xrt::drivers::wivrn::UDP::unsubscribe_multicast(in6_addr address)
|
||||
{
|
||||
assert(IN6_IS_ADDR_MULTICAST(&address));
|
||||
|
||||
ipv6_mreq subscribe{};
|
||||
subscribe.ipv6mr_multiaddr = address;
|
||||
|
||||
if (setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &subscribe, sizeof(subscribe)) < 0) {
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
xrt::drivers::wivrn::UDP::set_receive_buffer_size(int size)
|
||||
{
|
||||
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
|
||||
}
|
||||
|
||||
void
|
||||
xrt::drivers::wivrn::TCP::init()
|
||||
{
|
||||
int nodelay = 1;
|
||||
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) {
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
mutex = std::make_unique<std::mutex>();
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::TCP::TCP(int fd)
|
||||
{
|
||||
this->fd = fd;
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::TCP::TCP(in6_addr address, int port)
|
||||
{
|
||||
fd = socket(AF_INET6, SOCK_STREAM, 0);
|
||||
|
||||
if (fd < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
sockaddr_in6 sa;
|
||||
sa.sin6_family = AF_INET6;
|
||||
sa.sin6_addr = address;
|
||||
sa.sin6_port = htons(port);
|
||||
|
||||
if (connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0) {
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::TCP::TCP(in_addr address, int port)
|
||||
{
|
||||
fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
|
||||
if (fd < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
sockaddr_in sa;
|
||||
sa.sin_family = AF_INET;
|
||||
sa.sin_addr = address;
|
||||
sa.sin_port = htons(port);
|
||||
|
||||
if (connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0) {
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::TCPListener::TCPListener(int port)
|
||||
{
|
||||
fd = socket(AF_INET6, SOCK_STREAM, 0);
|
||||
|
||||
if (fd < 0) {
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
int reuse_addr = 1;
|
||||
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)) < 0) {
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
sockaddr_in6 addr{};
|
||||
addr.sin6_family = AF_INET6;
|
||||
addr.sin6_port = htons(port);
|
||||
addr.sin6_addr = in6addr_any;
|
||||
|
||||
if (bind(fd, (sockaddr *)&addr, sizeof(addr)) < 0) {
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
int backlog = 1;
|
||||
if (listen(fd, backlog) < 0) {
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
std::pair<xrt::drivers::wivrn::TCP, sockaddr_in6>
|
||||
xrt::drivers::wivrn::TCPListener::accept()
|
||||
{
|
||||
sockaddr_in6 addr{};
|
||||
socklen_t addrlen = sizeof(addr);
|
||||
|
||||
int fd2 = ::accept(fd, (sockaddr *)&addr, &addrlen);
|
||||
if (fd2 < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
return {TCP{fd2}, addr};
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::deserialization_packet
|
||||
xrt::drivers::wivrn::UDP::receive_raw()
|
||||
{
|
||||
std::vector<uint8_t> buffer(2000);
|
||||
|
||||
ssize_t received = recv(fd, buffer.data(), buffer.size(), 0);
|
||||
if (received < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
buffer.resize(received);
|
||||
|
||||
return deserialization_packet{buffer};
|
||||
}
|
||||
|
||||
void
|
||||
xrt::drivers::wivrn::UDP::send_raw(const std::vector<uint8_t> &data)
|
||||
{
|
||||
if (::send(fd, data.data(), data.size(), 0) < 0) {
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::deserialization_packet
|
||||
xrt::drivers::wivrn::TCP::receive_raw()
|
||||
{
|
||||
size_t expected_size;
|
||||
size_t already_received = buffer.size();
|
||||
|
||||
if (already_received < 4) {
|
||||
expected_size = 4 - buffer.size();
|
||||
} else {
|
||||
uint32_t payload_size = *reinterpret_cast<uint32_t *>(buffer.data());
|
||||
expected_size = payload_size + 4 - buffer.size();
|
||||
}
|
||||
|
||||
buffer.resize(already_received + expected_size);
|
||||
ssize_t received = recv(fd, buffer.data() + already_received, expected_size, MSG_DONTWAIT);
|
||||
|
||||
if (received < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
if (received == 0)
|
||||
throw socket_shutdown{};
|
||||
|
||||
buffer.resize(already_received + received);
|
||||
|
||||
if (buffer.size() < 4)
|
||||
return {};
|
||||
|
||||
uint32_t payload_size = *reinterpret_cast<uint32_t *>(buffer.data());
|
||||
if (buffer.size() < 4 + payload_size)
|
||||
return {};
|
||||
|
||||
assert(buffer.size() == 4 + payload_size);
|
||||
|
||||
std::vector<uint8_t> new_buffer;
|
||||
std::swap(buffer, new_buffer);
|
||||
|
||||
return deserialization_packet{std::move(new_buffer), 4};
|
||||
}
|
||||
|
||||
void
|
||||
xrt::drivers::wivrn::TCP::send_raw(const std::vector<uint8_t> &data)
|
||||
{
|
||||
std::lock_guard lock(*mutex);
|
||||
|
||||
uint32_t size = data.size();
|
||||
ssize_t sent = ::send(fd, &size, sizeof(size), MSG_NOSIGNAL);
|
||||
|
||||
if (sent == 0) {
|
||||
throw socket_shutdown{};
|
||||
}
|
||||
if (sent < 0) {
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
assert(sent == sizeof(size));
|
||||
|
||||
size_t index = 0;
|
||||
while (index < data.size()) {
|
||||
sent = ::send(fd, data.data() + index, data.size() - index, MSG_NOSIGNAL);
|
||||
|
||||
if (sent == 0) {
|
||||
throw socket_shutdown{};
|
||||
} else if (sent < 0) {
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
index += sent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "wivrn_serialization.h"
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <netinet/ip.h>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace xrt::drivers::wivrn {
|
||||
class socket_shutdown : public std::exception
|
||||
{
|
||||
public:
|
||||
const char *
|
||||
what() const noexcept override;
|
||||
};
|
||||
|
||||
class invalid_packet : public std::exception
|
||||
{
|
||||
public:
|
||||
const char *
|
||||
what() const noexcept override;
|
||||
};
|
||||
|
||||
template <typename T, typename... Ts> struct index_of_type
|
||||
{
|
||||
};
|
||||
|
||||
template <typename T, typename... Ts> struct index_of_type<T, T, Ts...> : std::integral_constant<size_t, 0>
|
||||
{
|
||||
};
|
||||
|
||||
template <typename T, typename T2, typename... Ts>
|
||||
struct index_of_type<T, T2, Ts...> : std::integral_constant<size_t, 1 + index_of_type<T, Ts...>::value>
|
||||
{
|
||||
};
|
||||
|
||||
static_assert(index_of_type<int, int, float>::value == 0);
|
||||
static_assert(index_of_type<float, int, float>::value == 1);
|
||||
|
||||
class socket_base
|
||||
{
|
||||
protected:
|
||||
int fd = -1;
|
||||
|
||||
socket_base() = default;
|
||||
socket_base(const socket_base &) = delete;
|
||||
socket_base(socket_base &&);
|
||||
~socket_base();
|
||||
|
||||
public:
|
||||
int
|
||||
get_fd() const
|
||||
{
|
||||
return fd;
|
||||
}
|
||||
};
|
||||
|
||||
class UDP : public socket_base
|
||||
{
|
||||
public:
|
||||
UDP();
|
||||
UDP(const UDP &) = delete;
|
||||
UDP(UDP &&) = default;
|
||||
|
||||
deserialization_packet
|
||||
receive_raw();
|
||||
void
|
||||
send_raw(const std::vector<uint8_t> &data);
|
||||
|
||||
void
|
||||
connect(in6_addr address, int port);
|
||||
void
|
||||
connect(in_addr address, int port);
|
||||
void
|
||||
bind(int port);
|
||||
void
|
||||
subscribe_multicast(in6_addr address);
|
||||
void
|
||||
unsubscribe_multicast(in6_addr address);
|
||||
void
|
||||
set_receive_buffer_size(int size);
|
||||
};
|
||||
|
||||
class TCP : public socket_base
|
||||
{
|
||||
std::vector<uint8_t> buffer;
|
||||
std::unique_ptr<std::mutex> mutex;
|
||||
|
||||
void
|
||||
init();
|
||||
|
||||
public:
|
||||
TCP(in6_addr address, int port);
|
||||
TCP(in_addr address, int port);
|
||||
explicit TCP(int fd);
|
||||
TCP(const TCP &) = delete;
|
||||
TCP(TCP &&) = default;
|
||||
|
||||
deserialization_packet
|
||||
receive_raw();
|
||||
void
|
||||
send_raw(const std::vector<uint8_t> &data);
|
||||
};
|
||||
|
||||
class TCPListener : public socket_base
|
||||
{
|
||||
public:
|
||||
TCPListener(int port);
|
||||
TCPListener(const TCPListener &) = delete;
|
||||
TCPListener(TCPListener &&) = default;
|
||||
|
||||
std::pair<TCP, sockaddr_in6>
|
||||
accept();
|
||||
};
|
||||
|
||||
template <typename Socket, typename ReceivedType, typename SentType> class typed_socket : public Socket
|
||||
{
|
||||
public:
|
||||
template <typename... Args> typed_socket(Args &&...args) : Socket(std::forward<Args>(args)...) {}
|
||||
|
||||
std::optional<ReceivedType>
|
||||
receive()
|
||||
{
|
||||
deserialization_packet packet = this->receive_raw();
|
||||
if (packet.empty())
|
||||
return {};
|
||||
|
||||
return packet.deserialize<ReceivedType>();
|
||||
}
|
||||
|
||||
template <typename T = SentType, typename = std::enable_if_t<std::is_same_v<T, SentType>>>
|
||||
void
|
||||
send(const T &data)
|
||||
{
|
||||
serialization_packet p;
|
||||
p.serialize(data);
|
||||
this->send_raw(std::move(p));
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,32 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "xrt_cast.h"
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
template <typename Out, typename In>
|
||||
Out
|
||||
do_cast(const In &in)
|
||||
{
|
||||
Out res;
|
||||
static_assert(sizeof(res) == sizeof(in));
|
||||
memcpy(&res, &in, sizeof(res));
|
||||
return res;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
#define XRT_CAST(in_type, out_type) \
|
||||
out_type xrt_cast(const in_type &in) \
|
||||
{ \
|
||||
return do_cast<out_type>(in); \
|
||||
}
|
||||
|
||||
XRT_CAST(XrPosef, xrt_pose)
|
||||
XRT_CAST(XrVector3f, xrt_vec3)
|
||||
XRT_CAST(XrQuaternionf, xrt_quat)
|
||||
XRT_CAST(XrFovf, xrt_fov)
|
||||
|
||||
XRT_CAST(xrt_pose, XrPosef)
|
||||
XRT_CAST(xrt_fov, XrFovf)
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "xrt/xrt_defines.h"
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
xrt_pose
|
||||
xrt_cast(const XrPosef &);
|
||||
xrt_vec3
|
||||
xrt_cast(const XrVector3f &);
|
||||
xrt_quat
|
||||
xrt_cast(const XrQuaternionf &);
|
||||
xrt_fov
|
||||
xrt_cast(const XrFovf &);
|
||||
|
||||
XrPosef
|
||||
xrt_cast(const xrt_pose &);
|
||||
XrFovf
|
||||
xrt_cast(const xrt_fov &);
|
||||
@@ -0,0 +1,396 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#include "yuv_converter.h"
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern const std::map<std::string, std::vector<uint32_t>> shaders;
|
||||
|
||||
static const VkFormat y_format = VK_FORMAT_R8_UNORM;
|
||||
static const VkFormat uv_format = VK_FORMAT_R8G8_UNORM;
|
||||
|
||||
static int
|
||||
bytes_per_pixel(VkFormat format)
|
||||
{
|
||||
switch (format) {
|
||||
case VK_FORMAT_R8_SRGB:
|
||||
case VK_FORMAT_R8_UNORM: return 1;
|
||||
case VK_FORMAT_R8G8_UNORM: return 2;
|
||||
default: assert(false); return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static VkResult
|
||||
create_image(vk_bundle &vk, VkExtent2D extent, VkFormat format, YuvConverter::image_bundle &bundle)
|
||||
{
|
||||
VkResult res = vk_create_image_simple(&vk, extent, format,
|
||||
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
|
||||
&bundle.image_memory, &bundle.image);
|
||||
vk_check_error("vk_create_image_simple", res, res);
|
||||
|
||||
bundle.stride = extent.width * bytes_per_pixel(format);
|
||||
|
||||
if (!vk_buffer_init(&vk, extent.height * bundle.stride, VK_BUFFER_USAGE_TRANSFER_DST_BIT,
|
||||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
|
||||
&bundle.buffer, &bundle.buffer_memory)) {
|
||||
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
|
||||
}
|
||||
|
||||
res = vk.vkMapMemory(vk.device, bundle.buffer_memory, 0, VK_WHOLE_SIZE, 0, &bundle.mapped_memory);
|
||||
vk_check_error("vkMapMemory", res, res);
|
||||
|
||||
|
||||
VkImageSubresourceRange subresource_range{};
|
||||
subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
subresource_range.baseMipLevel = 0;
|
||||
subresource_range.levelCount = 1;
|
||||
subresource_range.baseArrayLayer = 0;
|
||||
subresource_range.layerCount = 1;
|
||||
|
||||
res = vk_create_view(&vk, bundle.image, VK_IMAGE_VIEW_TYPE_2D, format, subresource_range, &bundle.view);
|
||||
vk_check_error("vk_create_view", res, res);
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static VkResult
|
||||
shader_load(struct vk_bundle *vk, const std::vector<uint32_t> &code, VkShaderModule *out_module)
|
||||
{
|
||||
VkResult ret;
|
||||
|
||||
VkShaderModuleCreateInfo info{};
|
||||
info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
|
||||
info.codeSize = code.size();
|
||||
info.pCode = code.data();
|
||||
|
||||
VkShaderModule module;
|
||||
ret = vk->vkCreateShaderModule(vk->device, //
|
||||
&info, //
|
||||
NULL, //
|
||||
&module); //
|
||||
if (ret != VK_SUCCESS) {
|
||||
VK_ERROR(vk, "vkCreateShaderModule failed: %s", vk_result_string(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
*out_module = module;
|
||||
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
static void
|
||||
destroy_all(YuvConverter *ptr)
|
||||
{
|
||||
auto &vk = ptr->vk;
|
||||
vk.vkDestroyDescriptorPool(vk.device, ptr->descriptor_pool, nullptr);
|
||||
vk.vkDestroyDescriptorSetLayout(vk.device, ptr->descriptor_set_layout, nullptr);
|
||||
for (auto &comp : {ptr->y, ptr->uv}) {
|
||||
vk.vkDestroyPipeline(vk.device, comp.pipeline, nullptr);
|
||||
vk.vkDestroyFramebuffer(vk.device, comp.frame_buffer, nullptr);
|
||||
vk.vkDestroyRenderPass(vk.device, comp.render_pass, nullptr);
|
||||
vk.vkDestroyShaderModule(vk.device, comp.frag, nullptr);
|
||||
|
||||
vk.vkUnmapMemory(vk.device, comp.buffer_memory);
|
||||
vk.vkDestroyBuffer(vk.device, comp.buffer, nullptr);
|
||||
vk.vkFreeMemory(vk.device, comp.buffer_memory, nullptr);
|
||||
vk.vkDestroyImageView(vk.device, comp.view, nullptr);
|
||||
vk.vkDestroyImage(vk.device, comp.image, nullptr);
|
||||
vk.vkFreeMemory(vk.device, comp.image_memory, nullptr);
|
||||
}
|
||||
vk.vkDestroyPipelineLayout(vk.device, ptr->pipeline_layout, nullptr);
|
||||
|
||||
vk.vkDestroyShaderModule(vk.device, ptr->vert, nullptr);
|
||||
}
|
||||
|
||||
#define vk_check_throw(fun, res) \
|
||||
do { \
|
||||
if (vk_has_error(res, fun, __FILE__, __LINE__)) \
|
||||
throw std::runtime_error(fun "failed"); \
|
||||
} while (0)
|
||||
|
||||
YuvConverter::YuvConverter(
|
||||
vk_bundle *vk, VkExtent3D extent, int offset_x, int offset_y, int input_width, int input_height)
|
||||
: vk(*vk)
|
||||
{
|
||||
std::unique_ptr<YuvConverter, decltype(&destroy_all)> deleter(this, destroy_all);
|
||||
|
||||
y.extent = {extent.width, extent.height};
|
||||
uv.extent = {extent.width / 2, extent.height / 2};
|
||||
|
||||
assert(y_format != VK_FORMAT_UNDEFINED);
|
||||
assert(uv_format != VK_FORMAT_UNDEFINED);
|
||||
|
||||
VkResult res = create_image(*vk, y.extent, y_format, y);
|
||||
vk_check_throw("create_image (y)", res);
|
||||
|
||||
res = create_image(*vk, uv.extent, uv_format, uv);
|
||||
vk_check_throw("create_image (uv)", res);
|
||||
|
||||
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
|
||||
samplerLayoutBinding.binding = 0;
|
||||
samplerLayoutBinding.descriptorCount = 1;
|
||||
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
samplerLayoutBinding.pImmutableSamplers = nullptr;
|
||||
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo layoutInfo{};
|
||||
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
|
||||
layoutInfo.bindingCount = 1;
|
||||
layoutInfo.pBindings = &samplerLayoutBinding;
|
||||
|
||||
res = vk->vkCreateDescriptorSetLayout(vk->device, &layoutInfo, nullptr, &descriptor_set_layout);
|
||||
vk_check_throw("vkCreateDescriptorSetLayout", res);
|
||||
|
||||
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
|
||||
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
|
||||
pipelineLayoutInfo.pSetLayouts = &descriptor_set_layout;
|
||||
pipelineLayoutInfo.setLayoutCount = 1;
|
||||
res = vk->vkCreatePipelineLayout(vk->device, &pipelineLayoutInfo, nullptr, &pipeline_layout);
|
||||
vk_check_throw("vkCreatePipelineLayout", res);
|
||||
|
||||
res = shader_load(vk, shaders.at("yuv_converter.vert"), &vert);
|
||||
vk_check_throw("shader_load", res);
|
||||
|
||||
res = shader_load(vk, shaders.at("yuv_converter.y.frag"), &y.frag);
|
||||
vk_check_throw("shader_load", res);
|
||||
res =
|
||||
shader_load(vk, shaders.at("yuv_converter.uv.frag"), &uv.frag);
|
||||
vk_check_throw("shader_load", res);
|
||||
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
VkAttachmentDescription colorAttachment{};
|
||||
VkAttachmentReference colorAttachmentRef{};
|
||||
auto &comp = (i == 0) ? y : uv;
|
||||
double scale = (i == 0) ? 1.0 : 0.5;
|
||||
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
||||
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
||||
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
||||
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
||||
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
||||
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||||
|
||||
colorAttachmentRef.attachment = 0;
|
||||
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
||||
|
||||
colorAttachment.format = (i == 0) ? y_format : uv_format;
|
||||
|
||||
VkSubpassDescription subpass{};
|
||||
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
|
||||
subpass.colorAttachmentCount = 1;
|
||||
subpass.pColorAttachments = &colorAttachmentRef;
|
||||
|
||||
VkRenderPassCreateInfo renderPassInfo{};
|
||||
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
|
||||
renderPassInfo.attachmentCount = 1;
|
||||
renderPassInfo.pAttachments = &colorAttachment;
|
||||
renderPassInfo.subpassCount = 1;
|
||||
renderPassInfo.pSubpasses = &subpass;
|
||||
|
||||
res = vk->vkCreateRenderPass(vk->device, &renderPassInfo, nullptr, &comp.render_pass);
|
||||
vk_check_throw("vkCreateRenderPass", res);
|
||||
|
||||
VkFramebufferCreateInfo framebufferInfo{};
|
||||
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
||||
framebufferInfo.renderPass = comp.render_pass;
|
||||
framebufferInfo.attachmentCount = 1;
|
||||
framebufferInfo.pAttachments = &comp.view;
|
||||
framebufferInfo.width = comp.extent.width;
|
||||
framebufferInfo.height = comp.extent.height;
|
||||
framebufferInfo.layers = 1;
|
||||
|
||||
res = vk->vkCreateFramebuffer(vk->device, &framebufferInfo, nullptr, &comp.frame_buffer);
|
||||
vk_check_throw("vkCreateFramebuffer", res);
|
||||
|
||||
VkPipelineShaderStageCreateInfo shaderStages[2] = {};
|
||||
|
||||
shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
|
||||
shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
|
||||
shaderStages[0].module = vert;
|
||||
shaderStages[0].pName = "main";
|
||||
|
||||
shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
|
||||
shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||||
shaderStages[1].module = comp.frag;
|
||||
shaderStages[1].pName = "main";
|
||||
|
||||
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
|
||||
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
|
||||
vertexInputInfo.vertexBindingDescriptionCount = 0;
|
||||
vertexInputInfo.vertexAttributeDescriptionCount = 0;
|
||||
|
||||
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
|
||||
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||||
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||||
inputAssembly.primitiveRestartEnable = VK_FALSE;
|
||||
|
||||
VkViewport viewport{};
|
||||
viewport.x = -offset_x * scale;
|
||||
viewport.y = -offset_y * scale;
|
||||
viewport.width = input_width * scale;
|
||||
viewport.height = input_height * scale;
|
||||
viewport.minDepth = 0.0f;
|
||||
viewport.maxDepth = 1.0f;
|
||||
|
||||
VkRect2D scissor{};
|
||||
scissor.offset = {0, 0};
|
||||
scissor.extent = comp.extent;
|
||||
|
||||
VkPipelineViewportStateCreateInfo viewportState{};
|
||||
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
|
||||
viewportState.viewportCount = 1;
|
||||
viewportState.pViewports = &viewport;
|
||||
viewportState.scissorCount = 1;
|
||||
viewportState.pScissors = &scissor;
|
||||
|
||||
VkPipelineRasterizationStateCreateInfo rasterizer{};
|
||||
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
|
||||
rasterizer.depthClampEnable = VK_FALSE;
|
||||
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
|
||||
rasterizer.lineWidth = 1.0f;
|
||||
|
||||
VkPipelineMultisampleStateCreateInfo multisampling{};
|
||||
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
|
||||
multisampling.sampleShadingEnable = VK_FALSE;
|
||||
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
|
||||
|
||||
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
|
||||
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT;
|
||||
colorBlendAttachment.blendEnable = VK_FALSE;
|
||||
|
||||
VkPipelineColorBlendStateCreateInfo colorBlending{};
|
||||
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
|
||||
colorBlending.logicOpEnable = VK_FALSE;
|
||||
colorBlending.attachmentCount = 1;
|
||||
colorBlending.pAttachments = &colorBlendAttachment;
|
||||
|
||||
VkGraphicsPipelineCreateInfo pipelineInfo{};
|
||||
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
|
||||
pipelineInfo.stageCount = std::size(shaderStages);
|
||||
pipelineInfo.pStages = shaderStages;
|
||||
pipelineInfo.pVertexInputState = &vertexInputInfo;
|
||||
pipelineInfo.pInputAssemblyState = &inputAssembly;
|
||||
pipelineInfo.pViewportState = &viewportState;
|
||||
pipelineInfo.pRasterizationState = &rasterizer;
|
||||
pipelineInfo.pMultisampleState = &multisampling;
|
||||
pipelineInfo.pColorBlendState = &colorBlending;
|
||||
pipelineInfo.layout = pipeline_layout;
|
||||
pipelineInfo.renderPass = comp.render_pass;
|
||||
pipelineInfo.subpass = 0;
|
||||
|
||||
res = vk->vkCreateGraphicsPipelines(vk->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||||
&comp.pipeline);
|
||||
vk_check_throw("vkCreateGraphicsPipelines", res);
|
||||
}
|
||||
|
||||
VkSamplerCreateInfo samplerInfo{};
|
||||
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
|
||||
samplerInfo.magFilter = VK_FILTER_LINEAR;
|
||||
samplerInfo.minFilter = VK_FILTER_LINEAR;
|
||||
samplerInfo.anisotropyEnable = VK_FALSE;
|
||||
res = vk->vkCreateSampler(vk->device, &samplerInfo, nullptr, &sampler);
|
||||
vk_check_throw("vkCreateSampler", res);
|
||||
|
||||
(void)deleter.release();
|
||||
}
|
||||
|
||||
YuvConverter::~YuvConverter()
|
||||
{
|
||||
destroy_all(this);
|
||||
}
|
||||
|
||||
void
|
||||
YuvConverter::SetImages(int num_images, VkImage *images, VkImageView *views)
|
||||
{
|
||||
// os_mutex_lock(&vk.cmd_pool_mutex);
|
||||
assert(command_buffers.empty());
|
||||
assert(descriptor_sets.empty());
|
||||
descriptor_sets.resize(num_images);
|
||||
VkDescriptorPoolSize poolSize{};
|
||||
poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
poolSize.descriptorCount = num_images;
|
||||
|
||||
VkDescriptorPoolCreateInfo poolInfo{};
|
||||
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
||||
poolInfo.poolSizeCount = 1;
|
||||
poolInfo.pPoolSizes = &poolSize;
|
||||
poolInfo.maxSets = num_images;
|
||||
VkResult res = vk.vkCreateDescriptorPool(vk.device, &poolInfo, nullptr, &descriptor_pool);
|
||||
vk_check_throw("vkCreateDescriptorPool", res);
|
||||
for (int i = 0; i < num_images; ++i) {
|
||||
const auto &view = views[i];
|
||||
auto &descriptor_set = descriptor_sets[i];
|
||||
|
||||
VkDescriptorSetAllocateInfo allocInfo{};
|
||||
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
|
||||
allocInfo.descriptorPool = descriptor_pool;
|
||||
allocInfo.descriptorSetCount = 1;
|
||||
allocInfo.pSetLayouts = &descriptor_set_layout;
|
||||
res = vk.vkAllocateDescriptorSets(vk.device, &allocInfo, &descriptor_set);
|
||||
vk_check_throw("vkAllocateDescriptorSets", res);
|
||||
|
||||
VkDescriptorImageInfo imageInfo{};
|
||||
imageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
|
||||
imageInfo.imageView = view;
|
||||
imageInfo.sampler = sampler;
|
||||
|
||||
VkWriteDescriptorSet descriptorWrite{};
|
||||
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||||
descriptorWrite.dstSet = descriptor_set;
|
||||
descriptorWrite.dstBinding = 0;
|
||||
descriptorWrite.dstArrayElement = 0;
|
||||
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
descriptorWrite.descriptorCount = 1;
|
||||
descriptorWrite.pImageInfo = &imageInfo;
|
||||
|
||||
vk.vkUpdateDescriptorSets(vk.device, 1, &descriptorWrite, 0, nullptr);
|
||||
|
||||
VkCommandBuffer cmdBuffer;
|
||||
res = vk_cmd_buffer_create_and_begin(&vk, &cmdBuffer);
|
||||
vk_check_throw("vk_cmd_buffer_create_and_begin", res);
|
||||
|
||||
for (auto &comp : {y, uv}) {
|
||||
VkRenderPassBeginInfo render_pass_info{};
|
||||
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
||||
render_pass_info.renderPass = comp.render_pass;
|
||||
render_pass_info.framebuffer = comp.frame_buffer;
|
||||
render_pass_info.renderArea.extent = comp.extent;
|
||||
|
||||
vk.vkCmdBeginRenderPass(cmdBuffer, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vk.vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, comp.pipeline);
|
||||
vk.vkCmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1,
|
||||
&descriptor_set, 0, nullptr);
|
||||
vk.vkCmdDraw(cmdBuffer, 3, 1, 0, 0);
|
||||
vk.vkCmdEndRenderPass(cmdBuffer);
|
||||
|
||||
if (comp.buffer != VK_NULL_HANDLE) {
|
||||
VkBufferImageCopy copy{};
|
||||
copy.bufferOffset = 0;
|
||||
copy.bufferRowLength = 0;
|
||||
copy.bufferImageHeight = 0;
|
||||
copy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
copy.imageSubresource.mipLevel = 0;
|
||||
copy.imageSubresource.baseArrayLayer = 0;
|
||||
copy.imageSubresource.layerCount = 1;
|
||||
copy.imageOffset = {0, 0, 0};
|
||||
copy.imageExtent = {comp.extent.width, comp.extent.height, 1};
|
||||
// TODO synchronisation?
|
||||
vk.vkCmdCopyImageToBuffer(cmdBuffer, comp.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
comp.buffer, 1, ©);
|
||||
}
|
||||
}
|
||||
|
||||
res = vk.vkEndCommandBuffer(cmdBuffer);
|
||||
vk_check_throw("vkEndCommandBuffer", res);
|
||||
|
||||
command_buffers.push_back(cmdBuffer);
|
||||
}
|
||||
// os_mutex_unlock(&vk.cmd_pool_mutex);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright 2022, Guillaume Meunier
|
||||
// Copyright 2022, Patrick Nicolas
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "vk/vk_helpers.h"
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
class YuvConverter
|
||||
{
|
||||
public:
|
||||
struct image_bundle
|
||||
{
|
||||
VkDeviceMemory image_memory = VK_NULL_HANDLE;
|
||||
VkImage image = VK_NULL_HANDLE;
|
||||
VkImageView view = VK_NULL_HANDLE;
|
||||
VkDeviceMemory buffer_memory = VK_NULL_HANDLE;
|
||||
VkBuffer buffer = VK_NULL_HANDLE;
|
||||
void *mapped_memory = nullptr;
|
||||
VkRenderPass render_pass = VK_NULL_HANDLE;
|
||||
VkFramebuffer frame_buffer = VK_NULL_HANDLE;
|
||||
VkShaderModule frag = VK_NULL_HANDLE;
|
||||
VkPipeline pipeline = VK_NULL_HANDLE;
|
||||
VkExtent2D extent;
|
||||
int stride;
|
||||
};
|
||||
vk_bundle &vk;
|
||||
image_bundle y;
|
||||
image_bundle uv;
|
||||
VkSampler sampler = VK_NULL_HANDLE;
|
||||
VkDescriptorSetLayout descriptor_set_layout = VK_NULL_HANDLE;
|
||||
VkDescriptorPool descriptor_pool = VK_NULL_HANDLE;
|
||||
|
||||
VkShaderModule vert = VK_NULL_HANDLE;
|
||||
|
||||
VkPipelineLayout pipeline_layout = VK_NULL_HANDLE;
|
||||
|
||||
std::vector<VkCommandBuffer> command_buffers;
|
||||
std::vector<VkDescriptorSet> descriptor_sets;
|
||||
|
||||
YuvConverter(vk_bundle *vk, VkExtent3D extent, int offset_x, int offset_y, int input_width, int input_height);
|
||||
~YuvConverter();
|
||||
|
||||
void
|
||||
SetImages(int num_images, VkImage *images, VkImageView *views);
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
#include "hostname.h"
|
||||
|
||||
#include <systemd/sd-bus.h>
|
||||
|
||||
std::string
|
||||
hostname()
|
||||
{
|
||||
sd_bus * bus;
|
||||
if (sd_bus_default_system(&bus) < 0)
|
||||
return "";
|
||||
|
||||
for(auto property: {"PrettyHostname", "StaticHostname", "Hostname"})
|
||||
{
|
||||
char * hostname = nullptr;
|
||||
sd_bus_error error = SD_BUS_ERROR_NULL;
|
||||
|
||||
if (sd_bus_get_property_string(bus, "org.freedesktop.hostname1", "/org/freedesktop/hostname1", "org.freedesktop.hostname1", property, &error, &hostname) < 0)
|
||||
{
|
||||
sd_bus_error_free(&error);
|
||||
continue;
|
||||
}
|
||||
|
||||
sd_bus_error_free(&error);
|
||||
if (hostname && strcmp(hostname, ""))
|
||||
{
|
||||
std::string s = hostname;
|
||||
free(hostname);
|
||||
sd_bus_unref(bus);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
sd_bus_unref(bus);
|
||||
|
||||
return "Unknown";
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
std::string hostname();
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
// Copyright 2022, Collabora, Ltd.
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
/*!
|
||||
* @file
|
||||
* @brief Main file for WiVRn Monado service.
|
||||
* @author
|
||||
* @author
|
||||
* @ingroup ipc
|
||||
*/
|
||||
|
||||
#include "util/u_trace_marker.h"
|
||||
|
||||
#include "driver/wivrn_sockets.h"
|
||||
#include "driver/wivrn_packets.h"
|
||||
#include <memory>
|
||||
#include <unistd.h>
|
||||
#include <sys/wait.h>
|
||||
#include <iostream>
|
||||
|
||||
#include "avahi_publisher.h"
|
||||
#include "hostname.h"
|
||||
|
||||
// Insert the on load constructor to init trace marker.
|
||||
U_TRACE_TARGET_SETUP(U_TRACE_WHICH_SERVICE)
|
||||
|
||||
extern "C" {
|
||||
int
|
||||
ipc_server_main(int argc, char *argv[]);
|
||||
|
||||
int
|
||||
oxr_sdl2_hack_create(void **out_hack)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
oxr_sdl2_hack_start(void *hack, struct xrt_instance *xinst, struct xrt_system_devices *xsysd)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
oxr_sdl2_hack_stop(void **hack_ptr)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
using namespace xrt::drivers::wivrn;
|
||||
|
||||
std::unique_ptr<TCP> tcp;
|
||||
|
||||
void
|
||||
avahi_callback(AvahiWatch *w, int fd, AvahiWatchEvent event, void *userdata)
|
||||
{
|
||||
bool *client_connected = (bool*)userdata;
|
||||
*client_connected = true;
|
||||
}
|
||||
|
||||
int
|
||||
main(int argc, char *argv[])
|
||||
{
|
||||
u_trace_marker_init();
|
||||
|
||||
while (true) {
|
||||
{
|
||||
avahi_publisher publisher(hostname().c_str(), "_wivrn._tcp", control_port);
|
||||
|
||||
TCPListener listener(control_port);
|
||||
bool client_connected = false;
|
||||
|
||||
AvahiWatch *watch = publisher.watch_new(listener.get_fd(), AVAHI_WATCH_IN, &avahi_callback, &client_connected);
|
||||
|
||||
while (publisher.iterate() && !client_connected)
|
||||
;
|
||||
|
||||
publisher.watch_free(watch);
|
||||
|
||||
tcp = std::make_unique<TCP>(listener.accept().first);
|
||||
}
|
||||
|
||||
pid_t child = fork();
|
||||
|
||||
if (child < 0) {
|
||||
perror("fork");
|
||||
return 1;
|
||||
}
|
||||
if (child == 0) {
|
||||
return ipc_server_main(argc, argv);
|
||||
} else {
|
||||
std::cerr << "Server started, PID " << child << std::endl;
|
||||
|
||||
int wstatus = 0;
|
||||
waitpid(child, &wstatus, 0);
|
||||
|
||||
std::cerr << "Server exited, exit status " << WEXITSTATUS(wstatus) << std::endl;
|
||||
if (WIFSIGNALED(wstatus))
|
||||
std::cerr << "Received signal " << sigabbrev_np(WTERMSIG(wstatus)) << " ("
|
||||
<< strsignal(WTERMSIG(wstatus)) << ")"
|
||||
<< (WCOREDUMP(wstatus) ? ", core dumped" : "") << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// Copyright 2020-2022, Collabora, Ltd.
|
||||
// SPDX-License-Identifier: BSL-1.0
|
||||
/*!
|
||||
* @file
|
||||
* @brief Shared default implementation of the instance with compositor.
|
||||
* @author Jakob Bornecrantz <jakob@collabora.com>
|
||||
*/
|
||||
|
||||
#include "xrt/xrt_gfx_native.h"
|
||||
#include "xrt/xrt_system.h"
|
||||
#include "xrt/xrt_config_build.h"
|
||||
|
||||
#include "os/os_time.h"
|
||||
|
||||
#include "util/u_debug.h"
|
||||
#include "util/u_trace_marker.h"
|
||||
#include "util/u_system_helpers.h"
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
#include "driver/wivrn_session.h"
|
||||
|
||||
/*
|
||||
*
|
||||
* Internal functions.
|
||||
*
|
||||
*/
|
||||
|
||||
extern std::unique_ptr<TCP> tcp;
|
||||
|
||||
static xrt_result_t
|
||||
wivrn_instance_create_system(struct xrt_instance *xinst,
|
||||
struct xrt_system_devices **out_xsysd,
|
||||
struct xrt_system_compositor **out_xsysc)
|
||||
{
|
||||
assert(out_xsysd != NULL);
|
||||
assert(*out_xsysd == NULL);
|
||||
assert(out_xsysc == NULL || *out_xsysc == NULL);
|
||||
|
||||
struct xrt_system_compositor *xsysc = NULL;
|
||||
struct xrt_system_devices *xsysd = xrt::drivers::wivrn::wivrn_session::create_session(std::move(*tcp));
|
||||
tcp.reset();
|
||||
|
||||
if (!xsysd)
|
||||
return XRT_ERROR_DEVICE_CREATION_FAILED;
|
||||
|
||||
xrt_result_t xret = XRT_SUCCESS;
|
||||
|
||||
|
||||
struct xrt_device *head = xsysd->roles.head;
|
||||
|
||||
if (xret == XRT_SUCCESS && xsysc == NULL) {
|
||||
xret = xrt_gfx_provider_create_system(head, &xsysc);
|
||||
}
|
||||
|
||||
if (xret != XRT_SUCCESS) {
|
||||
xrt_system_devices_destroy(&xsysd);
|
||||
return xret;
|
||||
}
|
||||
|
||||
*out_xsysd = xsysd;
|
||||
*out_xsysc = xsysc;
|
||||
|
||||
return xret;
|
||||
}
|
||||
|
||||
static void
|
||||
wivrn_instance_destroy(struct xrt_instance *xinst)
|
||||
{
|
||||
delete xinst;
|
||||
}
|
||||
|
||||
static xrt_result_t
|
||||
wivrn_instance_get_prober(struct xrt_instance *xinst, struct xrt_prober **out_xp)
|
||||
{
|
||||
*out_xp = nullptr;
|
||||
return XRT_ERROR_PROBER_NOT_SUPPORTED;
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
* Exported function(s).
|
||||
*
|
||||
*/
|
||||
|
||||
xrt_result_t
|
||||
xrt_instance_create(struct xrt_instance_info *ii, struct xrt_instance **out_xinst)
|
||||
{
|
||||
u_trace_marker_init();
|
||||
|
||||
struct xrt_instance *xinst = U_TYPED_CALLOC(struct xrt_instance);
|
||||
xinst->create_system = wivrn_instance_create_system;
|
||||
xinst->get_prober = wivrn_instance_get_prober;
|
||||
xinst->destroy = wivrn_instance_destroy;
|
||||
|
||||
xinst->startup_timestamp = os_monotonic_get_ns();
|
||||
|
||||
*out_xinst = xinst;
|
||||
|
||||
return XRT_SUCCESS;
|
||||
}
|
||||
Reference in New Issue
Block a user