From 4baf2b17ebe1f2c4716ff3ed5046831e95f0a054 Mon Sep 17 00:00:00 2001 From: Guillaume Meunier Date: Sun, 13 Nov 2022 11:00:04 +0100 Subject: [PATCH] move stuff in common, clang-format, update copyright --- client/src/.clang-format => .clang-format | 0 CMakeLists.txt | 15 + build.gradle | 2 +- client/CMakeLists.txt | 28 +- client/src/render/scene_renderer.cpp | 401 +++++++------- client/src/render/scene_renderer.h | 103 ++-- client/src/scenes/lobby.cpp | 1 - client/src/scenes/stream.cpp | 10 +- client/src/utils/backtrace.cpp | 30 +- common/CMakeLists.txt | 21 +- common/wivrn_config.h.in | 24 + {client/src => common}/wivrn_packets.h | 0 {client/src => common}/wivrn_serialization.h | 0 {client/src => common}/wivrn_sockets.cpp | 0 {client/src => common}/wivrn_sockets.h | 0 server/CMakeLists.txt | 12 +- server/avahi_publisher.cpp | 122 ++-- server/avahi_publisher.h | 49 +- server/driver/encoder_settings.cpp | 99 ++-- server/driver/encoder_settings.h | 32 +- server/driver/external/rs.c | 269 +++++---- server/driver/external/rs.h | 75 +-- server/driver/ffmpeg/VideoEncoderFFMPEG.cpp | 81 ++- server/driver/ffmpeg/VideoEncoderFFMPEG.h | 29 +- server/driver/ffmpeg/VideoEncoderVA.cpp | 158 ++++-- server/driver/ffmpeg/VideoEncoderVA.h | 40 +- server/driver/ffmpeg/ffmpeg_helper.cpp | 65 ++- server/driver/ffmpeg/ffmpeg_helper.h | 26 +- server/driver/pose_list.cpp | 43 +- server/driver/pose_list.h | 73 ++- .../driver/shaders/yuv_converter.uv.frag.glsl | 21 +- server/driver/shaders/yuv_converter.vert.glsl | 21 +- .../driver/shaders/yuv_converter.y.frag.glsl | 21 +- server/driver/video_encoder.cpp | 123 +++-- server/driver/video_encoder.h | 84 +-- server/driver/video_encoder_nvenc.cpp | 147 ++--- server/driver/video_encoder_nvenc.h | 51 +- server/driver/video_encoder_x264.cpp | 111 ++-- server/driver/video_encoder_x264.h | 63 ++- server/driver/view_list.cpp | 36 +- server/driver/view_list.h | 30 +- server/driver/wivrn_comp_target.cpp | 354 ++++++------ server/driver/wivrn_comp_target.h | 24 +- server/driver/wivrn_connection.cpp | 42 +- server/driver/wivrn_connection.h | 47 +- server/driver/wivrn_controller.cpp | 200 ++++--- server/driver/wivrn_controller.h | 43 +- server/driver/wivrn_hmd.cpp | 164 +++--- server/driver/wivrn_hmd.h | 53 +- server/driver/wivrn_packets.h | 237 -------- server/driver/wivrn_serialization.h | 522 ------------------ server/driver/wivrn_session.cpp | 93 ++-- server/driver/wivrn_session.h | 53 +- server/driver/wivrn_sockets.cpp | 315 ----------- server/driver/wivrn_sockets.h | 148 ----- server/driver/xrt_cast.cpp | 35 +- server/driver/xrt_cast.h | 39 +- server/driver/yuv_converter.cpp | 116 ++-- server/driver/yuv_converter.h | 30 +- server/hostname.cpp | 5 +- server/main.cpp | 70 +-- server/target_instance_wivrn.cpp | 31 +- 62 files changed, 2291 insertions(+), 2846 deletions(-) rename client/src/.clang-format => .clang-format (100%) create mode 100644 common/wivrn_config.h.in rename {client/src => common}/wivrn_packets.h (100%) rename {client/src => common}/wivrn_serialization.h (100%) rename {client/src => common}/wivrn_sockets.cpp (100%) rename {client/src => common}/wivrn_sockets.h (100%) delete mode 100644 server/driver/wivrn_packets.h delete mode 100644 server/driver/wivrn_serialization.h delete mode 100644 server/driver/wivrn_sockets.cpp delete mode 100644 server/driver/wivrn_sockets.h diff --git a/client/src/.clang-format b/.clang-format similarity index 100% rename from client/src/.clang-format rename to .clang-format diff --git a/CMakeLists.txt b/CMakeLists.txt index 1449bb85..b1d6bffe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,6 +23,18 @@ if (WIVRN_BUILD_SERVER) pkg_check_modules(LIBAV IMPORTED_TARGET libavcodec libavutil libswscale libavfilter) pkg_check_modules(X264 IMPORTED_TARGET x264) + if(CUDAToolkit_FOUND) + set(WIVRN_HAVE_CUDA ON) + endif() + + if(LIBAV_FOUND) + set(WIVRN_HAVE_FFMPEG ON) + endif() + + if(X264_FOUND) + set(WIVRN_HAVE_X264 ON) + endif() + if (NOT CUDAToolkit_FOUND AND NOT LIBAV_FOUND AND NOT X264_FOUND) message(FATAL_ERROR "No encoder found") endif() @@ -38,6 +50,9 @@ if(ANDROID) android_ndk_import_module_native_app_glue() endif() +FetchContent_Declare(boostpfr URL https://github.com/boostorg/pfr/archive/refs/tags/2.0.3.tar.gz) +FetchContent_MakeAvailable(boostpfr) + add_subdirectory(common) if (WIVRN_BUILD_CLIENT) diff --git a/build.gradle b/build.gradle index 383afa85..0ffead0a 100644 --- a/build.gradle +++ b/build.gradle @@ -64,7 +64,7 @@ android { externalNativeBuild { cmake { abiFilters 'arm64-v8a' - arguments '-DOCULUS_SDK=' + file('OculusSDK').absolutePath + arguments '-DOCULUS=ON' } } } diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 28fba3bb..5971cdd6 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -24,16 +24,15 @@ if(ANDROID) target_link_libraries(wivrn ${ANDROID_LIBRARY} ${MEDIA_LIBRARY}) if(OCULUS) - if(NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/OculusSDK) + set(OCULUS_SDK_PATH ${CMAKE_CURRENT_BINARY_DIR}/OculusSDK) + if(NOT EXISTS ${OCULUS_SDK_PATH}) file(GLOB OCULUS_SDK_ZIP ${CMAKE_SOURCE_DIR}/ovr_sdk_mobile_*.zip) if("${OCULUS_SDK_ZIP}" STREQUAL "") message(FATAL_ERROR "Download the Oculus SDK from https://developer.oculus.com/downloads/package/oculus-mobile-sdk/ in ${CMAKE_SOURCE_DIR}/ovr_sdk_mobile_*.zip") endif() - set(OCULUS_SDK_PATH ${CMAKE_CURRENT_BINARY_DIR}/OculusSDK) - file(ARCHIVE_EXTRACT INPUT ${OCULUS_SDK_ZIP} DESTINATION ${OCULUS_SDK_PATH}) endif() @@ -52,7 +51,7 @@ if(ANDROID) message(FATAL_ERROR "TODO: implement non-oculus android headsets") endif() - target_link_libraries(wivrn native_app_glue OpenXR Boost::pfr) + target_link_libraries(wivrn native_app_glue OpenXR) target_compile_definitions(wivrn PRIVATE -DXR_USE_PLATFORM_ANDROID -DVK_USE_PLATFORM_ANDROID_KHR) target_link_options(wivrn PRIVATE -Wl,--undefined=ANativeActivity_onCreate) @@ -115,19 +114,24 @@ endif() if(USE_ANDROID_VALIDATION_LAYER) set(VVL_VERSION "1.3.231.1") - set(VVL_ZIPFILE ${CMAKE_CURRENT_SOURCE_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip) - if(NOT EXISTS ${VVL_ZIPFILE}) - file(DOWNLOAD https://github.com/KhronosGroup/Vulkan-ValidationLayers/releases/download/sdk-${VVL_VERSION}/android-binaries-${VVL_VERSION}.zip - ${VVL_ZIPFILE}) + if(NOT EXISTS ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip) + if (EXISTS ${CMAKE_SOURCE_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip) + file(CREATE_LINK ${CMAKE_SOURCE_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip SYMBOLIC) + else() + file(DOWNLOAD https://github.com/KhronosGroup/Vulkan-ValidationLayers/releases/download/sdk-${VVL_VERSION}/android-binaries-${VVL_VERSION}.zip ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip + EXPECTED_HASH SHA256=eec3a54222d6d33d4f787a13a45c60ac5b9e8d7bf795fc41e4242354a02e34ba) + endif() endif() - file(ARCHIVE_EXTRACT INPUT ${VVL_ZIPFILE} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/Vulkan-ValidationLayer) + set(VVL_ZIPFILE ${CMAKE_CURRENT_SOURCE_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip) + + file(ARCHIVE_EXTRACT INPUT ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip DESTINATION ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayer) add_library(vvl1 SHARED IMPORTED) - set_property(TARGET vvl1 PROPERTY IMPORTED_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/Vulkan-ValidationLayer/${CMAKE_ANDROID_ARCH_ABI}/libVkLayer_khronos_validation.so) + set_property(TARGET vvl1 PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayer/${CMAKE_ANDROID_ARCH_ABI}/libVkLayer_khronos_validation.so) add_library(vvl2 SHARED IMPORTED) - set_property(TARGET vvl2 PROPERTY IMPORTED_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/Vulkan-ValidationLayer/${CMAKE_ANDROID_ARCH_ABI}/libc++_shared.so) + set_property(TARGET vvl2 PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayer/${CMAKE_ANDROID_ARCH_ABI}/libc++_shared.so) - target_link_libraries(wivrn PRIVATE vvl1 vvl2) # Hack to get gradle to package the validation layer in the APK + target_link_libraries(wivrn vvl1 vvl2) # Hack to get gradle to package the validation layer in the APK endif() diff --git a/client/src/render/scene_renderer.cpp b/client/src/render/scene_renderer.cpp index 7f965730..401a80a0 100644 --- a/client/src/render/scene_renderer.cpp +++ b/client/src/render/scene_renderer.cpp @@ -1,21 +1,3 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ #include "scene_renderer.h" #include "application.h" #include "spdlog/spdlog.h" @@ -34,6 +16,7 @@ VkFormat gltf_to_vkformat(int component, int bits, int pixel_type, bool srgb) case TINYGLTF_COMPONENT_TYPE_SHORT: case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: + assert(bits == 32); break; @@ -326,7 +309,8 @@ void scene_renderer::reserve(size_t size) buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; staging_buffer = vk::buffer(device, buffer_info); - staging_memory = vk::device_memory(device, physical_device, staging_buffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + staging_memory = + vk::device_memory(device, physical_device, staging_buffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); staging_buffer_size = size; staging_memory.map_memory(); } @@ -346,10 +330,7 @@ void scene_renderer::load_buffer(VkBuffer b, const void * data, size_t size) begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; CHECK_VK(vkBeginCommandBuffer(staging_command_buffer, &begin_info)); - VkBufferCopy copy_info{ - .srcOffset = 0, - .dstOffset = 0, - .size = size}; + VkBufferCopy copy_info{.srcOffset = 0, .dstOffset = 0, .size = size}; vkCmdCopyBuffer(staging_command_buffer, staging_buffer, b, 1, ©_info); CHECK_VK(vkEndCommandBuffer(staging_command_buffer)); @@ -394,28 +375,29 @@ void scene_renderer::load_image(VkImage i, void * data, VkExtent2D size, VkForma .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = i, - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = 0, - .levelCount = mipmap_count, - .baseArrayLayer = 0, - .layerCount = 1, - }, + .subresourceRange = + { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = mipmap_count, + .baseArrayLayer = 0, + .layerCount = 1, + }, }; vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); - VkBufferImageCopy copy_info{ - .bufferOffset = 0, - .bufferRowLength = 0, - .bufferImageHeight = 0, - .imageSubresource = VkImageSubresourceLayers{ - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .mipLevel = 0, - .baseArrayLayer = 0, - .layerCount = 1, - }, - .imageOffset = {0, 0, 0}, - .imageExtent = {size.width, size.height, 1}}; + VkBufferImageCopy copy_info{.bufferOffset = 0, + .bufferRowLength = 0, + .bufferImageHeight = 0, + .imageSubresource = + VkImageSubresourceLayers{ + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .mipLevel = 0, + .baseArrayLayer = 0, + .layerCount = 1, + }, + .imageOffset = {0, 0, 0}, + .imageExtent = {size.width, size.height, 1}}; vkCmdCopyBufferToImage(staging_command_buffer, staging_buffer, i, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_info); VkOffset3D size_src = {(int32_t)size.width, (int32_t)size.height, 1}; @@ -431,19 +413,21 @@ void scene_renderer::load_image(VkImage i, void * data, VkExtent2D size, VkForma VkOffset3D size_dst = {std::max(1, size_src.x / 2), std::max(1, size_src.y / 2), 1}; VkImageBlit blit_info{ - .srcSubresource = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .mipLevel = mipmap - 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, + .srcSubresource = + { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .mipLevel = mipmap - 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, .srcOffsets = {{0, 0, 0}, size_src}, - .dstSubresource = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .mipLevel = mipmap, - .baseArrayLayer = 0, - .layerCount = 1, - }, + .dstSubresource = + { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .mipLevel = mipmap, + .baseArrayLayer = 0, + .layerCount = 1, + }, .dstOffsets = {{0, 0, 0}, size_dst}, }; vkCmdBlitImage(staging_command_buffer, i, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, i, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit_info, VK_FILTER_LINEAR); @@ -487,16 +471,8 @@ void scene_renderer::load_image(VkImage i, void * data, VkExtent2D size, VkForma void scene_renderer::cleanup() { - for (auto & i: shaders) - cleanup_shader(*i); shaders.clear(); - - for (auto & i: images) - cleanup_image(*i); images.clear(); - - for (auto & i: buffers) - cleanup_buffer(*i); buffers.clear(); cleanup_output_images(); @@ -578,175 +554,204 @@ void scene_renderer::set_output_images(std::vector output_images_, VkEx } } -void scene_renderer::cleanup_shader(shader & s) +void scene_renderer::cleanup_shader(shader * s) { - for (auto & i: s.descriptor_pools) + for (auto & i: s->descriptor_set_layouts) + vkDestroyDescriptorSetLayout(device, i, nullptr); + for (auto & i: s->descriptor_pools) vkDestroyDescriptorPool(device, i, nullptr); + for (auto & i: s->pipelines) + vkDestroyPipeline(device, i.second, nullptr); - if (s.pipeline) - vkDestroyPipeline(device, s.pipeline, nullptr); - if (s.pipeline_layout) - vkDestroyPipelineLayout(device, s.pipeline_layout, nullptr); - if (s.descriptor_set_layout) - vkDestroyDescriptorSetLayout(device, s.descriptor_set_layout, nullptr); - - s.descriptor_pools.clear(); - s.pipeline = VK_NULL_HANDLE; - s.pipeline_layout = VK_NULL_HANDLE; - s.descriptor_set_layout = VK_NULL_HANDLE; + if (s->pipeline_layout) + vkDestroyPipelineLayout(device, s->pipeline_layout, nullptr); + if (s->fragment_shader) + vkDestroyShaderModule(device, s->fragment_shader, nullptr); + if (s->vertex_shader) + vkDestroyShaderModule(device, s->vertex_shader, nullptr); } -scene_renderer::shader * scene_renderer::create_shader(std::string name, VkPrimitiveTopology topology, std::vector uniform_bindings, std::vector vertex_bindings, std::vector vertex_attributes) +std::weak_ptr +scene_renderer::create_shader(std::string name, std::vector> uniform_bindings) { - auto s = std::make_unique(); + auto s = std::shared_ptr(new shader, [&](shader * s) { cleanup_shader(s); }); - try + // Create graphics pipeline + s->vertex_shader = vk::shader(device, name + ".vert").release(); + s->fragment_shader = vk::shader(device, name + ".frag").release(); + + s->descriptor_set_layouts.reserve(uniform_bindings.size()); + for (std::vector & bindings: uniform_bindings) { - // Create graphics pipeline - s->vertex_shader = vk::shader(device, name + ".vert").release(); - s->fragment_shader = vk::shader(device, name + ".frag").release(); - VkDescriptorSetLayoutCreateInfo layout_info{ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = (uint32_t)uniform_bindings.size(), - .pBindings = uniform_bindings.data(), + .pBindings = bindings.data(), }; - CHECK_VK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &s->descriptor_set_layout)); - - VkPipelineLayoutCreateInfo pipeline_layout_create_info{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, - .setLayoutCount = 1, - .pSetLayouts = &s->descriptor_set_layout, - }; - - CHECK_VK(vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &s->pipeline_layout)); - - VkPipelineColorBlendAttachmentState pcbas{.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | - VK_COLOR_COMPONENT_G_BIT | - VK_COLOR_COMPONENT_B_BIT}; - - vk::pipeline::graphics_info pipeline_info{ - .shader_stages = - {{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = s->vertex_shader, .pName = "main"}, - {.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = s->fragment_shader, .pName = "main"}}, - .vertex_input_bindings = vertex_bindings, - .vertex_input_attributes = vertex_attributes, - .InputAssemblyState = {.topology = topology}, - .viewports = {VkViewport{.x = 0, - .y = 0, - .width = (float)output_size.width, - .height = (float)output_size.height, - .minDepth = 0, - .maxDepth = 1}}, - .scissors = {VkRect2D{ - .offset = {0, 0}, - .extent = output_size, - }}, - .RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1}, - .MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}, - .ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas}, - .dynamic_states = {}, - .renderPass = renderpass, - .subpass = 0, - }; - - s->pipeline = vk::pipeline(device, pipeline_info, s->pipeline_layout).release(); - } - catch (...) - { - cleanup_shader(*s); - throw; + VkDescriptorSetLayout descriptor_set_layout; + CHECK_VK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &descriptor_set_layout)); + s->descriptor_set_layouts.push_back(descriptor_set_layout); } - return shaders.emplace_back(std::move(s)).get(); + VkPipelineLayoutCreateInfo pipeline_layout_create_info{ + .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, + .setLayoutCount = (uint32_t)s->descriptor_set_layouts.size(), + .pSetLayouts = s->descriptor_set_layouts.data(), + }; + + CHECK_VK(vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &s->pipeline_layout)); + + return shaders.emplace_back(s); } -void scene_renderer::cleanup_image(scene_renderer::image & i) +VkPipeline scene_renderer::get_shader_pipeline(std::weak_ptr weak_shader, VkPrimitiveTopology topology, std::span vertex_bindings, std::span vertex_attributes) { - if (i.image) - vkDestroyImage(device, i.image, nullptr); + auto shader = weak_shader.lock(); + if (!shader) + return VK_NULL_HANDLE; - if (i.memory) - vkFreeMemory(device, i.memory, nullptr); + for (auto & i: shader->pipelines) + { + if (topology != i.first.topology) + continue; - i.image = VK_NULL_HANDLE; - i.memory = VK_NULL_HANDLE; + if (vertex_bindings.size() != i.first.vertex_bindings.size()) + continue; + + if (memcmp(vertex_bindings.data(), i.first.vertex_bindings.data(), vertex_bindings.size() * sizeof(VkVertexInputBindingDescription))) + continue; + + if (vertex_attributes.size() != i.first.vertex_attributes.size()) + continue; + + if (memcmp(vertex_attributes.data(), i.first.vertex_attributes.data(), vertex_attributes.size() * sizeof(VkVertexInputAttributeDescription))) + continue; + + return i.second; + } + + shader::pipeline_info info{ + .topology = topology, + .vertex_bindings = {vertex_bindings.begin(), vertex_bindings.end()}, + .vertex_attributes = {vertex_attributes.begin(), vertex_attributes.end()}, + }; + + VkPipelineColorBlendAttachmentState pcbas{ + .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT}; + + vk::pipeline::graphics_info pipeline_info{ + .shader_stages = + {{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = shader->vertex_shader, .pName = "main"}, + {.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = shader->fragment_shader, .pName = "main"}}, + .vertex_input_bindings = info.vertex_bindings, + .vertex_input_attributes = info.vertex_attributes, + .InputAssemblyState = {.topology = topology}, + .viewports = {VkViewport{.x = 0, + .y = 0, + .width = (float)output_size.width, + .height = (float)output_size.height, + .minDepth = 0, + .maxDepth = 1}}, + .scissors = {VkRect2D{ + .offset = {0, 0}, + .extent = output_size, + }}, + .RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1}, + .MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}, + .ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas}, + .dynamic_states = {}, + .renderPass = renderpass, + .subpass = 0, + }; + + vk::pipeline pipeline(device, pipeline_info, shader->pipeline_layout); + + return shader->pipelines.emplace_back(info, pipeline.release()).second; } -scene_renderer::image * scene_renderer::create_image(void * data, VkExtent2D size, VkFormat format) +void scene_renderer::cleanup_image(scene_renderer::image * i) { - auto i = std::make_unique(); + if (i->image_view) + vkDestroyImageView(device, i->image_view, nullptr); - try - { - uint32_t mipmaps = std::log2(std::max(size.width, size.height)) + 1; + if (i->vk_image) + vkDestroyImage(device, i->vk_image, nullptr); - VkImageCreateInfo image_info{ - .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, - .flags = 0, - .imageType = VK_IMAGE_TYPE_2D, - .format = format, - .extent = {size.width, size.height, 1}, - .mipLevels = mipmaps, - .arrayLayers = 1, - .samples = VK_SAMPLE_COUNT_1_BIT, - .tiling = VK_IMAGE_TILING_OPTIMAL, - .usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, - .sharingMode = VK_SHARING_MODE_EXCLUSIVE, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, - }; - - i->image = vk::image(device, image_info).release(); - i->memory = vk::device_memory(device, physical_device, i->image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release(); - - load_image(i->image, data, size, format, mipmaps); - } - catch (...) - { - cleanup_image(*i); - throw; - } - - return images.emplace_back(std::move(i)).get(); + if (i->memory) + vkFreeMemory(device, i->memory, nullptr); } -void scene_renderer::cleanup_buffer(scene_renderer::buffer & b) +std::weak_ptr scene_renderer::create_image(void * data, VkExtent2D size, VkFormat format) { - if (b.buffer) - vkDestroyBuffer(device, b.buffer, nullptr); - if (b.memory) - vkFreeMemory(device, b.memory, nullptr); + auto i = std::shared_ptr(new image, [&](image * i) { cleanup_image(i); }); - b.buffer = VK_NULL_HANDLE; - b.memory = VK_NULL_HANDLE; + uint32_t mipmaps = std::log2(std::max(size.width, size.height)) + 1; + + VkImageCreateInfo image_info{ + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .flags = 0, + .imageType = VK_IMAGE_TYPE_2D, + .format = format, + .extent = {size.width, size.height, 1}, + .mipLevels = mipmaps, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + }; + + i->vk_image = vk::image(device, image_info).release(); + i->memory = + vk::device_memory(device, physical_device, i->vk_image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release(); + + load_image(i->vk_image, data, size, format, mipmaps); + + VkImageViewCreateInfo image_view_info{ + .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .flags = 0, + .image = i->vk_image, + .viewType = VK_IMAGE_VIEW_TYPE_2D, + .format = format, + .components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}, + .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = mipmaps, + .baseArrayLayer = 0, + .layerCount = 1}}; + CHECK_VK(vkCreateImageView(device, &image_view_info, nullptr, &i->image_view)); + + return images.emplace_back(i); } -scene_renderer::buffer * scene_renderer::create_buffer(const void * data, size_t size, VkBufferUsageFlags usage) +void scene_renderer::cleanup_buffer(scene_renderer::buffer * b) { - auto b = std::make_unique(); + if (b->vk_buffer) + vkDestroyBuffer(device, b->vk_buffer, nullptr); + if (b->memory) + vkFreeMemory(device, b->memory, nullptr); +} - try - { - VkBufferCreateInfo buffer_info{ - .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - .size = size, - .usage = usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - .sharingMode = VK_SHARING_MODE_EXCLUSIVE, - }; +std::weak_ptr scene_renderer::create_buffer(const void * data, size_t size, VkBufferUsageFlags usage) +{ + auto b = std::shared_ptr(new buffer, [&](buffer * b) { cleanup_buffer(b); }); - b->buffer = vk::buffer(device, buffer_info).release(); - b->memory = vk::device_memory(device, physical_device, b->buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release(); + VkBufferCreateInfo buffer_info{ + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .size = size, + .usage = usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + }; - load_buffer(b->buffer, data, size); - } - catch (...) - { - cleanup_buffer(*b); - throw; - } + b->vk_buffer = vk::buffer(device, buffer_info).release(); + b->memory = + vk::device_memory(device, physical_device, b->vk_buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release(); - return buffers.emplace_back(std::move(b)).get(); + load_buffer(b->vk_buffer, data, size); + + return buffers.emplace_back(b); } scene_renderer::model * scene_renderer::load_gltf(const std::string & filename) @@ -775,7 +780,8 @@ scene_renderer::model * scene_renderer::load_gltf(const std::string & filename) for (tinygltf::Buffer & i: m->gltf_model.buffers) { - m->buffers.push_back(create_buffer(i.data, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT)); + m->buffers.push_back( + create_buffer(i.data, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT)); } std::vector srgb(m->gltf_model.images.size(), false); @@ -784,7 +790,8 @@ scene_renderer::model * scene_renderer::load_gltf(const std::string & filename) if (i.emissiveTexture.index >= 0 && i.emissiveTexture.index < (int)srgb.size()) srgb[i.emissiveTexture.index] = true; - if (i.pbrMetallicRoughness.baseColorTexture.index >= 0 && i.pbrMetallicRoughness.baseColorTexture.index < (int)srgb.size()) + if (i.pbrMetallicRoughness.baseColorTexture.index >= 0 && + i.pbrMetallicRoughness.baseColorTexture.index < (int)srgb.size()) srgb[i.pbrMetallicRoughness.baseColorTexture.index] = true; } diff --git a/client/src/render/scene_renderer.h b/client/src/render/scene_renderer.h index d17cf92a..36afbbf8 100644 --- a/client/src/render/scene_renderer.h +++ b/client/src/render/scene_renderer.h @@ -1,21 +1,3 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ #pragma once #include @@ -23,6 +5,8 @@ #include #include +#include "glm/vec2.hpp" +#include "glm/vec3.hpp" #include "tiny_gltf.h" #include "vk/buffer.h" #include "vk/command_pool.h" @@ -32,18 +16,31 @@ #include "vk/renderpass.h" class scene_renderer + { public: class shader { friend class scene_renderer; - VkDescriptorSetLayout descriptor_set_layout{}; + std::vector descriptor_set_layouts; std::vector descriptor_pools; + VkShaderModule vertex_shader{}; + VkShaderModule fragment_shader{}; VkPipelineLayout pipeline_layout{}; - VkPipeline pipeline{}; - VkShaderModule vertex_shader; - VkShaderModule fragment_shader; + + struct pipeline_info + { + VkPrimitiveTopology topology; + std::vector vertex_bindings; + std::vector vertex_attributes; + }; + + std::vector> pipelines; + + shader() = default; + shader(const shader &) = delete; + shader(shader &&) = delete; }; class image @@ -52,9 +49,13 @@ public: VkDeviceMemory memory{}; VkSampler sampler{}; - VkImage image{}; + VkImage vk_image{}; VkImageView image_view{}; VkDescriptorSet descriptor_set{}; + + image() = default; + image(const image &) = delete; + image(image &&) = delete; }; class buffer @@ -62,12 +63,32 @@ public: friend class scene_renderer; VkDeviceMemory memory{}; - VkBuffer buffer{}; + VkBuffer vk_buffer{}; + + buffer() = default; + buffer(const buffer &) = delete; + buffer(buffer &&) = delete; }; struct mesh_primitive { - shader * s; + struct vertex + { + glm::vec3 position; + glm::vec3 normal; + glm::vec2 texcoord; + }; + + VkPrimitiveTopology topology; + + VkPipeline pipeline; + + std::weak_ptr indices; + size_t indices_offset; + size_t indices_count; + + std::weak_ptr vertices; + size_t vertices_offset; }; class model @@ -75,8 +96,8 @@ public: friend class scene_renderer; tinygltf::Model gltf_model; - std::vector images; - std::vector buffers; + std::vector> images; + std::vector> buffers; }; class model_instance @@ -115,11 +136,11 @@ private: void load_image(VkImage i, void * data, VkExtent2D size, VkFormat format, uint32_t mipmap_count, VkImageLayout final_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // Scene data - std::vector> shaders; - std::vector> images; - std::vector> buffers; - std::vector> primitives; - std::vector> models; + std::vector> shaders; + std::vector> images; + std::vector> buffers; + std::vector> primitives; + std::vector> models; std::vector instances; // Destination images @@ -134,9 +155,9 @@ private: void cleanup(); void cleanup_output_images(); - void cleanup_shader(shader &); - void cleanup_buffer(buffer &); - void cleanup_image(image &); + void cleanup_shader(shader *); + void cleanup_buffer(buffer *); + void cleanup_image(image *); public: scene_renderer(VkDevice device, VkPhysicalDevice physical_device, VkQueue queue); @@ -146,16 +167,18 @@ public: void set_output_images(std::vector output_images, VkExtent2D output_size, VkFormat output_format); - shader * create_shader(std::string name, VkPrimitiveTopology topology, std::vector uniform_bindings, std::vector vertex_bindings, std::vector vertex_attributes); + std::weak_ptr create_shader(std::string name, + std::vector> uniform_bindings); - image * create_image(void * data, VkExtent2D size, VkFormat format); + VkPipeline get_shader_pipeline(std::weak_ptr shader, VkPrimitiveTopology topology, std::span vertex_bindings, std::span vertex_attributes); - buffer * create_buffer(const void * data, size_t size, VkBufferUsageFlags usage); + std::weak_ptr create_image(void * data, VkExtent2D size, VkFormat format); + + std::weak_ptr create_buffer(const void * data, size_t size, VkBufferUsageFlags usage); template // requires(std::contiguous_iterator) - buffer * create_buffer(const T & data, - VkBufferUsageFlags usage) + std::weak_ptr create_buffer(const T & data, VkBufferUsageFlags usage) { return create_buffer(data.data(), data.size() * sizeof(T), usage); } diff --git a/client/src/scenes/lobby.cpp b/client/src/scenes/lobby.cpp index 4ea7bf8c..e2fbb34e 100644 --- a/client/src/scenes/lobby.cpp +++ b/client/src/scenes/lobby.cpp @@ -357,7 +357,6 @@ void scenes::lobby::render() void scenes::lobby::render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index) { xr::swapchain & swapchain = swapchains[swapchain_index]; - xr::swapchain::image & swapchain_image = swapchain.images()[image_index]; image_data & data = images_data[swapchain_index][image_index]; VkClearValue clearColor = {{{0.0f, 0.0f, 0.0f, 1.0f}}}; diff --git a/client/src/scenes/stream.cpp b/client/src/scenes/stream.cpp index dece0f4d..ccebabee 100644 --- a/client/src/scenes/stream.cpp +++ b/client/src/scenes/stream.cpp @@ -211,7 +211,7 @@ void scenes::stream::render() application::pop_scene(); XrFrameState framestate = session.wait_frame(); - auto t0 = application::now(); + // auto t0 = application::now(); if (decoders.empty()) framestate.shouldRender = false; @@ -233,7 +233,7 @@ void scenes::stream::render() } session.begin_frame(); - auto dt2 = application::now() - t0; + // auto dt2 = application::now() - t0; auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space); assert(views.size() == swapchains.size()); @@ -354,7 +354,7 @@ void scenes::stream::render() .pCommandBuffers = &command_buffer, }; CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, fence)); - auto dt4 = application::now() - t0; + // auto dt4 = application::now() - t0; std::vector layers_base; std::vector layer_view; @@ -396,14 +396,14 @@ void scenes::stream::render() layers_base.push_back(reinterpret_cast(&layer)); session.end_frame(/*timestamp*/ framestate.predictedDisplayTime, layers_base); - auto dt5 = application::now() - t0; + // auto dt5 = application::now() - t0; CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX)); CHECK_VK(vkResetFences(device, 1, &fence)); // We don't need those after vkWaitForFences current_blit_handles.clear(); - auto dt6 = application::now() - t0; + // auto dt6 = application::now() - t0; read_actions(); // spdlog::info("Render timing: begin frame {:.3f}ms, submit commands {:.3f}ms, end frame {:.3f}ms, wait fence {:.3f}ms, predicted display time {:.3f}ms", dt2/1.e6, dt4/1.e6, dt5/1.e6, dt6/1.e6, (framestate.predictedDisplayTime - t0) / 1.e6); diff --git a/client/src/utils/backtrace.cpp b/client/src/utils/backtrace.cpp index f78b3738..091eacd6 100644 --- a/client/src/utils/backtrace.cpp +++ b/client/src/utils/backtrace.cpp @@ -81,21 +81,21 @@ static int iterate_phdr_callback(dl_phdr_info * info, size_t size, void * arg) return 0; } -static std::string unmangle(const char * function) -{ - if (!function) - return "(null)"; - - int status; - char * demangled = abi::__cxa_demangle(function, nullptr, nullptr, &status); - - if (status != 0) - return function; - - std::string s = demangled; - free(demangled); - return s; -} +// static std::string unmangle(const char * function) +// { +// if (!function) +// return "(null)"; +// +// int status; +// char * demangled = abi::__cxa_demangle(function, nullptr, nullptr, &status); +// +// if (status != 0) +// return function; +// +// std::string s = demangled; +// free(demangled); +// return s; +// } std::vector utils::backtrace(size_t max) { diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index ced5d0aa..071740cb 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -3,18 +3,23 @@ FetchContent_Declare(boostpfr URL https://github.com/boostorg/pfr/archive/refs/t FetchContent_MakeAvailable(boostpfr) -execute_process(COMMAND git describe --always OUTPUT_VARIABLE GIT_VERSION) -string(STRIP ${GIT_VERSION} GIT_VERSION) - -add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/version.cpp +add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/version.cpp COMMAND ${CMAKE_COMMAND} -D GIT_EXECUTABLE=${GIT_EXECUTABLE} - -D INPUT_FILE=${CMAKE_SOURCE_DIR}/common/version.cpp.in - -D OUTPUT_FILE=${CMAKE_BINARY_DIR}/version.cpp + -D INPUT_FILE=${CMAKE_CURRENT_SOURCE_DIR}/version.cpp.in + -D OUTPUT_FILE=${CMAKE_CURRENT_BINARY_DIR}/version.cpp -P ${CMAKE_SOURCE_DIR}/cmake/GitVersion.cmake ) file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS "*.cpp") -add_library(wivrn-common STATIC ${CMAKE_BINARY_DIR}/version.cpp ${LOCAL_SOURCES}) +configure_file(wivrn_config.h.in wivrn_config.h) -target_include_directories(wivrn-common PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +add_library(wivrn-common STATIC + wivrn_sockets.cpp + ${CMAKE_CURRENT_BINARY_DIR}/version.cpp +) + +target_link_libraries(wivrn-common PUBLIC Boost::pfr) +target_compile_features(wivrn-common PRIVATE cxx_std_20) + +target_include_directories(wivrn-common PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) diff --git a/common/wivrn_config.h.in b/common/wivrn_config.h.in new file mode 100644 index 00000000..3054e4ba --- /dev/null +++ b/common/wivrn_config.h.in @@ -0,0 +1,24 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#cmakedefine WIVRN_HAVE_X264 +#cmakedefine WIVRN_HAVE_CUDA +#cmakedefine WIVRN_HAVE_FFMPEG diff --git a/client/src/wivrn_packets.h b/common/wivrn_packets.h similarity index 100% rename from client/src/wivrn_packets.h rename to common/wivrn_packets.h diff --git a/client/src/wivrn_serialization.h b/common/wivrn_serialization.h similarity index 100% rename from client/src/wivrn_serialization.h rename to common/wivrn_serialization.h diff --git a/client/src/wivrn_sockets.cpp b/common/wivrn_sockets.cpp similarity index 100% rename from client/src/wivrn_sockets.cpp rename to common/wivrn_sockets.cpp diff --git a/client/src/wivrn_sockets.h b/common/wivrn_sockets.h similarity index 100% rename from client/src/wivrn_sockets.h rename to common/wivrn_sockets.h diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 616bcd71..c30df897 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -61,7 +61,6 @@ add_executable(monado-wivrn 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} @@ -99,16 +98,17 @@ compile_glsl(monado-wivrn ${VULKAN_SHADERS}) target_link_libraries( monado-wivrn PRIVATE - aux_os + aux_os aux_util - aux_vk + aux_vk comp_main ipc_server - xrt-external-openxr - xrt-interfaces + xrt-external-openxr + xrt-interfaces systemd - Boost::pfr + Boost::pfr PkgConfig::AVAHI Eigen3::Eigen + wivrn-common ) diff --git a/server/avahi_publisher.cpp b/server/avahi_publisher.cpp index 169fc665..c82fc178 100644 --- a/server/avahi_publisher.cpp +++ b/server/avahi_publisher.cpp @@ -1,26 +1,25 @@ #include "avahi_publisher.h" -#include #include -#include -#include -#include #include +#include +#include +#include +#include #include #include -void -avahi_publisher::alt_name() +void avahi_publisher::alt_name() { - char *new_name = avahi_alternative_service_name(name); + char * new_name = avahi_alternative_service_name(name); avahi_free(name); name = new_name; } -void -avahi_publisher::create_service(AvahiClient *client) +void avahi_publisher::create_service(AvahiClient * client) { - if (!entry_group) { + if (!entry_group) + { entry_group = avahi_entry_group_new(client, avahi_entry_group_callback, nullptr); } avahi_entry_group_reset(entry_group); @@ -29,73 +28,83 @@ avahi_publisher::create_service(AvahiClient *client) 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) { + 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) { + if (ret < 0) + { std::cerr << "Cannot add service: " << avahi_strerror(ret) << std::endl; } ret = avahi_entry_group_commit(entry_group); - if (ret < 0) { + if (ret < 0) + { std::cerr << "Cannot commit entry group: " << avahi_strerror(ret) << std::endl; - } else { + } + 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()*/) +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; + 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)); + 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; + 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() */) +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; + 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_COLLISION: + case AVAHI_CLIENT_S_REGISTERING: + avahi_entry_group_reset(self->entry_group); + break; - case AVAHI_CLIENT_S_RUNNING: self->create_service(s); 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_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); + 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)); @@ -108,26 +117,23 @@ avahi_publisher::~avahi_publisher() 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 * 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); + 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) +void avahi_publisher::watch_free(AvahiWatch * watch) { avahi_simple_poll_get(avahi_poll)->watch_free(watch); } -bool -avahi_publisher::iterate(int sleep_time) +bool avahi_publisher::iterate(int sleep_time) { int r = avahi_simple_poll_iterate(avahi_poll, sleep_time); diff --git a/server/avahi_publisher.h b/server/avahi_publisher.h index e9335ef2..3810fefb 100644 --- a/server/avahi_publisher.h +++ b/server/avahi_publisher.h @@ -1,51 +1,44 @@ #pragma once -#include #include #include +#include #include class avahi_publisher { - AvahiEntryGroup *entry_group{}; - char *name{}; + AvahiEntryGroup * entry_group{}; + char * name{}; std::string type; int port; - AvahiSimplePoll *avahi_poll{}; - AvahiClient *avahi_client{}; + AvahiSimplePoll * avahi_poll{}; + AvahiClient * avahi_client{}; - void - alt_name(); + void alt_name(); - void - create_service(AvahiClient *client); + 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 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() */); + 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(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); + AvahiWatch * watch_new(int fd, + AvahiWatchEvent event, + void (*callback)(AvahiWatch * w, int fd, AvahiWatchEvent event, void * userdata), + void * userdata); - void - watch_free(AvahiWatch *watch); + void watch_free(AvahiWatch * watch); - bool - iterate(int sleep_time = -1); + bool iterate(int sleep_time = -1); }; diff --git a/server/driver/encoder_settings.cpp b/server/driver/encoder_settings.cpp index 1d412be1..036562fc 100644 --- a/server/driver/encoder_settings.cpp +++ b/server/driver/encoder_settings.cpp @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "encoder_settings.h" #include "util/u_config_json.h" @@ -10,7 +25,9 @@ #include #include -#ifdef XRT_HAVE_FFMPEG +#include "wivrn_config.h" + +#ifdef WIVRN_HAVE_FFMPEG #include "ffmpeg/VideoEncoderVA.h" #endif @@ -19,16 +36,14 @@ 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) +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 -get_encoder_default_settings(vk_bundle *vk, uint16_t width, uint16_t height) +static std::vector get_encoder_default_settings(vk_bundle * vk, uint16_t width, uint16_t height) { xrt::drivers::wivrn::encoder_settings settings{}; settings.width = width; @@ -36,10 +51,11 @@ get_encoder_default_settings(vk_bundle *vk, uint16_t width, uint16_t height) settings.codec = xrt::drivers::wivrn::h265; settings.bitrate = default_bitrate; - if (is_nvidia(vk)) { -#ifdef XRT_HAVE_CUDA + if (is_nvidia(vk)) + { +#ifdef WIVRN_HAVE_CUDA settings.encoder_name = encoder_nvenc; -#elif defined(XRT_HAVE_X264) +#elif defined(WIVRN_HAVE_X264) settings.encoder_name = encoder_x264; settings.codec = xrt::drivers::wivrn::h264; U_LOG_W("nvidia GPU detected, but cuda support not compiled"); @@ -47,10 +63,12 @@ get_encoder_default_settings(vk_bundle *vk, uint16_t width, uint16_t height) U_LOG_E("no suitable encoder available (compile with x264 or cuda support)"); return {}; #endif - } else { -#ifdef XRT_HAVE_FFMPEG + } + else + { +#ifdef WIVRN_HAVE_FFMPEG settings.encoder_name = encoder_vaapi; -#elif defined(XRT_HAVE_X264) +#elif defined(WIVRN_HAVE_X264) settings.encoder_name = encoder_x264; settings.codec = xrt::drivers::wivrn::h264; U_LOG_W("ffmpeg support not compiled, vaapi encoder not available"); @@ -63,26 +81,28 @@ get_encoder_default_settings(vk_bundle *vk, uint16_t width, uint16_t height) return {settings}; } -std::vector -xrt::drivers::wivrn::get_encoder_settings(vk_bundle *vk, uint16_t width, uint16_t height) +std::vector xrt::drivers::wivrn::get_encoder_settings(vk_bundle * vk, uint16_t width, uint16_t height) { u_config_json config_json{}; std::unique_ptr raii(&config_json, u_config_json_close); u_config_json_open_or_create_main_file(&config_json); - if (!config_json.file_loaded) { + 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) { + 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) { + 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); } @@ -91,14 +111,16 @@ xrt::drivers::wivrn::get_encoder_settings(vk_bundle *vk, uint16_t width, uint16_ int next_group = 0; - for (int i = 0; i < num_encoders; ++i) { - cJSON *encoder = cJSON_GetArrayItem(config_encoder, i); + 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 { + else + { U_LOG_E("missing \"encoder\" key in config_wivrn"); continue; } @@ -133,20 +155,25 @@ xrt::drivers::wivrn::get_encoder_settings(vk_bundle *vk, uint16_t width, uint16_ settings.group = group->valueint; auto codec = u_json_get(encoder, "codec"); - if (codec && cJSON_IsString(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 { + 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)) { + if (options && cJSON_IsObject(options)) + { + for (auto child = options->child; child; child = child->next) + { + if (cJSON_IsString(child)) + { settings.options[child->string] = child->valuestring; } } @@ -160,16 +187,16 @@ xrt::drivers::wivrn::get_encoder_settings(vk_bundle *vk, uint16_t width, uint16_ return res; } -VkImageTiling -xrt::drivers::wivrn::get_required_tiling(vk_bundle *vk, - const std::vector &settings) +VkImageTiling xrt::drivers::wivrn::get_required_tiling(vk_bundle * vk, + const std::vector & 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) { + for (const auto & item: settings) + { +#ifdef WIVRN_HAVE_FFMPEG + if (item.encoder_name == encoder_vaapi) + { can_optimal = false; if (not use_drm_format_modifiers) can_drm = false; diff --git a/server/driver/encoder_settings.h b/server/driver/encoder_settings.h index ef5052b5..2ad28b0a 100644 --- a/server/driver/encoder_settings.h +++ b/server/driver/encoder_settings.h @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -10,7 +25,8 @@ #include #include -namespace xrt::drivers::wivrn { +namespace xrt::drivers::wivrn +{ struct encoder_settings : public to_headset::video_stream_description::item { @@ -22,12 +38,8 @@ struct encoder_settings : public to_headset::video_stream_description::item int group = 0; }; +std::vector get_encoder_settings(vk_bundle * vk, uint16_t width, uint16_t height); -std::vector -get_encoder_settings(vk_bundle *vk, uint16_t width, uint16_t height); - - -VkImageTiling -get_required_tiling(vk_bundle *vk, const std::vector &settings); +VkImageTiling get_required_tiling(vk_bundle * vk, const std::vector & settings); } // namespace xrt::drivers::wivrn diff --git a/server/driver/external/rs.c b/server/driver/external/rs.c index 8b11c48b..3ea6f6fe 100644 --- a/server/driver/external/rs.c +++ b/server/driver/external/rs.c @@ -39,8 +39,8 @@ #include #include -#include #include "rs.h" +#include #ifdef _MSC_VER #define alloca(x) _alloca(x) @@ -52,12 +52,12 @@ typedef unsigned char gf; #define GF_PP "101110001" #define GF_SIZE ((1 << GF_BITS) - 1) -#define SWAP(a, b, t) \ - { \ - t tmp; \ - tmp = a; \ - a = b; \ - b = tmp; \ +#define SWAP(a, b, t) \ + { \ + t tmp; \ + tmp = a; \ + a = b; \ + b = tmp; \ } /* @@ -67,7 +67,7 @@ typedef unsigned char gf; * 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 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] @@ -94,7 +94,8 @@ static gf gf_mul_table[(GF_SIZE + 1) * (GF_SIZE + 1)] __attribute__((aligned(256 static inline gf modnn(int x) { - while (x >= GF_SIZE) { + while (x >= GF_SIZE) + { x -= GF_SIZE; x = (x >> GF_BITS) + (x & GF_SIZE); } @@ -102,12 +103,13 @@ modnn(int x) } static void -addmul(gf *dst1, gf *src1, gf c, int sz) +addmul(gf * dst1, gf * src1, gf c, int sz) { USE_GF_MULC; - if (c != 0) { + if (c != 0) + { gf *dst = dst1, *src = src1; - gf *lim = &dst[sz]; + gf * lim = &dst[sz]; GF_MULC0(c); for (; dst < lim; dst++, src++) @@ -116,33 +118,37 @@ addmul(gf *dst1, gf *src1, gf c, int sz) } static void -mul(gf *dst1, gf *src1, gf c, int sz) +mul(gf * dst1, gf * src1, gf c, int sz) { USE_GF_MULC; - if (c != 0) { + if (c != 0) + { gf *dst = dst1, *src = src1; - gf *lim = &dst[sz]; + gf * lim = &dst[sz]; GF_MULC0(c); for (; dst < lim; dst++, src++) GF_MULC(*dst, *src); - } else + } + else memset(dst1, 0, c); } /* y = a.dot(b) */ static gf * -multiply1(gf *a, int ar, int ac, gf *b, int br, int bc) +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) { - + if (NULL != new_m) + { /* this multiply is slow */ - for (r = 0; r < ar; r++) { - for (c = 0; c < bc; c++) { + 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]); @@ -184,7 +190,8 @@ generate_gf(void) * 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) { + for (i = 0; i < GF_BITS; i++, mask <<= 1) + { gf_exp[i] = mask; gf_log[gf_exp[i]] = i; /* @@ -206,7 +213,8 @@ generate_gf(void) * \alpha ** i is shifted. */ mask = 1 << (GF_BITS - 1); - for (i = GF_BITS + 1; i < GF_SIZE; i++) { + 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 @@ -240,16 +248,16 @@ generate_gf(void) * Return non-zero if singular. */ static int -invert_mat(gf *src, int k) +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)); + 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)); /* @@ -258,35 +266,45 @@ invert_mat(gf *src, int k) for (i = 0; i < k; i++) ipiv[i] = 0; - for (col = 0; col < k; col++) { - gf *pivot_row; + 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) { + 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) { + 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) { + } + else if (ipiv[ix] > 1) + { fprintf(stderr, "singular matrix\n"); goto fail; } } } } - if (icol == -1) { + if (icol == -1) + { fprintf(stderr, "XXX pivot not found!\n"); goto fail; } @@ -298,8 +316,10 @@ invert_mat(gf *src, int k) * element will be correct. Rarely done, not worth * optimizing. */ - if (irow != icol) { - for (ix = 0; ix < k; ix++) { + if (irow != icol) + { + for (ix = 0; ix < k; ix++) + { SWAP(src[irow * k + ix], src[icol * k + ix], gf); } } @@ -307,10 +327,13 @@ invert_mat(gf *src, int k) indxc[col] = icol; pivot_row = &src[icol * k]; c = pivot_row[icol]; - if (c == 0) { + if (c == 0) + { fprintf(stderr, "singular matrix 2\n"); goto fail; - } else if (c != 1) { + } + else if (c != 1) + { /* * this is done often , but optimizing is not so * fruitful, at least in the obvious ways (unrolling) @@ -328,9 +351,12 @@ invert_mat(gf *src, int k) * 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) { + 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); @@ -339,12 +365,14 @@ invert_mat(gf *src, int k) } id_row[icol] = 0; } - for (col = k - 1; col >= 0; col--) { + 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]) { + else if (indxr[col] != indxc[col]) + { for (row = 0; row < k; row++) SWAP(src[row * k + indxr[col]], src[row * k + indxc[col]], gf); } @@ -359,14 +387,17 @@ fail: * Not check for input params * */ static gf * -sub_matrix(gf *matrix, int rmin, int cmin, int rmax, int cmax, int nrows, int ncols) +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++) { + 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]; } } @@ -377,13 +408,15 @@ sub_matrix(gf *matrix, int rmin, int cmin, int rmax, int cmax, int nrows, int nc /* copy from golang rs version */ static inline int -code_some_shards(gf *matrixRows, gf **inputs, gf **outputs, int dataShards, int outputCount, int byteCount) +code_some_shards(gf * matrixRows, gf ** inputs, gf ** outputs, int dataShards, int outputCount, int byteCount) { - gf *in; + gf * in; int iRow, c; - for (c = 0; c < dataShards; c++) { + for (c = 0; c < dataShards; c++) + { in = inputs[c]; - for (iRow = 0; iRow < outputCount; iRow++) { + for (iRow = 0; iRow < outputCount; iRow++) + { if (0 == c) mul(outputs[iRow], in, matrixRows[iRow * dataShards + c], byteCount); else @@ -394,8 +427,7 @@ code_some_shards(gf *matrixRows, gf **inputs, gf **outputs, int dataShards, int return 0; } -void -reed_solomon_init(void) +void reed_solomon_init(void) { generate_gf(); init_mul_table(); @@ -404,12 +436,13 @@ reed_solomon_init(void) reed_solomon * reed_solomon_new(int data_shards, int parity_shards) { - gf *vm = NULL; - gf *top = NULL; + gf * vm = NULL; + gf * top = NULL; int err = 0; - reed_solomon *rs = NULL; + reed_solomon * rs = NULL; - do { + do + { rs = (reed_solomon *)malloc(sizeof(reed_solomon)); if (NULL == rs) return NULL; @@ -420,26 +453,30 @@ reed_solomon_new(int data_shards, int parity_shards) rs->m = NULL; rs->parity = NULL; - if (rs->shards > DATA_SHARDS_MAX || data_shards <= 0 || parity_shards <= 0) { + 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) { + if (NULL == vm) + { err = 2; break; } int ptr = 0; - for (int row = 0; row < rs->shards; row++) { + 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) { + if (NULL == top) + { err = 3; break; } @@ -448,18 +485,21 @@ reed_solomon_new(int data_shards, int parity_shards) assert(0 == err); rs->m = multiply1(vm, rs->shards, data_shards, top, data_shards, data_shards); - if (NULL == rs->m) { + if (NULL == rs->m) + { err = 4; break; } - for (int j = 0; j < parity_shards; j++) { + 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) { + if (NULL == rs->parity) + { err = 5; break; } @@ -479,7 +519,8 @@ reed_solomon_new(int data_shards, int parity_shards) if (NULL != top) free(top); - if (NULL != rs) { + if (NULL != rs) + { if (NULL != rs->m) free(rs->m); @@ -492,10 +533,10 @@ reed_solomon_new(int data_shards, int parity_shards) return NULL; } -void -reed_solomon_release(reed_solomon *rs) +void reed_solomon_release(reed_solomon * rs) { - if (NULL != rs) { + if (NULL != rs) + { if (NULL != rs->m) free(rs->m); @@ -518,28 +559,31 @@ reed_solomon_release(reed_solomon *rs) * nr_fec_blocks: the number of erased blocks * */ static int -reed_solomon_decode(reed_solomon *rs, - gf *dataDecodeMatrix, - unsigned char **data_blocks, +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, + 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; + 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++) { + 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]) { + 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]; @@ -555,10 +599,12 @@ reed_solomon_decode(reed_solomon *rs, j = 0; subMatrixRow = 0; dataShards = rs->data_shards; - for (i = 0; i < dataShards; i++) { + for (i = 0; i < dataShards; i++) + { if (j < nr_fec_blocks && i == (int)erased_blocks[j]) j++; - else { + else + { /* this row is ok */ for (c = 0; c < dataShards; c++) dataDecodeMatrix[subMatrixRow * dataShards + c] = m[i * dataShards + c]; @@ -568,7 +614,8 @@ reed_solomon_decode(reed_solomon *rs, } } - for (i = 0; i < nr_fec_blocks && subMatrixRow < dataShards; i++) { + 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++) @@ -582,7 +629,8 @@ reed_solomon_decode(reed_solomon *rs, invert_mat(dataDecodeMatrix, dataShards); - for (i = 0; i < nr_fec_blocks; i++) { + 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); @@ -598,17 +646,17 @@ reed_solomon_decode(reed_solomon *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) +int reed_solomon_encode(reed_solomon * rs, unsigned char ** shards, int nr_shards, int block_size) { - unsigned char **data_blocks; - unsigned char **fec_blocks; + 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) { + 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; @@ -624,15 +672,14 @@ reed_solomon_encode(reed_solomon *rs, unsigned char **shards, int nr_shards, int * 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) +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 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 * fec_marks; unsigned char **data_blocks, **fec_blocks; - gf *dataDecodeMatrix = malloc(DATA_SHARDS_MAX * DATA_SHARDS_MAX * sizeof(gf)); + 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; @@ -643,16 +690,21 @@ reed_solomon_reconstruct(reed_solomon *rs, unsigned char **shards, unsigned char fec_marks = marks + n * ds; // after all data, is't fec marks fec_blocks = shards + n * ds; - for (j = 0; j < n; j++) { + for (j = 0; j < n; j++) + { dn = 0; - for (i = 0; i < ds; i++) { + for (i = 0; i < ds; i++) + { if (marks[i]) erased_blocks[dn++] = i; } - if (dn > 0) { + if (dn > 0) + { pn = 0; - for (i = 0; i < ps && pn < dn; i++) { - if (!fec_marks[i]) { + 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]; @@ -660,10 +712,11 @@ reed_solomon_reconstruct(reed_solomon *rs, unsigned char **shards, unsigned char } } - if (dn == pn) { - reed_solomon_decode(rs, dataDecodeMatrix, data_blocks, block_size, dec_fec_blocks, - fec_block_nos, erased_blocks, dn); - } else + 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; diff --git a/server/driver/external/rs.h b/server/driver/external/rs.h index 268cb301..d5514011 100644 --- a/server/driver/external/rs.h +++ b/server/driver/external/rs.h @@ -39,52 +39,53 @@ #define __RS_H_ #ifdef __cplusplus -extern "C" { +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; + 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); + /** + * 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); + 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); + /** + * 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); + /** + * 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 }; diff --git a/server/driver/ffmpeg/VideoEncoderFFMPEG.cpp b/server/driver/ffmpeg/VideoEncoderFFMPEG.cpp index c74702f5..ba3e021a 100644 --- a/server/driver/ffmpeg/VideoEncoderFFMPEG.cpp +++ b/server/driver/ffmpeg/VideoEncoderFFMPEG.cpp @@ -1,53 +1,73 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "VideoEncoderFFMPEG.h" #include #include #include -extern "C" { +extern "C" +{ #include } -namespace { +namespace +{ -bool -should_keep_nal_h264(const uint8_t *header_start) +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; + 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) +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; + 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 &out, VideoEncoderFFMPEG::Codec codec) +void filter_NAL(const uint8_t * input, size_t input_size, std::vector & out, VideoEncoderFFMPEG::Codec codec) { if (input_size < 4) return; std::array header = {{0, 0, 1}}; auto end = input + input_size; auto header_start = input; - while (header_start != end) { + 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) { + if (next_header != end and next_header[-1] == 0) + { next_header--; } if (codec == VideoEncoderFFMPEG::Codec::h264 and should_keep_nal_h264(header_start)) @@ -60,21 +80,22 @@ filter_NAL(const uint8_t *input, size_t input_size, std::vector &out, V } // namespace - -void -VideoEncoderFFMPEG::Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) +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(); + AVPacket * enc_pkt = av_packet_alloc(); int err = avcodec_receive_packet(encoder_ctx.get(), enc_pkt); - if (err == 0) { + if (err == 0) + { SendData({enc_pkt->data, enc_pkt->data + enc_pkt->size}); av_packet_free(&enc_pkt); } - if (err == AVERROR(EAGAIN)) { + if (err == AVERROR(EAGAIN)) + { return; } - if (err) { + if (err) + { throw std::runtime_error("frame encoding failed, code " + std::to_string(err)); } } diff --git a/server/driver/ffmpeg/VideoEncoderFFMPEG.h b/server/driver/ffmpeg/VideoEncoderFFMPEG.h index 99c8193e..2d003dcc 100644 --- a/server/driver/ffmpeg/VideoEncoderFFMPEG.h +++ b/server/driver/ffmpeg/VideoEncoderFFMPEG.h @@ -1,14 +1,29 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once -#include -#include -#include -#include "ffmpeg_helper.h" #include "../video_encoder.h" +#include "ffmpeg_helper.h" +#include +#include +#include class VideoEncoderFFMPEG : public VideoEncoder { diff --git a/server/driver/ffmpeg/VideoEncoderVA.cpp b/server/driver/ffmpeg/VideoEncoderVA.cpp index 56a528c2..0e8af827 100644 --- a/server/driver/ffmpeg/VideoEncoderVA.cpp +++ b/server/driver/ffmpeg/VideoEncoderVA.cpp @@ -1,15 +1,31 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "VideoEncoderVA.h" #include "ffmpeg_helper.h" #include "vk/vk_helpers.h" #include -#include #include +#include -extern "C" { +extern "C" +{ #include #include #include @@ -20,25 +36,29 @@ extern "C" { #include } -namespace { +namespace +{ const char * encoder(VideoEncoderFFMPEG::Codec codec) { - switch (codec) { - case VideoEncoderFFMPEG::Codec::h264: return "h264_vaapi"; - case VideoEncoderFFMPEG::Codec::h265: return "hevc_vaapi"; + 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) +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) { + if (not hw_frames_ref) + { throw std::runtime_error("Failed to create VAAPI frame context."); } auto frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data); @@ -47,7 +67,8 @@ set_hwframe_ctx(AVCodecContext *ctx, AVBufferRef *hw_device_ctx) 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) { + 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()); @@ -56,7 +77,7 @@ set_hwframe_ctx(AVCodecContext *ctx, AVBufferRef *hw_device_ctx) } std::string -get_render_device(vk_bundle *vk) +get_render_device(vk_bundle * vk) { VkPhysicalDeviceDrmPropertiesEXT drmProps{}; drmProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT; @@ -67,7 +88,8 @@ get_render_device(vk_bundle *vk) vk->vkGetPhysicalDeviceProperties2(vk->physical_device, &props); - if (!drmProps.hasRender) { + if (!drmProps.hasRender) + { U_LOG_E("Failed to find render DRM device"); throw std::runtime_error("Failed to find render DRM device"); } @@ -76,8 +98,8 @@ get_render_device(vk_bundle *vk) } // 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) +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 @@ -91,32 +113,41 @@ VideoEncoderVA::VideoEncoderVA(vk_bundle *vk, const encoder_settings &settings, * and the encoder that takes the converted frame and produces packets. */ - AVBufferRef *tmp; + 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) { + 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) { + 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) { + if (not encoder_ctx) + { throw std::runtime_error("failed to allocate VAAPI encoder"); } - AVDictionary *opts = nullptr; - for (auto option : settings.options) { + 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; + 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; @@ -133,56 +164,66 @@ VideoEncoderVA::VideoEncoderVA(vk_bundle *vk, const encoder_settings &settings, err = avcodec_open2(encoder_ctx.get(), codec, &opts); av_dict_free(&opts); - if (err < 0) { + 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) +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) { + 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) { + 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) { + 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) +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) { + if (!va_ctx) + { throw std::runtime_error("Failed to create VAAPI frame context."); } - AVHWFramesContext *va_frames_ctx = (AVHWFramesContext *)(va_ctx->data); + 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) { + 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) { + for (int i = 0; i < num_images; ++i) + { VkMemoryRequirements req; vk->vkGetImageMemoryRequirements(vk->device, images[i], &req); @@ -199,7 +240,7 @@ VideoEncoderVA::SetImages( 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]; + 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; @@ -210,7 +251,8 @@ VideoEncoderVA::SetImages( // 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) { + if (drm_tiling) + { VkImageDrmFormatModifierPropertiesEXT modifiers{}; modifiers.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT; vk->vkGetImageDrmFormatModifierPropertiesEXT(vk->device, images[i], &modifiers); @@ -218,9 +260,10 @@ VideoEncoderVA::SetImages( } // 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}; + ? 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; @@ -243,19 +286,18 @@ VideoEncoderVA::SetImages( InitFilterGraph(); } -void -VideoEncoderVA::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(); + 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(); + AVBufferSrcParameters * par = av_buffersrc_parameters_alloc(); memset(par, 0, sizeof(*par)); par->width = mapped_frames[0]->width; par->height = mapped_frames[0]->height; @@ -266,8 +308,8 @@ VideoEncoderVA::InitFilterGraph() av_free(par); int err; - if ((err = avfilter_graph_create_filter(&filter_out, avfilter_get_by_name("buffersink"), "out", NULL, NULL, - filter_graph.get()))) { + 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"); } @@ -286,11 +328,13 @@ VideoEncoderVA::InitFilterGraph() 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) { + 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))) { + if ((err = avfilter_graph_config(filter_graph.get(), NULL))) + { throw std::system_error(err, av_error_category(), "avfilter_graph_config failed"); } } diff --git a/server/driver/ffmpeg/VideoEncoderVA.h b/server/driver/ffmpeg/VideoEncoderVA.h index 0e3815e4..674c855c 100644 --- a/server/driver/ffmpeg/VideoEncoderVA.h +++ b/server/driver/ffmpeg/VideoEncoderVA.h @@ -1,14 +1,30 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once #include "VideoEncoderFFMPEG.h" -#include "vk/vk_helpers.h" #include "ffmpeg_helper.h" +#include "vk/vk_helpers.h" -extern "C" { +extern "C" +{ #include } @@ -20,16 +36,16 @@ struct AVFilterContext; class VideoEncoderVA : public VideoEncoderFFMPEG { public: - VideoEncoderVA(vk_bundle *vk, const encoder_settings &settings, float fps); + 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; + VkImage * images, + VkImageView * views, + VkDeviceMemory * memory) override; void PushFrame(uint32_t frame_index, bool idr, std::chrono::steady_clock::time_point pts) override; @@ -38,7 +54,7 @@ private: void InitFilterGraph(); - vk_bundle *vk; + vk_bundle * vk; int width; int height; // relevant part of the input image to encode @@ -47,6 +63,6 @@ private: av_buffer_ptr hw_ctx_vaapi; std::vector mapped_frames; av_filter_graph_ptr filter_graph; - AVFilterContext *filter_in = nullptr; - AVFilterContext *filter_out = nullptr; + AVFilterContext * filter_in = nullptr; + AVFilterContext * filter_out = nullptr; }; diff --git a/server/driver/ffmpeg/ffmpeg_helper.cpp b/server/driver/ffmpeg/ffmpeg_helper.cpp index f47ddb35..3242dde0 100644 --- a/server/driver/ffmpeg/ffmpeg_helper.cpp +++ b/server/driver/ffmpeg/ffmpeg_helper.cpp @@ -1,11 +1,27 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "ffmpeg_helper.h" #include -extern "C" { +extern "C" +{ #include #include #include @@ -13,7 +29,8 @@ extern "C" { #include } -namespace { +namespace +{ struct : public std::error_category { const char * @@ -41,11 +58,15 @@ av_error_category() AVPixelFormat vk_format_to_av_format(VkFormat vk_fmt) { - switch (vk_fmt) { - case VK_FORMAT_B8G8R8A8_SRGB: return AV_PIX_FMT_BGRA; - default: break; + 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) { + 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); @@ -56,40 +77,40 @@ vk_format_to_av_format(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; + 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) +void AvDeleter::operator()(AVBufferRef * x) { av_buffer_unref(&x); } -void -AvDeleter::operator()(AVFrame *x) +void AvDeleter::operator()(AVFrame * x) { av_frame_unref(x); } -void -AvDeleter::operator()(AVCodecContext *x) +void AvDeleter::operator()(AVCodecContext * x) { avcodec_free_context(&x); } -void -AvDeleter::operator()(AVFilterGraph *x) +void AvDeleter::operator()(AVFilterGraph * x) { avfilter_graph_free(&x); } av_frame_ptr -make_av_frame(AVFrame *frame) +make_av_frame(AVFrame * frame) { return av_frame_ptr(frame); } diff --git a/server/driver/ffmpeg/ffmpeg_helper.h b/server/driver/ffmpeg/ffmpeg_helper.h index 4424fcac..605e6728 100644 --- a/server/driver/ffmpeg/ffmpeg_helper.h +++ b/server/driver/ffmpeg/ffmpeg_helper.h @@ -1,21 +1,37 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once +#include "vk/vk_helpers.h" #include #include #include #include -#include "vk/vk_helpers.h" struct AVBufferRef; struct AVFilterGraph; struct AVFrame; struct AVCodecContext; -extern "C" { +extern "C" +{ #include } diff --git a/server/driver/pose_list.cpp b/server/driver/pose_list.cpp index c03d1c03..5ce1c67b 100644 --- a/server/driver/pose_list.cpp +++ b/server/driver/pose_list.cpp @@ -1,27 +1,40 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "pose_list.h" +#include "math/m_eigen_interop.hpp" #include "math/m_space.h" +#include "math/m_vec3.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 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(&a), const_cast(&b), t, flags, &result); + m_space_relation_interpolate(const_cast(&a), const_cast(&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) +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; @@ -38,7 +51,6 @@ extrapolate(const xrt_space_relation &a, const xrt_space_relation &b, uint64_t t // 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; @@ -53,10 +65,10 @@ extrapolate(const xrt_space_relation &a, const xrt_space_relation &b, uint64_t t return res; } -void -pose_list::update_tracking(const from_headset::tracking &tracking, const clock_offset &offset) +void pose_list::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset) { - for (const auto &pose : tracking.device_poses) { + for (const auto & pose: tracking.device_poses) + { if (pose.device != device) continue; @@ -65,8 +77,7 @@ pose_list::update_tracking(const from_headset::tracking &tracking, const clock_o } } -xrt_space_relation -pose_list::convert_pose(const from_headset::tracking::pose &pose) +xrt_space_relation pose_list::convert_pose(const from_headset::tracking::pose & pose) { xrt_space_relation res{}; diff --git a/server/driver/pose_list.h b/server/driver/pose_list.h index 1c09cb7f..4053f3c8 100644 --- a/server/driver/pose_list.h +++ b/server/driver/pose_list.h @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -9,11 +24,13 @@ #include #include -template class history +template +class history { struct TimedData : public Data { - TimedData(const Data &d, uint64_t t) : Data(d), at_timestamp_ns(t) {} + TimedData(const Data & d, uint64_t t) : + Data(d), at_timestamp_ns(t) {} uint64_t at_timestamp_ns; }; @@ -21,14 +38,12 @@ template class history std::vector data; protected: - void - add_sample(uint64_t timestamp, const Data &sample, const clock_offset &offset) + 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; }); + 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); @@ -42,55 +57,55 @@ protected: } public: - Data - get_at(uint64_t at_timestamp_ns) + Data get_at(uint64_t at_timestamp_ns) { std::lock_guard lock(mutex); - if (data.empty()) { + if (data.empty()) + { return {}; } - if (data.size() == 1) { + 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); + 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) { + 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(); + 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 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); +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 { device_id device; public: - pose_list(device_id id) : device(id) {} + pose_list(device_id id) : + device(id) {} - void - update_tracking(const from_headset::tracking &, const clock_offset &offset); + void update_tracking(const from_headset::tracking &, const clock_offset & offset); - static xrt_space_relation - convert_pose(const from_headset::tracking::pose &); + static xrt_space_relation convert_pose(const from_headset::tracking::pose &); }; diff --git a/server/driver/shaders/yuv_converter.uv.frag.glsl b/server/driver/shaders/yuv_converter.uv.frag.glsl index 28670315..aeb7f7af 100644 --- a/server/driver/shaders/yuv_converter.uv.frag.glsl +++ b/server/driver/shaders/yuv_converter.uv.frag.glsl @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #version 450 diff --git a/server/driver/shaders/yuv_converter.vert.glsl b/server/driver/shaders/yuv_converter.vert.glsl index 54098018..5dab93bd 100644 --- a/server/driver/shaders/yuv_converter.vert.glsl +++ b/server/driver/shaders/yuv_converter.vert.glsl @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #version 450 diff --git a/server/driver/shaders/yuv_converter.y.frag.glsl b/server/driver/shaders/yuv_converter.y.frag.glsl index 3e1df30a..592661da 100644 --- a/server/driver/shaders/yuv_converter.y.frag.glsl +++ b/server/driver/shaders/yuv_converter.y.frag.glsl @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #version 450 diff --git a/server/driver/video_encoder.cpp b/server/driver/video_encoder.cpp index 0df43a91..6fc8e0e3 100644 --- a/server/driver/video_encoder.cpp +++ b/server/driver/video_encoder.cpp @@ -1,61 +1,87 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "video_encoder.h" #include "external/rs.h" #include "util/u_logging.h" -#include "xrt/xrt_defines.h" #include -#ifdef XRT_HAVE_CUDA +#include "wivrn_config.h" + +#ifdef WIVRN_HAVE_CUDA #include "video_encoder_nvenc.h" #endif -#ifdef XRT_HAVE_FFMPEG +#ifdef WIVRN_HAVE_FFMPEG #include "ffmpeg/VideoEncoderVA.h" #endif -#ifdef XRT_HAVE_X264 +#ifdef WIVRN_HAVE_X264 #include "video_encoder_x264.h" #endif -namespace xrt::drivers::wivrn { +namespace xrt::drivers::wivrn +{ -std::unique_ptr -VideoEncoder::Create( - vk_bundle *vk, encoder_settings &settings, uint8_t stream_idx, int input_width, int input_height, float fps) +std::unique_ptr 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 res; -#ifdef XRT_HAVE_X264 - if (settings.encoder_name == encoder_x264) { +#ifdef WIVRN_HAVE_X264 + if (settings.encoder_name == encoder_x264) + { res = std::make_unique(vk, settings, input_width, input_height, fps); } #endif -#ifdef XRT_HAVE_CUDA - if (settings.encoder_name == encoder_nvenc) { +#ifdef WIVRN_HAVE_CUDA + if (settings.encoder_name == encoder_nvenc) + { res = std::make_unique(vk, settings, fps); } #endif -#ifdef XRT_HAVE_FFMPEG - if (settings.encoder_name == encoder_vaapi) { +#ifdef WIVRN_HAVE_FFMPEG + if (settings.encoder_name == encoder_vaapi) + { res = std::make_unique(vk, settings, fps); } #endif - if (res) { + if (res) + { res->stream_idx = stream_idx; - } else { + } + 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) +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; @@ -66,10 +92,10 @@ VideoEncoder::Encode(wivrn_session &cnx, 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) { + 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); + 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; @@ -79,10 +105,11 @@ VideoEncoder::Encode(wivrn_session &cnx, std::vector> data_shards; data_shards.reserve(shards.size()); size_t max_size = 0; - for (const auto &shard : shards) { + for (const auto & shard: shards) + { serialization_packet packet; packet.serialize(shard); - const auto &serialized = data_shards.emplace_back(std::move(packet)); + const auto & serialized = data_shards.emplace_back(std::move(packet)); max_size = std::max(max_size, serialized.size()); } @@ -91,12 +118,14 @@ VideoEncoder::Encode(wivrn_session &cnx, std::vector shard_pointers; - for (auto &shard : data_shards) { + for (auto & shard: data_shards) + { shard.resize(max_size, 0); shard_pointers.push_back(shard.data()); } - for (auto &shard : parity_shards) { + for (auto & shard: parity_shards) + { shard.resize(max_size, 0); shard_pointers.push_back(shard.data()); } @@ -106,10 +135,12 @@ VideoEncoder::Encode(wivrn_session &cnx, std::unique_ptr rs(reed_solomon_new(shards.size(), parity), reed_solomon_release); - if (rs) { + if (rs) + { reed_solomon_encode(rs.get(), shard_pointers.data(), shard_pointers.size(), max_size); - for (auto &shard : parity_shards) { + for (auto & shard: parity_shards) + { to_headset::video_stream_parity_shard packet{}; packet.stream_item_idx = stream_idx; packet.frame_idx = frame_idx; @@ -118,25 +149,29 @@ VideoEncoder::Encode(wivrn_session &cnx, packet.payload = std::move(shard); cnx.send_stream(packet); } - } else { + } + else + { U_LOG_W("failed to setup reed_solomon encoder with %ld data shards", data_shards.size()); } } -void -VideoEncoder::SendData(std::vector &&data) +void VideoEncoder::SendData(std::vector && data) { - auto &max_payload_size = to_headset::video_stream_data_shard::max_payload_size; + 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) { + 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) { + while (begin != end) + { auto next = std::min(end, begin + max_payload_size); - if (next == end) { + if (next == end) + { flags |= to_headset::video_stream_data_shard::end_of_slice; } PushShard({begin, next}, flags); @@ -145,10 +180,10 @@ VideoEncoder::SendData(std::vector &&data) } } -void -VideoEncoder::PushShard(std::vector &&payload, uint8_t flags) +void VideoEncoder::PushShard(std::vector && payload, uint8_t flags) { - if (not shards.empty()) { + if (not shards.empty()) + { cnx->send_stream(shards.back()); } to_headset::video_stream_data_shard shard; diff --git a/server/driver/video_encoder.h b/server/driver/video_encoder.h index f1619c6e..c51e897b 100644 --- a/server/driver/video_encoder.h +++ b/server/driver/video_encoder.h @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -15,11 +30,12 @@ #include "wivrn_packets.h" #include "wivrn_session.h" -namespace xrt::drivers::wivrn { +namespace xrt::drivers::wivrn +{ -inline const char *encoder_nvenc = "nvenc"; -inline const char *encoder_vaapi = "vaapi"; -inline const char *encoder_x264 = "x264"; +inline const char * encoder_nvenc = "nvenc"; +inline const char * encoder_vaapi = "vaapi"; +inline const char * encoder_x264 = "x264"; class VideoEncoder { @@ -28,56 +44,48 @@ class VideoEncoder uint64_t frame_idx; // temporary data - wivrn_session *cnx; + wivrn_session * cnx; std::vector shards; public: - static std::unique_ptr - Create(vk_bundle *vk, - encoder_settings &settings, - uint8_t stream_idx, - int input_width, - int input_height, - float fps); + static std::unique_ptr 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; + 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) + 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); - + 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; + virtual void Encode(int index, bool idr, std::chrono::steady_clock::time_point target_timestamp) = 0; - void - SendData(std::vector &&data); + void SendData(std::vector && data); private: - void - PushShard(std::vector &&payload, uint8_t flags); + void PushShard(std::vector && payload, uint8_t flags); }; } // namespace xrt::drivers::wivrn diff --git a/server/driver/video_encoder_nvenc.cpp b/server/driver/video_encoder_nvenc.cpp index 908bd31a..f1203d35 100644 --- a/server/driver/video_encoder_nvenc.cpp +++ b/server/driver/video_encoder_nvenc.cpp @@ -1,47 +1,67 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "video_encoder_nvenc.h" #include "external/nvEncodeAPI.h" #include -#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"); \ - } \ +#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"); \ - } \ +#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"); \ - } \ +#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 { +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) +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)); @@ -50,7 +70,6 @@ VideoEncoderNvenc::VideoEncoderNvenc(vk_bundle *vk, const encoder_settings &sett 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; @@ -66,15 +85,20 @@ VideoEncoderNvenc::VideoEncoderNvenc(vk_bundle *vk, const encoder_settings &sett 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; + switch (codec) + { + case video_codec::h264: + printf("%d H264 presets\n", count); + break; - case video_codec::h265: printf("%d HEVC 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]); + 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{}; @@ -89,14 +113,13 @@ VideoEncoderNvenc::VideoEncoderNvenc(vk_bundle *vk, const encoder_settings &sett 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) +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 : @@ -110,7 +133,6 @@ VideoEncoderNvenc::SetImages(int full_width, 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 @@ -123,17 +145,18 @@ VideoEncoderNvenc::SetImages(int full_width, 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; + 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{}; @@ -168,7 +191,8 @@ VideoEncoderNvenc::SetImages(int full_width, // TODO: cleanup on error this->images.resize(num_images); CU_CHECK(cuCtxPushCurrent(cuda)); - for (int i = 0; i < num_images; i++) { + for (int i = 0; i < num_images; i++) + { VkMemoryGetFdInfoKHR getinfo{}; getinfo.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR; getinfo.pNext = nullptr; @@ -217,8 +241,7 @@ VideoEncoderNvenc::SetImages(int full_width, CU_CHECK(cuCtxPopCurrent(NULL)); } -void -VideoEncoderNvenc::Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) +void VideoEncoderNvenc::Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) { CU_CHECK(cuCtxPushCurrent(cuda)); CUDA_MEMCPY2D copy{}; @@ -259,7 +282,7 @@ VideoEncoderNvenc::Encode(int index, bool idr, std::chrono::steady_clock::time_p NVENC_CHECK(fn.nvEncLockBitstream(session_handle, ¶m2)); SendData( - {(uint8_t *)param2.bitstreamBufferPtr, (uint8_t *)param2.bitstreamBufferPtr + param2.bitstreamSizeInBytes}); + {(uint8_t *)param2.bitstreamBufferPtr, (uint8_t *)param2.bitstreamBufferPtr + param2.bitstreamSizeInBytes}); NVENC_CHECK(fn.nvEncUnlockBitstream(session_handle, bitstreamBuffer)); diff --git a/server/driver/video_encoder_nvenc.h b/server/driver/video_encoder_nvenc.h index 71cc9ca8..f26a098e 100644 --- a/server/driver/video_encoder_nvenc.h +++ b/server/driver/video_encoder_nvenc.h @@ -1,18 +1,34 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once -#include "video_encoder.h" #include "external/nvEncodeAPI.h" +#include "video_encoder.h" #include -namespace xrt::drivers::wivrn { +namespace xrt::drivers::wivrn +{ class VideoEncoderNvenc : public VideoEncoder { - vk_bundle *vk; + vk_bundle * vk; // relevant part of the input image to encode int offset_x; int offset_y; @@ -21,7 +37,7 @@ class VideoEncoderNvenc : public VideoEncoder NV_ENCODE_API_FUNCTION_LIST fn; CUcontext cuda; - void *session_handle; + void * session_handle; NV_ENC_OUTPUT_PTR bitstreamBuffer; struct image_data @@ -40,20 +56,17 @@ class VideoEncoderNvenc : public VideoEncoder bool supports_frame_invalidation; public: - VideoEncoderNvenc(vk_bundle *vk, const encoder_settings &settings, float fps); + 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 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; + void Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) override; }; - } // namespace xrt::drivers::wivrn diff --git a/server/driver/video_encoder_x264.cpp b/server/driver/video_encoder_x264.cpp index f4e36d93..0f514b4f 100644 --- a/server/driver/video_encoder_x264.cpp +++ b/server/driver/video_encoder_x264.cpp @@ -1,55 +1,78 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "video_encoder_x264.h" #include -namespace xrt::drivers::wivrn { - -void -VideoEncoderX264::ProcessCb(x264_t *h, x264_nal_t *nal, void *opaque) +namespace xrt::drivers::wivrn { - VideoEncoderX264 *self = (VideoEncoderX264 *)opaque; + +void VideoEncoderX264::ProcessCb(x264_t * h, x264_nal_t * nal, void * opaque) +{ + VideoEncoderX264 * self = (VideoEncoderX264 *)opaque; std::vector 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)}); + 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) +void VideoEncoderX264::ProcessNal(pending_nal && nal) { std::lock_guard lock(mutex); - if (nal.first_mb == next_mb) { + if (nal.first_mb == next_mb) + { next_mb = nal.last_mb + 1; SendData(std::move(nal.data)); - } else { + } + else + { InsertInPendingNal(std::move(nal)); } - while ((not pending_nals.empty()) and pending_nals.front().first_mb == next_mb) { + 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) +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) { + for (; it != end; ++it) + { + if (it->first_mb > nal.last_mb) + { pending_nals.insert(it, std::move(nal)); return; } @@ -58,10 +81,15 @@ VideoEncoderX264::InsertInPendingNal(pending_nal &&nal) } VideoEncoderX264::VideoEncoderX264( - vk_bundle *vk, encoder_settings &settings, int input_width, int input_height, float fps) - : vk(vk) + vk_bundle * vk, + encoder_settings & settings, + int input_width, + int input_height, + float fps) : + vk(vk) { - if (settings.codec != h264) { + if (settings.codec != h264) + { U_LOG_W("requested x264 encoder with codec != h264"); settings.codec = h264; } @@ -71,8 +99,7 @@ VideoEncoderX264::VideoEncoderX264( settings.height += settings.height % 2; converter = - std::make_unique(vk, VkExtent3D{uint32_t(settings.width), uint32_t(settings.height), 1}, - settings.offset_x, settings.offset_y, input_width, input_height); + std::make_unique(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; @@ -98,14 +125,14 @@ VideoEncoderX264::VideoEncoderX264( 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) { + if (not enc) + { throw std::runtime_error("failed to create x264 encoder"); } assert(x264_encoder_maximum_delayed_frames(enc) == 0); - - auto &pic = pic_in; + auto & pic = pic_in; x264_picture_init(&pic); pic.opaque = this; pic.img.i_csp = X264_CSP_NV12; @@ -117,34 +144,32 @@ VideoEncoderX264::VideoEncoderX264( 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) +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) +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) +void VideoEncoderX264::Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) { int num_nal; - x264_nal_t *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) { + if (size < 0) + { U_LOG_W("x264_encoder_encode failed: %d", size); return; } - if (size == 0) { + if (size == 0) + { return; } } diff --git a/server/driver/video_encoder_x264.h b/server/driver/video_encoder_x264.h index 9ecdbd47..94490498 100644 --- a/server/driver/video_encoder_x264.h +++ b/server/driver/video_encoder_x264.h @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -8,17 +23,18 @@ #include "x264.h" #include "yuv_converter.h" -#include #include +#include -namespace xrt::drivers::wivrn { +namespace xrt::drivers::wivrn +{ class VideoEncoderX264 : public VideoEncoder { x264_param_t param = {}; - x264_t *enc; + x264_t * enc; - vk_bundle *vk; + vk_bundle * vk; x264_picture_t pic_in; x264_picture_t pic_out = {}; std::unique_ptr converter; @@ -35,35 +51,28 @@ class VideoEncoderX264 : public VideoEncoder std::list pending_nals; public: - VideoEncoderX264(vk_bundle *vk, encoder_settings &settings, int input_width, int input_height, float fps); + 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 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 PresentImage(int index, VkCommandBuffer * out_buffer) override; - void - Encode(int index, bool idr, std::chrono::steady_clock::time_point pts) 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); + static void ProcessCb(x264_t * h, x264_nal_t * nal, void * opaque); - void - ProcessNal(pending_nal &&nal); + void ProcessNal(pending_nal && nal); - void - InsertInPendingNal(pending_nal &&nal); + void InsertInPendingNal(pending_nal && nal); }; - } // namespace xrt::drivers::wivrn diff --git a/server/driver/view_list.cpp b/server/driver/view_list.cpp index a9dd0614..dcd5db1d 100644 --- a/server/driver/view_list.cpp +++ b/server/driver/view_list.cpp @@ -1,32 +1,45 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #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 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 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) +void view_list::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset) { - for (const auto &pose : tracking.device_poses) { + for (const auto & pose: tracking.device_poses) + { if (pose.device != device_id::HEAD) continue; @@ -35,7 +48,8 @@ view_list::update_tracking(const from_headset::tracking &tracking, const clock_o view.relation = pose_list::convert_pose(pose); view.flags = tracking.flags; - for (size_t eye = 0; eye < 2; ++eye) { + 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); } diff --git a/server/driver/view_list.h b/server/driver/view_list.h index 12622de4..d75a402d 100644 --- a/server/driver/view_list.h +++ b/server/driver/view_list.h @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -15,15 +30,12 @@ struct tracked_views std::array fovs; }; -tracked_views -interpolate(const tracked_views &a, const tracked_views &b, float t); +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); +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 { public: - void - update_tracking(const from_headset::tracking &tracking, const clock_offset &offset); + void update_tracking(const from_headset::tracking & tracking, const clock_offset & offset); }; diff --git a/server/driver/wivrn_comp_target.cpp b/server/driver/wivrn_comp_target.cpp index 9bd60e8c..abeac6f5 100644 --- a/server/driver/wivrn_comp_target.cpp +++ b/server/driver/wivrn_comp_target.cpp @@ -1,26 +1,40 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #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 "video_encoder.h" #include "xrt/xrt_config_have.h" #include "xrt_cast.h" #include +#include #include #include #include -#include static const uint8_t image_free = 0; static const uint8_t image_acquired = 1; struct pseudo_swapchain { - struct pseudo_swapchain_memory { VkFence fence; @@ -36,7 +50,7 @@ struct pseudo_swapchain struct wivrn_comp_target : public comp_target { //! Compositor frame pacing helper - struct u_pacing_compositor *upc{}; + struct u_pacing_compositor * upc{}; float fps; @@ -70,33 +84,31 @@ struct wivrn_comp_target : public comp_target std::shared_ptr cnx; }; +static void target_init_semaphores(struct wivrn_comp_target * cn); -static void -target_init_semaphores(struct wivrn_comp_target *cn); +static void target_fini_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) +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) +static void destroy_images(struct wivrn_comp_target * cn) { - if (cn->images == NULL) { + if (cn->images == NULL) + { return; } cn->encoder_threads.clear(); cn->encoders.clear(); - struct vk_bundle *vk = get_vk(cn); + 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) { + for (uint32_t i = 0; i < cn->image_count; i++) + { + if (cn->images[i].view == VK_NULL_HANDLE) + { continue; } @@ -115,16 +127,14 @@ destroy_images(struct wivrn_comp_target *cn) struct encoder_thread_param { - wivrn_comp_target *cn; - wivrn_comp_target::encoder_thread *thread; + wivrn_comp_target * cn; + wivrn_comp_target::encoder_thread * thread; std::vector> encoders; }; -static void * -comp_wivrn_present_thread(void *void_param); +static void * comp_wivrn_present_thread(void * void_param); -static void -create_encoders(wivrn_comp_target *cn, std::vector &_settings) +static void create_encoders(wivrn_comp_target * cn, std::vector & _settings) { auto vk = get_vk(cn); assert(cn->encoders.empty()); @@ -137,30 +147,32 @@ create_encoders(wivrn_comp_target *cn, std::vector &_settings) std::map thread_params; - for (auto &settings : _settings) { + 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)); + 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 images(cn->image_count); std::vector memory(cn->image_count); std::vector views(cn->image_count); - for (size_t j = 0; j < cn->image_count; j++) { + 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()); + 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) { + for (auto & [group, params]: thread_params) + { auto params_ptr = new encoder_thread_param(params); - auto &thread = cn->encoder_threads.emplace_back(); + auto & thread = cn->encoder_threads.emplace_back(); thread.index = cn->encoder_threads.size() - 1; params_ptr->thread = &thread; params_ptr->cn = cn; @@ -177,8 +189,8 @@ class drm_image_modifier_helper std::vector modifiers; public: - void *pNext = nullptr; - drm_image_modifier_helper(vk_bundle *vk, VkFormat format, VkImageTiling tiling) + void * pNext = nullptr; + drm_image_modifier_helper(vk_bundle * vk, VkFormat format, VkImageTiling tiling) { if (tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT) return; @@ -197,11 +209,11 @@ public: 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) { + for (const auto & mod: properties) + { if ((mod.drmFormatModifierTilingFeatures & required_features) == required_features) modifiers.push_back(mod.drmFormatModifier); } @@ -216,11 +228,9 @@ public: } }; - -static VkResult -create_images(struct wivrn_comp_target *cn, VkImageUsageFlags flags, VkImageTiling tiling) +static VkResult create_images(struct wivrn_comp_target * cn, VkImageUsageFlags flags, VkImageTiling tiling) { - struct vk_bundle *vk = get_vk(cn); + struct vk_bundle * vk = get_vk(cn); assert(cn->image_count > 0); COMP_DEBUG(cn->c, "Creating %d images.", cn->image_count); @@ -241,10 +251,11 @@ create_images(struct wivrn_comp_target *cn, VkImageUsageFlags flags, VkImageTili 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; + 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}; @@ -272,17 +283,16 @@ create_images(struct wivrn_comp_target *cn, VkImageUsageFlags flags, VkImageTili 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); + 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 + 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{}; @@ -295,81 +305,79 @@ create_images(struct wivrn_comp_target *cn, VkImageUsageFlags flags, VkImageTili vk_check_error("vkCreateFence", res, res); } - return VK_SUCCESS; } -static bool -comp_wivrn_init_pre_vulkan(struct comp_target *ct) +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) +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) +static bool comp_wivrn_check_ready(struct comp_target * ct) { return true; } -static void -target_fini_semaphores(struct wivrn_comp_target *cn) +static void target_fini_semaphores(struct wivrn_comp_target * cn) { - struct vk_bundle *vk = get_vk(cn); + struct vk_bundle * vk = get_vk(cn); - if (cn->semaphores.present_complete != VK_NULL_HANDLE) { + 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) { + 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) +static void target_init_semaphores(struct wivrn_comp_target * cn) { - struct vk_bundle *vk = get_vk(cn); + struct vk_bundle * vk = get_vk(cn); VkResult ret; target_fini_semaphores(cn); VkSemaphoreCreateInfo info = { - .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, }; ret = vk->vkCreateSemaphore(vk->device, &info, NULL, &cn->semaphores.present_complete); - if (ret != VK_SUCCESS) { + 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) { + 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) +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; + struct wivrn_comp_target * cn = (struct wivrn_comp_target *)ct; uint64_t now_ns = os_monotonic_get_ns(); - if (cn->upc == NULL) { + if (cn->upc == NULL) + { u_pc_fake_create(ct->c->settings.nominal_frame_interval_ns, now_ns, &cn->upc); } @@ -392,30 +400,32 @@ comp_wivrn_create_images(struct comp_target *ct, 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__)) { + if (vk_has_error(res, "create_images", __FILE__, __LINE__)) + { // TODO abort(); } - try { + try + { create_encoders(cn, settings); - } catch (const std::exception &e) { + } + 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) +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) +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); + 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; @@ -433,10 +443,13 @@ comp_wivrn_acquire(struct comp_target *ct, uint32_t *out_index) res = VK_ERROR_OUT_OF_HOST_MEMORY; - while (res != VK_SUCCESS) { + 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) { + 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; @@ -449,19 +462,19 @@ comp_wivrn_acquire(struct comp_target *ct, uint32_t *out_index) return res; } -static void * -comp_wivrn_present_thread(void *void_param) +static void * comp_wivrn_present_thread(void * void_param) { std::unique_ptr param((encoder_thread_param *)void_param); - struct wivrn_comp_target *cn = param->cn; - struct vk_bundle *vk = get_vk(cn); + 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 fences(cn->image_count); std::vector indices(cn->image_count); - while (os_thread_helper_is_running(¶m->thread->thread)) { + while (os_thread_helper_is_running(¶m->thread->thread)) + { int presenting_index = -1; int nb_fences = 0; { @@ -469,9 +482,12 @@ comp_wivrn_present_thread(void *void_param) 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) { + 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; @@ -479,7 +495,8 @@ comp_wivrn_present_thread(void *void_param) } } - if (presenting_index < 0) { + 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)); @@ -490,21 +507,24 @@ comp_wivrn_present_thread(void *void_param) 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) { + 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); + encoder->Encode(*cn->cnx, psc_image.view_info, psc_image.frame_index, presenting_index, idr_requested); } } - catch(...) { + catch (...) + { // Ignore errors } std::lock_guard lock(cn->psc.mutex); - for (int i = 0; i < nb_fences; i++) { + for (int i = 0; i < nb_fences; i++) + { cn->psc.images[indices[i]].status &= ~status_bit; } } @@ -512,20 +532,20 @@ comp_wivrn_present_thread(void *void_param) 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) +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); + 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) { + 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; @@ -547,15 +567,14 @@ comp_wivrn_present(struct comp_target *ct, 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); + 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) { + for (auto & encoder: cn->encoders) + { VkCommandBuffer cmdBuffer = VK_NULL_HANDLE; encoder->PresentImage(index, &cmdBuffer); if (cmdBuffer != VK_NULL_HANDLE) @@ -586,9 +605,10 @@ comp_wivrn_present(struct comp_target *ct, 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; + 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) { + 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]); @@ -602,21 +622,19 @@ comp_wivrn_present(struct comp_target *ct, return VK_SUCCESS; } -static void -comp_wivrn_flush(struct comp_target *ct) +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) +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; + 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*/; @@ -650,76 +668,68 @@ comp_wivrn_calc_frame_pacing(struct comp_target *ct, *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) +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; + 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); + 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) +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_set_title(struct comp_target * ct, const char * title) {} -static void -comp_wivrn_destroy(struct comp_target *ct) +static void comp_wivrn_destroy(struct comp_target * ct) { - struct wivrn_comp_target *cn = (struct wivrn_comp_target *)ct; + struct wivrn_comp_target * cn = (struct wivrn_comp_target *)ct; - vk_bundle *vk = get_vk(cn); + 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) +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; + 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 cnx, float fps) +comp_target * comp_target_wivrn_create(std::shared_ptr cnx, float fps) { - wivrn_comp_target *cn = new wivrn_comp_target{}; + wivrn_comp_target * cn = new wivrn_comp_target{}; cn->cnx = cnx; cn->check_ready = comp_wivrn_check_ready; diff --git a/server/driver/wivrn_comp_target.h b/server/driver/wivrn_comp_target.h index 4992de9d..81655189 100644 --- a/server/driver/wivrn_comp_target.h +++ b/server/driver/wivrn_comp_target.h @@ -1,11 +1,25 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once #include "main/comp_target.h" #include "wivrn_session.h" -comp_target * -comp_target_wivrn_create(std::shared_ptr cnx, float fps); +comp_target * comp_target_wivrn_create(std::shared_ptr cnx, float fps); diff --git a/server/driver/wivrn_connection.cpp b/server/driver/wivrn_connection.cpp index 2a35e644..1ff1c0ee 100644 --- a/server/driver/wivrn_connection.cpp +++ b/server/driver/wivrn_connection.cpp @@ -1,32 +1,45 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "wivrn_connection.h" #include using namespace std::chrono_literals; -wivrn_connection::wivrn_connection(TCP&& tcp, in6_addr address) : control(std::move(tcp)) +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) +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) +void wivrn_connection::send_stream(const to_headset::stream_packets & packet) { stream.send(packet); } -std::optional -wivrn_connection::poll_stream(int timeout) +std::optional wivrn_connection::poll_stream(int timeout) { pollfd fds{}; fds.events = POLLIN; @@ -36,15 +49,15 @@ wivrn_connection::poll_stream(int timeout) if (r < 0) throw std::system_error(errno, std::system_category()); - if (r > 0 && (fds.revents & POLLIN)) { + if (r > 0 && (fds.revents & POLLIN)) + { return stream.receive(); } return {}; } -std::optional -wivrn_connection::poll_control(int timeout) +std::optional wivrn_connection::poll_control(int timeout) { pollfd fds{}; fds.events = POLLIN; @@ -54,7 +67,8 @@ wivrn_connection::poll_control(int timeout) if (r < 0) throw std::system_error(errno, std::system_category()); - if (r > 0 && (fds.revents & POLLIN)) { + if (r > 0 && (fds.revents & POLLIN)) + { return control.receive(); } diff --git a/server/driver/wivrn_connection.h b/server/driver/wivrn_connection.h index b59b4240..c0b0e9cc 100644 --- a/server/driver/wivrn_connection.h +++ b/server/driver/wivrn_connection.h @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -17,24 +32,18 @@ class wivrn_connection typed_socket stream; public: - wivrn_connection(TCP &&tcp, in6_addr address); + wivrn_connection(TCP && tcp, in6_addr address); wivrn_connection(const wivrn_connection &) = delete; - wivrn_connection & - operator=(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); + void send_control(const to_headset::control_packets & packet); + void send_stream(const to_headset::stream_packets & packet); - std::optional - poll_stream(int timeout); - std::optional - poll_control(int timeout); + std::optional poll_stream(int timeout); + std::optional poll_control(int timeout); template - int - poll(T &&visitor, int timeout) + int poll(T && visitor, int timeout) { pollfd fds[2] = {}; fds[0].events = POLLIN; @@ -52,13 +61,15 @@ public: if (fds[1].revents & (POLLHUP | POLLERR)) throw std::runtime_error("Error on control socket"); - if (fds[0].revents & POLLIN) { + if (fds[0].revents & POLLIN) + { auto packet = stream.receive(); if (packet) std::visit(std::forward(visitor), std::move(*packet)); } - if (fds[1].revents & POLLIN) { + if (fds[1].revents & POLLIN) + { auto packet = control.receive(); if (packet) std::visit(std::forward(visitor), std::move(*packet)); diff --git a/server/driver/wivrn_controller.cpp b/server/driver/wivrn_controller.cpp index 6bd2fb23..3a898fe7 100644 --- a/server/driver/wivrn_controller.cpp +++ b/server/driver/wivrn_controller.cpp @@ -1,12 +1,27 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "wivrn_controller.h" -#include "util/u_logging.h" #include "os/os_threading.h" #include "util/u_device.h" +#include "util/u_logging.h" #include #include "xrt/xrt_defines.h" @@ -94,31 +109,23 @@ static const wivrn_to_wivrn_controller_input right_hand_bindings[] = { 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_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_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); +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 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 * hmd, + std::shared_ptr 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; + xrt_device * base = this; base->destroy = wivrn_controller_destroy; base->get_tracked_pose = wivrn_controller_get_tracked_pose; @@ -138,10 +145,11 @@ wivrn_controller::wivrn_controller(int hand_id, 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; \ +#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); @@ -164,108 +172,128 @@ wivrn_controller::wivrn_controller(int hand_id, inputs_staging = inputs_array; - switch (hand_id) { - case 0: - device_type = XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER; - SET_INPUT(MENU_CLICK); + 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"); + // Print name. + strcpy(str, "WiVRn HMD left hand controller"); + strcpy(serial, "WiVRn HMD left hand controller"); - break; + break; - case 1: - device_type = XRT_DEVICE_TYPE_RIGHT_HAND_CONTROLLER; + 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"); + // Print name. + strcpy(str, "WiVRn HMD right hand controller"); + strcpy(serial, "WiVRn HMD right hand controller"); - break; + break; - default: throw std::runtime_error("Invalid hand ID"); + default: + throw std::runtime_error("Invalid hand ID"); } } -void -wivrn_controller::update_inputs() +void wivrn_controller::update_inputs() { std::lock_guard _{mutex}; inputs_array = inputs_staging; } -void -wivrn_controller::set_inputs(const from_headset::inputs &inputs) + +void wivrn_controller::set_inputs(const from_headset::inputs & inputs) { std::lock_guard lock{mutex}; - for (const auto &input : inputs.values) { + for (const auto & input: inputs.values) + { set_inputs(input.id, input.value); } } -void -wivrn_controller::set_inputs(device_id input_id, float value) +void wivrn_controller::set_inputs(device_id input_id, float value) { - const struct wivrn_to_wivrn_controller_input *bindings; + const struct wivrn_to_wivrn_controller_input * bindings; size_t bindings_count; - if (device_type == XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER) { + if (device_type == XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER) + { bindings = left_hand_bindings; bindings_count = left_hand_bindings_count; - } else { + } + 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) { + 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; + 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) +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); + 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); + case XRT_INPUT_TOUCH_GRIP_POSE: + return grip.get_at(at_timestamp_ns); - default: U_LOG_W("Unknown input name requested"); return {}; + default: + U_LOG_W("Unknown input name requested"); + return {}; } } -void -wivrn_controller::update_tracking(const from_headset::tracking &tracking, const clock_offset &offset) +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) +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 - - }); + try + { + cnx->send_stream(to_headset::haptics{ + .id = id, + .duration = std::chrono::nanoseconds(value->vibration.duration_ns), + .frequency = value->vibration.frequency, + .amplitude = value->vibration.amplitude}); } - catch(...) + catch (...) { // Ignore errors } @@ -277,29 +305,25 @@ wivrn_controller::set_output(xrt_output_name name, const xrt_output_value *value * */ -static void -wivrn_controller_destroy(xrt_device *xdev) +static void wivrn_controller_destroy(xrt_device * xdev) { delete (wivrn_controller *)xdev; } -static void -wivrn_controller_update_inputs(xrt_device *xdev) +static void wivrn_controller_update_inputs(xrt_device * xdev) { static_cast(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) +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(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 void wivrn_controller_set_output(struct xrt_device * xdev, enum xrt_output_name name, const union xrt_output_value * value) { static_cast(xdev)->set_output(name, value); } diff --git a/server/driver/wivrn_controller.h b/server/driver/wivrn_controller.h index 0a177007..190e2949 100644 --- a/server/driver/wivrn_controller.h +++ b/server/driver/wivrn_controller.h @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -9,9 +24,9 @@ #include "pose_list.h" #include "wivrn_session.h" +#include #include #include -#include class wivrn_controller : public xrt_device { @@ -27,27 +42,21 @@ class wivrn_controller : public xrt_device std::shared_ptr cnx; public: - wivrn_controller(int hand_id, xrt_device *hmd, std::shared_ptr cnx); + wivrn_controller(int hand_id, xrt_device * hmd, std::shared_ptr cnx); - void - unregister() + void unregister() { cnx = nullptr; } - void - update_inputs(); + void update_inputs(); - xrt_space_relation - get_tracked_pose(xrt_input_name name, uint64_t at_timestamp_ns); + 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_output(xrt_output_name name, const xrt_output_value * value); - void - set_inputs(const from_headset::inputs &); + void set_inputs(const from_headset::inputs &); - void - update_tracking(const from_headset::tracking &, const clock_offset &); + void update_tracking(const from_headset::tracking &, const clock_offset &); private: void diff --git a/server/driver/wivrn_hmd.cpp b/server/driver/wivrn_hmd.cpp index 5d29e24d..c696b40f 100644 --- a/server/driver/wivrn_hmd.cpp +++ b/server/driver/wivrn_hmd.cpp @@ -1,14 +1,20 @@ -// 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 - * @ingroup drv_wivrn +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ #include "wivrn_hmd.h" @@ -21,17 +27,17 @@ #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 "util/u_logging.h" +#include "util/u_misc.h" +#include "util/u_time.h" +#include "util/u_var.h" -#include -#include #include +#include +#include #include "wivrn_comp_target.h" @@ -41,54 +47,44 @@ * */ - - /*! * A wivrn HMD device. * * @implements xrt_device */ - /* * * Functions * */ +static void wivrn_hmd_destroy(xrt_device * xdev); -static void -wivrn_hmd_destroy(xrt_device *xdev); +static void wivrn_hmd_update_inputs(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_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); +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 cnx, - const from_headset::headset_info_packet &info) - : xrt_device{}, cnx(cnx) + const from_headset::headset_info_packet & info) : + xrt_device{}, cnx(cnx) { - xrt_device *base = this; + xrt_device * base = this; base->hmd = &hmd_parts; base->tracking_origin = &tracking_origin; @@ -163,17 +159,15 @@ wivrn_hmd::wivrn_hmd(std::shared_ptr cnx, u_distortion_mesh_set_none(this); } -void -wivrn_hmd::update_inputs() +void wivrn_hmd::update_inputs() { // Empty } - -xrt_space_relation -wivrn_hmd::get_tracked_pose(xrt_input_name name, uint64_t at_timestamp_ns) +xrt_space_relation wivrn_hmd::get_tracked_pose(xrt_input_name name, uint64_t at_timestamp_ns) { - if (name != XRT_INPUT_GENERIC_HEAD_POSE) { + if (name != XRT_INPUT_GENERIC_HEAD_POSE) + { U_LOG_E("Unknown input name"); return {}; } @@ -181,19 +175,17 @@ wivrn_hmd::get_tracked_pose(xrt_input_name name, uint64_t at_timestamp_ns) return views.get_at(at_timestamp_ns).relation; } -void -wivrn_hmd::update_tracking(const from_headset::tracking &tracking, const clock_offset &offset) +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) +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); @@ -215,67 +207,59 @@ wivrn_hmd::get_view_poses(const xrt_vec3 *default_eye_relation, *out_head_relation = view.relation; assert(view_count == 2); - for (size_t eye = 0; eye < 2; ++eye) { + 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 * wivrn_hmd::create_compositor_target(struct comp_compositor * comp) { - comp_target *target = comp_target_wivrn_create(cnx, fps); + comp_target * target = comp_target_wivrn_create(cnx, fps); target->c = comp; return target; } - - /* * * Functions * */ -static void -wivrn_hmd_destroy(xrt_device *xdev) +static void wivrn_hmd_destroy(xrt_device * xdev) { static_cast(xdev)->unregister(); } -static void -wivrn_hmd_update_inputs(xrt_device *xdev) +static void wivrn_hmd_update_inputs(xrt_device * xdev) { static_cast(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) +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(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 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(xdev)->get_view_poses(default_eye_relation, at_timestamp_ns, view_count, - out_head_relation, out_fovs, out_poses); + static_cast(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) +static void wivrn_hmd_create_compositor_target(struct xrt_device * xdev, + struct comp_compositor * comp, + struct comp_target ** out_target) { *out_target = static_cast(xdev)->create_compositor_target(comp); } diff --git a/server/driver/wivrn_hmd.h b/server/driver/wivrn_hmd.h index 11d61a1c..66024f55 100644 --- a/server/driver/wivrn_hmd.h +++ b/server/driver/wivrn_hmd.h @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -10,8 +25,8 @@ #include "view_list.h" #include "wivrn_session.h" -#include #include +#include class wivrn_hmd : public xrt_device { @@ -29,27 +44,21 @@ class wivrn_hmd : public xrt_device public: wivrn_hmd(std::shared_ptr cnx, - const from_headset::headset_info_packet &info); - void - unregister() + 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_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 &); + void update_tracking(const from_headset::tracking &, const clock_offset &); }; diff --git a/server/driver/wivrn_packets.h b/server/driver/wivrn_packets.h deleted file mode 100644 index 4de3fa0e..00000000 --- a/server/driver/wivrn_packets.h +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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 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 views; - std::vector device_poses; - }; - - struct inputs - { - struct input_value - { - device_id id; - float value; - }; - std::vector 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 received_pose; - std::array 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; - using stream_packets = std::variant; -} // 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 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 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 pose; - std::array fov; - }; - std::optional 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 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; - using control_packets = std::variant; - -} // namespace to_headset - -} // namespace xrt::drivers::wivrn diff --git a/server/driver/wivrn_serialization.h b/server/driver/wivrn_serialization.h deleted file mode 100644 index 503883c1..00000000 --- a/server/driver/wivrn_serialization.h +++ /dev/null @@ -1,522 +0,0 @@ -// 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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(-n)); - } else { - feed_unsigned(static_cast(n)); - } - - return hash; - } - }; -} // namespace details - -template struct serialization_traits; - -class deserialization_error : public std::runtime_error -{ -public: - deserialization_error() : std::runtime_error("Deserialization error") {} -}; - -class serialization_packet -{ - std::vector 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 - void - serialize(const T &value) - { - serialization_traits::serialize(value, *this); - } - - operator std::vector &&() && - { - return std::move(buffer); - } -}; - -class deserialization_packet -{ - std::vector buffer; - size_t read_index; - -public: - deserialization_packet() : read_index(0) {} - explicit deserialization_packet(std::vector 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 - T - deserialize() - { - return serialization_traits::deserialize(*this); - } -}; - -template struct serialization_traits>> -{ - static constexpr void - type_hash(details::hash_context &h) - { - if constexpr (std::is_floating_point_v) - h.feed("float"); - else if constexpr (std::is_integral_v) { - if constexpr (std::is_unsigned_v) - 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 struct serialization_traits>> -{ - 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 struct is_stdarray : public std::false_type -{ -}; - -template struct is_stdarray> : public std::true_type -{ -}; - -template inline constexpr bool is_stdarray_v = is_stdarray::value; - -template struct serialization_traits && !is_stdarray_v>> -{ - template - static constexpr void - aux2(details::hash_context &h) - { - if constexpr (I > 0) - h.feed(","); - serialization_traits>::type_hash(h); - } - - template - static constexpr void - aux1(details::hash_context &h, std::index_sequence) - { - (aux2(h), ...); - } - - static constexpr void - type_hash(details::hash_context &h) - { - h.feed("structure{"); - aux1(h, std::make_index_sequence>()); - 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>(); }); - - return value; - } -}; - -template <> struct serialization_traits -{ - static constexpr void - type_hash(details::hash_context &h) - { - h.feed("string"); - } - - static void - serialize(const std::string &value, serialization_packet &packet) - { - packet.serialize(value.size()); - packet.write(value.data(), value.size()); - } - - static std::string - deserialize(deserialization_packet &packet) - { - std::string value; - size_t size = packet.deserialize(); - - packet.check_remaining_size(size); - - value.resize(size); - packet.read(value.data(), size); - return value; - } -}; - -template struct serialization_traits> -{ - static constexpr void - type_hash(details::hash_context &h) - { - h.feed("vector<"); - serialization_traits::type_hash(h); - h.feed(">"); - } - - static void - serialize(const std::vector &value, serialization_packet &packet) - { - packet.serialize(value.size()); - - for (const T &i : value) - packet.serialize(i); - } - - static std::vector - deserialize(deserialization_packet &packet) - { - std::vector value; - size_t size = packet.deserialize(); - - packet.check_remaining_size(size); - - value.reserve(size); - for (size_t i = 0; i < size; i++) { - value.emplace_back(packet.deserialize()); - } - - return value; - } -}; - -template struct serialization_traits> -{ - static constexpr void - type_hash(details::hash_context &h) - { - h.feed("optional<"); - serialization_traits::type_hash(h); - h.feed(">"); - } - - static void - serialize(const std::optional &value, serialization_packet &packet) - { - if (value) { - packet.serialize(true); - packet.serialize(*value); - } else { - packet.serialize(false); - } - } - - static std::optional - deserialize(deserialization_packet &packet) - { - if (packet.deserialize()) - return packet.deserialize(); - else - return std::nullopt; - } -}; - -template struct serialization_traits> -{ - static constexpr void - type_hash(details::hash_context &h) - { - h.feed("array<"); - serialization_traits::type_hash(h); - h.feed(","); - h.feed(N); - h.feed(">"); - } - - static void - serialize(const std::array &value, serialization_packet &packet) - { - for (const T &i : value) - packet.serialize(i); - } - - static std::array - deserialize(deserialization_packet &packet) - { - std::array value; - - for (size_t i = 0; i < N; i++) { - value[i] = packet.deserialize(); - } - - return value; - } -}; - -template struct serialization_traits> -{ - template - static constexpr void - type_list_hash(details::hash_context &h) - { - serialization_traits::type_hash(h); - - if constexpr (sizeof...(V) > 0) { - h.feed(","); - type_list_hash(h); - } - } - - static constexpr void - type_hash(details::hash_context &h) - { - h.feed("variant<"); - type_list_hash(h); - h.feed(">"); - } - - static void - serialize(const std::variant &value, serialization_packet &packet) - { - packet.serialize(value.index()); - std::visit([&](const auto &x) { packet.serialize(x); }, value); - } - - template using i_th_type = std::tuple_element_t>; - - template - static std::variant - deserialize_aux(deserialization_packet &packet, size_t type_index, std::index_sequence) - { - std::variant value; - ((I == type_index ? (void)(value = packet.deserialize>()) : (void)0), ...); - return value; - } - - static std::variant - deserialize(deserialization_packet &packet) - { - uint32_t type_index = packet.deserialize(); - if (type_index >= sizeof...(T)) - throw deserialization_error(); - - return deserialize_aux(packet, type_index, std::make_index_sequence()); - } -}; - -template struct serialization_traits> -{ - static constexpr void - type_hash(details::hash_context &h) - { - h.feed("duration<"); - serialization_traits::type_hash(h); - h.feed(","); - h.feed(Period::num); - h.feed("/"); - h.feed(Period::den); - h.feed(">"); - } - - static void - serialize(const std::chrono::duration &value, serialization_packet &packet) - { - packet.serialize(value.count()); - } - - static std::chrono::duration - deserialize(deserialization_packet &packet) - { - Rep nsec = packet.deserialize(); - return std::chrono::duration{nsec}; - } -}; - -namespace unit_tests { - template - 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 - constexpr uint64_t - serialization_type_hash() - { - details::hash_context h; - serialization_traits::type_hash(h); - return h.hash; - } - - static_assert(serialization_type_hash() == hash("uint8")); - static_assert(serialization_type_hash() == hash("int32")); - static_assert(serialization_type_hash() == hash("float32")); - static_assert(serialization_type_hash() == hash("float64")); - static_assert(serialization_type_hash() == hash("duration")); - static_assert(serialization_type_hash>() == hash("optional")); - static_assert(serialization_type_hash>() == hash("vector")); - static_assert(serialization_type_hash>() == hash("array")); - static_assert(serialization_type_hash() == hash("string")); - static_assert(serialization_type_hash>() == hash("variant")); - - struct test - { - int x; - float y; - }; - static_assert(serialization_type_hash() == hash("structure{int32,float32}")); -} // namespace unit_tests - -} // namespace xrt::drivers::wivrn diff --git a/server/driver/wivrn_session.cpp b/server/driver/wivrn_session.cpp index 23fbd057..c2ed0e63 100644 --- a/server/driver/wivrn_session.cpp +++ b/server/driver/wivrn_session.cpp @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "wivrn_session.h" #include "os/os_time.h" @@ -9,16 +24,16 @@ #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::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) +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) + if (getpeername(tcp.get_fd(), (sockaddr *)&address, &address_len) < 0) { U_LOG_E("Cannot get peer address: %s", strerror(errno)); return nullptr; @@ -31,18 +46,21 @@ xrt::drivers::wivrn::wivrn_session::create_session(xrt::drivers::wivrn::TCP &&tc self = std::shared_ptr(new wivrn_session(std::move(tcp), address.sin6_addr)); control = self->connection.poll_control(-1); } - catch(std::exception& e) + catch (std::exception & e) { U_LOG_E("Error creating WiVRn session: %s", e.what()); return nullptr; } - if (control) { - const auto &info = std::get(*control); + if (control) + { + const auto & info = std::get(*control); self->hmd = std::make_unique(self, info); self->left_hand = std::make_unique(0, self->hmd.get(), self); self->right_hand = std::make_unique(1, self->hmd.get(), self); - } else { + } + else + { throw std::runtime_error("no packet received from headset, failed to initialise"); } @@ -57,7 +75,7 @@ xrt::drivers::wivrn::wivrn_session::create_session(xrt::drivers::wivrn::TCP &&tc devices->roles.right = devices->xdevs[n++] = self->right_hand.get(); devices->xdev_count = n; - devices->destroy = [](xrt_system_devices * xsd){ + devices->destroy = [](xrt_system_devices * xsd) { // TODO }; @@ -70,21 +88,17 @@ xrt::drivers::wivrn::wivrn_session::create_session(xrt::drivers::wivrn::TCP &&tc return devices; } - -clock_offset -wivrn_session::get_offset() +clock_offset wivrn_session::get_offset() { std::lock_guard lock(mutex); return offset; } -void -wivrn_session::operator()(from_headset::headset_info_packet &&) +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) +void wivrn_session::operator()(from_headset::tracking && tracking) { if (offset.epoch_offset.count() == 0) return; @@ -93,25 +107,24 @@ wivrn_session::operator()(from_headset::tracking &&tracking) left_hand->update_tracking(tracking, offset); right_hand->update_tracking(tracking, offset); } -void -wivrn_session::operator()(from_headset::inputs &&inputs) + +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) +void wivrn_session::operator()(from_headset::timesync_response && timesync) { 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) +void wivrn_session::operator()(from_headset::feedback && feedback) { - if (feedback_csv) { + 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 << "," @@ -142,38 +155,42 @@ wivrn_session::operator()(from_headset::feedback &&feedback) } } -uint64_t -clock_offset::from_headset(uint64_t ts) const +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 +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 weak_self) +void wivrn_session::run(std::weak_ptr weak_self) { - while (true) { - try { + while (true) + { + try + { auto self = weak_self.lock(); - if (self and not self->quit) { + 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)) { + 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 + } + else return; - } catch (const std::exception &e) { + } + catch (const std::exception & e) + { U_LOG_E("Exception in network thread: %s", e.what()); auto self = weak_self.lock(); if (self) diff --git a/server/driver/wivrn_session.h b/server/driver/wivrn_session.h index cc9b83a1..637ede46 100644 --- a/server/driver/wivrn_session.h +++ b/server/driver/wivrn_session.h @@ -1,22 +1,38 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once -#include "wivrn_packets.h" #include "wivrn_connection.h" +#include "wivrn_packets.h" #include "xrt/xrt_system.h" #include +#include #include #include #include -#include class wivrn_hmd; class wivrn_controller; -namespace xrt::drivers::wivrn { +namespace xrt::drivers::wivrn +{ struct clock_offset { @@ -45,36 +61,29 @@ class wivrn_session : public std::enable_shared_from_this std::ofstream feedback_csv; - wivrn_session(TCP&& tcp, in6_addr &address); + wivrn_session(TCP && tcp, in6_addr & address); public: static xrt_system_devices * - create_session(TCP&& tcp); + 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 &&); + 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 - void - send_stream(const T &packet) + void send_stream(const T & packet) { connection.send_stream(packet); } template - void - send_control(const T &packet) + void send_control(const T & packet) { connection.send_control(packet); } diff --git a/server/driver/wivrn_sockets.cpp b/server/driver/wivrn_sockets.cpp deleted file mode 100644 index 6eb4f50c..00000000 --- a/server/driver/wivrn_sockets.cpp +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 - -#include "wivrn_sockets.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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(); -} - -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::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 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 &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(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(buffer.data()); - if (buffer.size() < 4 + payload_size) - return {}; - - assert(buffer.size() == 4 + payload_size); - - std::vector 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 &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; - } -} diff --git a/server/driver/wivrn_sockets.h b/server/driver/wivrn_sockets.h deleted file mode 100644 index f6e8b899..00000000 --- a/server/driver/wivrn_sockets.h +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 - -#pragma once - -#include "wivrn_serialization.h" - -#include -#include -#include -#include -#include -#include - -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 struct index_of_type -{ -}; - -template struct index_of_type : std::integral_constant -{ -}; - -template -struct index_of_type : std::integral_constant::value> -{ -}; - -static_assert(index_of_type::value == 0); -static_assert(index_of_type::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 &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 buffer; - std::unique_ptr 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 &data); -}; - -class TCPListener : public socket_base -{ -public: - TCPListener(int port); - TCPListener(const TCPListener &) = delete; - TCPListener(TCPListener &&) = default; - - std::pair - accept(); -}; - -template class typed_socket : public Socket -{ -public: - template typed_socket(Args &&...args) : Socket(std::forward(args)...) {} - - std::optional - receive() - { - deserialization_packet packet = this->receive_raw(); - if (packet.empty()) - return {}; - - return packet.deserialize(); - } - - template >> - void - send(const T &data) - { - serialization_packet p; - p.serialize(data); - this->send_raw(std::move(p)); - } -}; - -} // namespace xrt::drivers::wivrn diff --git a/server/driver/xrt_cast.cpp b/server/driver/xrt_cast.cpp index 0d625e50..5de05dbd 100644 --- a/server/driver/xrt_cast.cpp +++ b/server/driver/xrt_cast.cpp @@ -1,14 +1,29 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "xrt_cast.h" #include -namespace { +namespace +{ template -Out -do_cast(const In &in) +Out do_cast(const In & in) { Out res; static_assert(sizeof(res) == sizeof(in)); @@ -17,10 +32,10 @@ do_cast(const In &in) } } // namespace -#define XRT_CAST(in_type, out_type) \ - out_type xrt_cast(const in_type &in) \ - { \ - return do_cast(in); \ +#define XRT_CAST(in_type, out_type) \ + out_type xrt_cast(const in_type & in) \ + { \ + return do_cast(in); \ } XRT_CAST(XrPosef, xrt_pose) diff --git a/server/driver/xrt_cast.h b/server/driver/xrt_cast.h index 16131afb..0f417ba5 100644 --- a/server/driver/xrt_cast.h +++ b/server/driver/xrt_cast.h @@ -1,22 +1,31 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once #include "xrt/xrt_defines.h" #include -xrt_pose -xrt_cast(const XrPosef &); -xrt_vec3 -xrt_cast(const XrVector3f &); -xrt_quat -xrt_cast(const XrQuaternionf &); -xrt_fov -xrt_cast(const XrFovf &); +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 &); +XrPosef xrt_cast(const xrt_pose &); +XrFovf xrt_cast(const xrt_fov &); diff --git a/server/driver/yuv_converter.cpp b/server/driver/yuv_converter.cpp index 25a24089..32c2b8b2 100644 --- a/server/driver/yuv_converter.cpp +++ b/server/driver/yuv_converter.cpp @@ -1,12 +1,27 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include "yuv_converter.h" #include +#include #include #include -#include #include #include @@ -15,38 +30,36 @@ extern const std::map> 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) +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; + 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) +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); + 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)) { + 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; @@ -59,8 +72,7 @@ create_image(vk_bundle &vk, VkExtent2D extent, VkFormat format, YuvConverter::im return VK_SUCCESS; } -static VkResult -shader_load(struct vk_bundle *vk, const std::vector &code, VkShaderModule *out_module) +static VkResult shader_load(struct vk_bundle * vk, const std::vector & code, VkShaderModule * out_module) { VkResult ret; @@ -74,7 +86,8 @@ shader_load(struct vk_bundle *vk, const std::vector &code, VkShaderMod &info, // NULL, // &module); // - if (ret != VK_SUCCESS) { + if (ret != VK_SUCCESS) + { VK_ERROR(vk, "vkCreateShaderModule failed: %s", vk_result_string(ret)); return ret; } @@ -84,14 +97,13 @@ shader_load(struct vk_bundle *vk, const std::vector &code, VkShaderMod return VK_SUCCESS; } - -static void -destroy_all(YuvConverter *ptr) +static void destroy_all(YuvConverter * ptr) { - auto &vk = ptr->vk; + 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}) { + 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); @@ -109,15 +121,15 @@ destroy_all(YuvConverter *ptr) 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"); \ +#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) +YuvConverter::YuvConverter(vk_bundle * vk, VkExtent3D extent, int offset_x, int offset_y, int input_width, int input_height) : + vk(*vk) { std::unique_ptr deleter(this, destroy_all); @@ -161,13 +173,14 @@ YuvConverter::YuvConverter( 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); + shader_load(vk, shaders.at("yuv_converter.uv.frag"), &uv.frag); vk_check_throw("shader_load", res); - for (int i = 0; i < 2; ++i) { + for (int i = 0; i < 2; ++i) + { VkAttachmentDescription colorAttachment{}; VkAttachmentReference colorAttachmentRef{}; - auto &comp = (i == 0) ? y : uv; + 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; @@ -285,8 +298,7 @@ YuvConverter::YuvConverter( pipelineInfo.renderPass = comp.render_pass; pipelineInfo.subpass = 0; - res = vk->vkCreateGraphicsPipelines(vk->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, - &comp.pipeline); + res = vk->vkCreateGraphicsPipelines(vk->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &comp.pipeline); vk_check_throw("vkCreateGraphicsPipelines", res); } @@ -306,8 +318,7 @@ YuvConverter::~YuvConverter() destroy_all(this); } -void -YuvConverter::SetImages(int num_images, VkImage *images, VkImageView *views) +void YuvConverter::SetImages(int num_images, VkImage * images, VkImageView * views) { // os_mutex_lock(&vk.cmd_pool_mutex); assert(command_buffers.empty()); @@ -324,9 +335,10 @@ YuvConverter::SetImages(int num_images, VkImage *images, VkImageView *views) 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]; + 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; @@ -356,7 +368,8 @@ YuvConverter::SetImages(int num_images, VkImage *images, VkImageView *views) res = vk_cmd_buffer_create_and_begin(&vk, &cmdBuffer); vk_check_throw("vk_cmd_buffer_create_and_begin", res); - for (auto &comp : {y, uv}) { + 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; @@ -365,12 +378,12 @@ YuvConverter::SetImages(int num_images, VkImage *images, VkImageView *views) 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.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) { + if (comp.buffer != VK_NULL_HANDLE) + { VkBufferImageCopy copy{}; copy.bufferOffset = 0; copy.bufferRowLength = 0; @@ -382,8 +395,7 @@ YuvConverter::SetImages(int num_images, VkImage *images, VkImageView *views) 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, ©); + vk.vkCmdCopyImageToBuffer(cmdBuffer, comp.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, comp.buffer, 1, ©); } } diff --git a/server/driver/yuv_converter.h b/server/driver/yuv_converter.h index e7743058..7a6ee460 100644 --- a/server/driver/yuv_converter.h +++ b/server/driver/yuv_converter.h @@ -1,6 +1,21 @@ -// Copyright 2022, Guillaume Meunier -// Copyright 2022, Patrick Nicolas -// SPDX-License-Identifier: BSL-1.0 +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -18,7 +33,7 @@ public: VkImageView view = VK_NULL_HANDLE; VkDeviceMemory buffer_memory = VK_NULL_HANDLE; VkBuffer buffer = VK_NULL_HANDLE; - void *mapped_memory = nullptr; + void * mapped_memory = nullptr; VkRenderPass render_pass = VK_NULL_HANDLE; VkFramebuffer frame_buffer = VK_NULL_HANDLE; VkShaderModule frag = VK_NULL_HANDLE; @@ -26,7 +41,7 @@ public: VkExtent2D extent; int stride; }; - vk_bundle &vk; + vk_bundle & vk; image_bundle y; image_bundle uv; VkSampler sampler = VK_NULL_HANDLE; @@ -40,9 +55,8 @@ public: std::vector command_buffers; std::vector descriptor_sets; - YuvConverter(vk_bundle *vk, VkExtent3D extent, int offset_x, int offset_y, int input_width, int input_height); + 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); + void SetImages(int num_images, VkImage * images, VkImageView * views); }; diff --git a/server/hostname.cpp b/server/hostname.cpp index 5576e9a1..64393ac1 100644 --- a/server/hostname.cpp +++ b/server/hostname.cpp @@ -2,14 +2,13 @@ #include -std::string -hostname() +std::string hostname() { sd_bus * bus; if (sd_bus_default_system(&bus) < 0) return ""; - for(auto property: {"PrettyHostname", "StaticHostname", "Hostname"}) + for (auto property: {"PrettyHostname", "StaticHostname", "Hostname"}) { char * hostname = nullptr; sd_bus_error error = SD_BUS_ERROR_NULL; diff --git a/server/main.cpp b/server/main.cpp index 17475cd7..1c0727ba 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -10,12 +10,12 @@ #include "util/u_trace_marker.h" -#include "driver/wivrn_sockets.h" -#include "driver/wivrn_packets.h" -#include -#include -#include +#include "wivrn_packets.h" +#include "wivrn_sockets.h" #include +#include +#include +#include #include "avahi_publisher.h" #include "hostname.h" @@ -23,53 +23,53 @@ // 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) +extern "C" { - return 0; -} + int + ipc_server_main(int argc, char * argv[]); -int -oxr_sdl2_hack_start(void *hack, struct xrt_instance *xinst, struct xrt_system_devices *xsysd) -{ - return 0; -} + int + oxr_sdl2_hack_create(void ** out_hack) + { + return 0; + } -int -oxr_sdl2_hack_stop(void **hack_ptr) -{ - 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; -void -avahi_callback(AvahiWatch *w, int fd, AvahiWatchEvent event, void *userdata) +void avahi_callback(AvahiWatch * w, int fd, AvahiWatchEvent event, void * userdata) { - bool *client_connected = (bool*)userdata; + bool * client_connected = (bool *)userdata; *client_connected = true; } -int -main(int argc, char *argv[]) +int main(int argc, char * argv[]) { u_trace_marker_init(); - while (true) { + 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); + AvahiWatch * watch = publisher.watch_new(listener.get_fd(), AVAHI_WATCH_IN, &avahi_callback, &client_connected); while (publisher.iterate() && !client_connected) ; @@ -81,13 +81,17 @@ main(int argc, char *argv[]) pid_t child = fork(); - if (child < 0) { + if (child < 0) + { perror("fork"); return 1; } - if (child == 0) { + if (child == 0) + { return ipc_server_main(argc, argv); - } else { + } + else + { std::cerr << "Server started, PID " << child << std::endl; int wstatus = 0; diff --git a/server/target_instance_wivrn.cpp b/server/target_instance_wivrn.cpp index 5acfdd60..3fd8a7b8 100644 --- a/server/target_instance_wivrn.cpp +++ b/server/target_instance_wivrn.cpp @@ -6,15 +6,15 @@ * @author Jakob Bornecrantz */ +#include "xrt/xrt_config_build.h" #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 "util/u_trace_marker.h" #include @@ -29,16 +29,16 @@ extern std::unique_ptr 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) +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)); + 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) @@ -46,14 +46,15 @@ wivrn_instance_create_system(struct xrt_instance *xinst, xrt_result_t xret = XRT_SUCCESS; + struct xrt_device * head = xsysd->roles.head; - struct xrt_device *head = xsysd->roles.head; - - if (xret == XRT_SUCCESS && xsysc == NULL) { + if (xret == XRT_SUCCESS && xsysc == NULL) + { xret = xrt_gfx_provider_create_system(head, &xsysc); } - if (xret != XRT_SUCCESS) { + if (xret != XRT_SUCCESS) + { xrt_system_devices_destroy(&xsysd); return xret; } @@ -65,13 +66,13 @@ wivrn_instance_create_system(struct xrt_instance *xinst, } static void -wivrn_instance_destroy(struct xrt_instance *xinst) +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) +wivrn_instance_get_prober(struct xrt_instance * xinst, struct xrt_prober ** out_xp) { *out_xp = nullptr; return XRT_ERROR_PROBER_NOT_SUPPORTED; @@ -84,11 +85,11 @@ wivrn_instance_get_prober(struct xrt_instance *xinst, struct xrt_prober **out_xp */ xrt_result_t -xrt_instance_create(struct xrt_instance_info *ii, struct xrt_instance **out_xinst) +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); + 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;