diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index b9417e68..5c847e25 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -36,17 +36,33 @@ body: validations: required: true + - type: input + attributes: + label: Installation method + description: Describe how WiVRn and OpenComposite/xrizer were installed + placeholder: flatpak --user, flatpak, AUR, Gentoo/Guru, built from sources... + - type: textarea attributes: label: Server Config - description: Provide the content of `config.json` for the server. - placeholder: Add the content of config.json here... + description: | + Provide the content of `config.json` for the server. + Located in `${XDG_CONFIG_HOME-${HOME}/.config}/wivrn/config.json` + or `~/.var/app/io.github.wivrn.wivrn/config/wivrn/config.json` for the flatpak version + placeholder: | + { + "encoders": [ + {"codec": "h264"} + ] + } - type: textarea attributes: label: Server Logs description: Provide the `wivrn-server` output. - placeholder: Add the output of the wivrn-server here... + placeholder: | + Add the output of the wivrn-server here. + If more than a few lines, prefer file attachment. - type: dropdown id: gpu @@ -64,7 +80,8 @@ body: attributes: label: Vulkan Info description: Provide the output of `vulkaninfo --summary` command. - placeholder: Add the output of vulkaninfo command here... + render: text + placeholder: Attach the output as a file here. - type: dropdown id: hmd @@ -90,4 +107,5 @@ body: attributes: label: ADB Logs description: Provide the output of `adb logcat` command. - placeholder: Add the output of adb logcat command here... + render: plain + placeholder: Attach the output of adb logcat as a file. diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index cbc1e2af..c57d944f 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -78,7 +78,7 @@ jobs: build-dashboard: name: Linux dashboard runs-on: ubuntu-24.04 - container: ubuntu:oracular + container: ubuntu:plucky if: ${{ vars.APK_ONLY == '' }} steps: - uses: actions/checkout@v4 @@ -459,7 +459,7 @@ jobs: strategy: fail-fast: false matrix: - distro: ['oracular', 'plucky'] + distro: ['plucky'] runs-on: ubuntu-24.04 container: ubuntu:${{ matrix.distro }} steps: diff --git a/CMakeLists.txt b/CMakeLists.txt index fa271ff3..01c4980b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,6 +6,7 @@ set(CMAKE_POLICY_DEFAULT_CMP0069 NEW) set(CMAKE_POLICY_DEFAULT_CMP0077 NEW) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_STANDARD 23) set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) @@ -33,6 +34,7 @@ option(WIVRN_BUILD_WIVRNCTL "Build wivrnctl" ON) option(WIVRN_BUILD_DISSECTOR "Build Wireshark dissector" OFF) option(WIVRN_BUILD_TEST "Build test binaries" OFF) option(WIVRN_WERROR "Treat warnings as errors" OFF) +option(WIVRN_OPTIMIZE_SHADERS "Run siprv-opt on compiled shaders" ON) option(WIVRN_USE_NVENC "Enable nvenc (Nvidia) hardware encoder" ON) auto_option(WIVRN_USE_VAAPI "Enable vaapi (AMD/Intel) hardware encoder" AUTO) @@ -276,9 +278,8 @@ FetchContent_Declare(spdlog EXCLUDE_FROM_ALL SYSTEM URL https://github.co URL_HASH SHA256=1586508029a7d0670dfcb2d97575dcdc242d3868a259742b69f100801ab4e16b) FetchContent_Declare(stb EXCLUDE_FROM_ALL SYSTEM URL https://github.com/nothings/stb/archive/013ac3beddff3dbffafd5177e7972067cd2b5083.zip URL_HASH SHA256=b7f476902bbef1b30f8ecc2d9d95c459c32302c8b559d09b589b5955463b7af8) -FetchContent_Declare(libktx EXCLUDE_FROM_ALL SYSTEM - GIT_REPOSITORY https://github.com/KhronosGroup/KTX-Software - GIT_TAG 91ace88675ac59a97e55d0378a6602a9ae6b98bd) +FetchContent_Declare(libktx EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/KTX-Software/archive/refs/tags/v4.4.0.tar.gz + URL_HASH SHA256=3585d76edcdcbe3a671479686f8c81c1c10339f419e4b02a9a6f19cc6e4e0612) FetchContent_Declare(implot EXCLUDE_FROM_ALL SYSTEM URL https://github.com/epezent/implot/archive/3da8bd34299965d3b0ab124df743fe3e076fa222.zip URL_HASH SHA256=e9b439a94aa6f09fcf12ed9c2cd784efe5e99e96242122aa683e690b29f7a59f) file(GLOB IMGUI_PATCHES CONFIGURE_DEPENDS patches/imgui/*) diff --git a/assets/licenses/SGSR b/assets/licenses/SGSR deleted file mode 100644 index 9ce2740b..00000000 --- a/assets/licenses/SGSR +++ /dev/null @@ -1,32 +0,0 @@ -Snapdragon(TM) Game Super Resolution -Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved. - -https://github.com/SnapdragonStudios/snapdragon-gsr - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -SPDX-License-Identifier: BSD-3-Clause diff --git a/build.gradle b/build.gradle index 088cf94e..b0dd3325 100644 --- a/build.gradle +++ b/build.gradle @@ -17,45 +17,86 @@ allprojects { apply plugin: 'com.android.application' -task "generatePngs"() { - group = 'Custom' - mkdir layout.buildDirectory.dir('generated_resources') - ["mipmap-mdpi", "mipmap-hdpi", "mipmap-xhdpi", "mipmap-xxhdpi", "mipmap-xxxhdpi", ].each { - mkdir layout.buildDirectory.dir("generated_resources/${it}") - } +import javax.inject.Inject +import org.gradle.api.DefaultTask +import org.gradle.api.tasks.* +import org.gradle.api.file.DirectoryProperty +import org.gradle.process.ExecOperations - def css = project.hasProperty('wivrn_css') ? project.wivrn_css: "images/wivrn-local.css" +abstract class GeneratePngsTask extends DefaultTask { + @Inject + abstract ExecOperations getExecOps() - exec { - executable = 'rsvg-convert' - args = [ "images/wivrn.svg", "-w", "48", "-h", "48", "-o", layout.buildDirectory.file('generated_resources/mipmap-mdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ] - } + @InputFile + abstract RegularFileProperty getSvg() - exec { - executable = 'rsvg-convert' - args = [ "images/wivrn.svg", "-w", "72", "-h", "72", "-o", layout.buildDirectory.file('generated_resources/mipmap-hdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ] - } + @InputFile + @Optional + abstract RegularFileProperty getCss() - exec { - executable = 'rsvg-convert' - args = [ "images/wivrn.svg", "-w", "96", "-h", "96", "-o", layout.buildDirectory.file('generated_resources/mipmap-xhdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ] - } + @OutputDirectory + abstract DirectoryProperty getOutputDir() - exec { - executable = 'rsvg-convert' - args = [ "images/wivrn.svg", "-w", "144", "-h", "144", "-o", layout.buildDirectory.file('generated_resources/mipmap-xxhdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ] - } + @TaskAction + void generate() { + def outDir = getOutputDir().get().asFile + outDir.mkdirs() - exec { - executable = 'rsvg-convert' - args = [ "images/wivrn.svg", "-w", "192", "-h", "192", "-o", layout.buildDirectory.file('generated_resources/mipmap-xxxhdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ] + // Map of density → size + def dpiConfigs = [ + "mipmap-mdpi" : 48, + "mipmap-hdpi" : 72, + "mipmap-xhdpi" : 96, + "mipmap-xxhdpi" : 144, + "mipmap-xxxhdpi": 192 + ] + + def cssFile = getCss().isPresent() ? getCss().get().asFile : null + + dpiConfigs.each { dpi, size -> + def dpiDir = new File(outDir, dpi) + dpiDir.mkdirs() + + def outputFile = new File(dpiDir, "ic_wivrn_launcher.png") + + def argsList = [ + getSvg().get().asFile.absolutePath, + "-w", size.toString(), + "-h", size.toString(), + "-o", outputFile.absolutePath + ] + if (cssFile != null) { + argsList.add("--stylesheet=${cssFile.absolutePath}") + } + + execOps.exec { + executable = "rsvg-convert" + args = argsList + } + } } } +tasks.register("generatePngs", GeneratePngsTask) { + group = "Custom" + + // configure defaults + svg.set(layout.projectDirectory.file("images/wivrn.svg")) + outputDir.set(layout.buildDirectory.dir("generated_resources")) + + if (project.hasProperty("wivrn_css")) { + css.set(layout.projectDirectory.file(project.wivrn_css)) + } else { + css.set(layout.projectDirectory.file("images/wivrn-local.css")) + } +} + + + android { - namespace "org.meumeu.wivrn" - ndkVersion "28.1.13356709" + namespace = "org.meumeu.wivrn" + ndkVersion = "28.1.13356709" lint { disable += "ExpiredTargetSdkVersion" @@ -105,7 +146,7 @@ android { keyAlias "default_key" storePassword signingKeyPassword // Set in gradle.properties keyPassword signingKeyPassword - enableV2Signing true + enableV2Signing = true } } } @@ -113,7 +154,7 @@ android { buildTypes { if (project.hasProperty("signingKeyPassword")) { release { - signingConfig signingConfigs.release + signingConfig = signingConfigs.release } } @@ -182,7 +223,7 @@ android { externalNativeBuild { cmake { - version '3.30.3' + version = '3.30.3' path 'CMakeLists.txt' } } diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 16f63874..4f5b7163 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -89,7 +89,7 @@ file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS file(GLOB_RECURSE VULKAN_SHADERS CONFIGURE_DEPENDS "*.glsl") target_sources(wivrn PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS}) -wivrn_compile_glsl(wivrn ${VULKAN_SHADERS}) +wivrn_compile_glsl(wivrn SHADERS ${VULKAN_SHADERS}) target_link_libraries(wivrn Vulkan::Vulkan spdlog::spdlog glm::glm fastgltf FreetypeHarfbuzz stb Boost::url Boost::locale) @@ -177,6 +177,9 @@ if(USE_ANDROID_VALIDATION_LAYER) file(COPY ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayer/android-binaries-${VVL_VERSION}/${CMAKE_ANDROID_ARCH_ABI} DESTINATION ${CMAKE_ANDROID_LIB_DIRECTORIES}) +else() + # silence "Manually-specified variables were not used by the project" warning + set(_unused ${CMAKE_ANDROID_LIB_DIRECTORIES}) endif() diff --git a/client/application.cpp b/client/application.cpp index 5e01e050..50d77654 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -18,7 +18,7 @@ */ #include "application.h" -#include "asset.h" + #include "hardware.h" #include "openxr/openxr.h" #include "scene.h" @@ -26,6 +26,7 @@ #include "spdlog/spdlog.h" #include "utils/contains.h" #include "utils/files.h" +#include "utils/i18n.h" #include "vk/check.h" #include "wifi_lock.h" #include "xr/actionset.h" @@ -67,7 +68,6 @@ struct interaction_profile std::string profile_name; std::vector required_extensions; XrVersion min_version = XR_MAKE_VERSION(1, 0, 0); - XrVersion max_version = XR_MAKE_VERSION(2, 0, 0); // exclusive std::vector input_sources; bool available; }; @@ -134,8 +134,7 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/facebook/touch_controller_pro", - .required_extensions = {"XR_FB_touch_controller_pro"}, - .max_version = XR_MAKE_VERSION(1, 1, 0), + .required_extensions = {XR_FB_TOUCH_CONTROLLER_PRO_EXTENSION_NAME}, .input_sources = { "/user/hand/left/output/haptic", "/user/hand/left/output/haptic_trigger_fb", @@ -247,8 +246,7 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/meta/touch_controller_plus", - .required_extensions = {"XR_META_touch_controller_plus"}, - .max_version = XR_MAKE_VERSION(1, 1, 0), + .required_extensions = {XR_META_TOUCH_CONTROLLER_PLUS_EXTENSION_NAME}, .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -971,7 +969,8 @@ void application::initialize_actions() std::vector sources; for (auto & profile: interaction_profiles) { - profile.available = utils::contains_all(xr_extensions, profile.required_extensions) and profile.min_version <= api_version and profile.max_version > api_version; + profile.available = std::ranges::all_of(profile.required_extensions, [&](auto & ext) { return xr_instance.has_extension(ext); }) and + profile.min_version <= api_version; if (profile.profile_name.ends_with("khr/simple_controller")) { @@ -1352,50 +1351,47 @@ void application::initialize() vk_cmdpool = vk::raii::CommandPool{vk_device, cmdpool_create_info}; initialize_actions(); + load_locale(); +} +void application::load_locale() +{ gen.add_messages_domain("wivrn"); std::locale loc = gen(""); + messages_info.encoding = "UTF-8"; + if (config->locale.empty()) + { #ifdef __ANDROID__ - jni::klass java_util_Locale("java/util/Locale"); - auto default_locale = java_util_Locale.call>("getDefault"); + jni::klass java_util_Locale("java/util/Locale"); + auto default_locale = java_util_Locale.call>("getDefault"); - // if (auto language = default_locale.call("toString")) - if (auto language = default_locale.call("getLanguage")) - messages_info.language = language; - - if (auto country = default_locale.call("getCountry")) - messages_info.country = country; - - messages_info.encoding = "UTF-8"; + // if (auto language = default_locale.call("toString")) + if (auto language = default_locale.call("getLanguage")) + messages_info.language = language; + if (auto country = default_locale.call("getCountry")) + messages_info.country = country; #else - auto & facet = std::use_facet(loc); - messages_info.language = facet.language(); - messages_info.country = facet.country(); - messages_info.encoding = "UTF-8"; + auto & facet = std::use_facet(loc); + messages_info.language = facet.language(); + messages_info.country = facet.country(); #endif + } + else + { + auto pos = config->locale.find("_"); + messages_info.language = config->locale.substr(0, pos); + if (pos != std::string::npos) + messages_info.country = config->locale.substr(pos + 1); + } spdlog::info("Current locale: language {}, country {}, encoding {}", messages_info.language, messages_info.country, messages_info.encoding); messages_info.paths.push_back("locale"); messages_info.domains.push_back(boost::locale::gnu_gettext::messages_info::domain("wivrn")); - messages_info.callback = [](const std::string & file_name, const std::string & encoding) { - std::vector buffer; - try - { - asset file(file_name); - buffer.resize(file.size()); - memcpy(buffer.data(), file.data(), file.size()); - } - catch (...) - { - } - - return buffer; - }; - + messages_info.callback = open_locale_file; loc = std::locale(loc, boost::locale::gnu_gettext::create_messages_facet(messages_info)); std::locale::global(loc); diff --git a/client/application.h b/client/application.h index cb17f87e..69327ae2 100644 --- a/client/application.h +++ b/client/application.h @@ -486,4 +486,6 @@ public: { return instance().messages_info; } + + void load_locale(); }; diff --git a/client/configuration.cpp b/client/configuration.cpp index abe7f15e..6698a9c9 100644 --- a/client/configuration.cpp +++ b/client/configuration.cpp @@ -214,8 +214,8 @@ configuration::configuration(xr::system & system) if (auto val = root["resolution_scale"]; val.is_double()) resolution_scale = val.get_double(); - if (auto val = root["sgsr"]; val.is_object()) - parse_sgsr_options(val.get_object()); + if (auto val = root["enable_stream_gui"]; val.is_bool()) + enable_stream_gui = val.get_bool(); if (auto val = root["openxr_post_processing"]; val.is_object()) parse_openxr_post_processing_options(val.get_object()); @@ -254,6 +254,9 @@ configuration::configuration(xr::system & system) if (auto val = root["first_run"]; val.is_bool()) first_run = val.get_bool(); + + if (auto val = root["locale"]; val.is_string()) + locale = val.get_string().value(); } catch (std::exception & e) { @@ -264,31 +267,11 @@ configuration::configuration(xr::system & system) preferred_refresh_rate.reset(); minimum_refresh_rate.reset(); resolution_scale = 1.4; - sgsr = {}; openxr_post_processing = {}; passthrough_enabled = system.passthrough_supported() == xr::system::passthrough_type::color; } } -void configuration::parse_sgsr_options(simdjson::simdjson_result sgsr_root) -{ - sgsr = {}; - if (auto val = sgsr_root["enabled"]; val.is_bool()) - sgsr.enabled = val.get_bool(); - - if (auto val = sgsr_root["upscaling_factor"]; val.is_double()) - sgsr.upscaling_factor = val.get_double(); - - if (auto val = sgsr_root["use_edge_direction"]; val.is_bool()) - sgsr.use_edge_direction = val.get_bool(); - - if (auto val = sgsr_root["edge_threshold"]; val.is_double()) - sgsr.edge_threshold = val.get_double(); - - if (auto val = sgsr_root["edge_sharpness"]; val.is_double()) - sgsr.edge_sharpness = val.get_double(); -} - void configuration::parse_openxr_post_processing_options(simdjson::simdjson_result openxr_post_processing_root) { openxr_post_processing = {}; @@ -304,17 +287,6 @@ static std::ostream & operator<<(std::ostream & stream, feature f) return stream << "\"" << magic_enum::enum_name(f) << "\""; } -static std::ostream & write_sgsr(std::ofstream & stream, const configuration::sgsr_settings & sgsr) -{ - stream << "{\"enabled\":" << std::boolalpha << sgsr.enabled; - stream << ",\"upscaling_factor\":" << sgsr.upscaling_factor; - stream << ",\"use_edge_direction\":" << std::boolalpha << sgsr.use_edge_direction; - stream << ",\"edge_threshold\":" << sgsr.edge_threshold; - stream << ",\"edge_sharpness\":" << sgsr.edge_sharpness; - stream << "}"; - return stream; -} - static std::ostream & write_openxr_post_processing(std::ofstream & stream, const configuration::openxr_post_processing_settings & openxr_post_processing) { stream << "{\"super_sampling\":" << openxr_post_processing.super_sampling; @@ -357,8 +329,6 @@ void configuration::save() if (minimum_refresh_rate) json << ",\"minimum_refresh_rate\":" << *minimum_refresh_rate; json << ",\"resolution_scale\":" << resolution_scale; - json << ",\"sgsr\":"; - write_sgsr(json, sgsr); json << ",\"openxr_post_processing\":"; write_openxr_post_processing(json, openxr_post_processing); json << ",\"passthrough_enabled\":" << std::boolalpha << passthrough_enabled; @@ -372,5 +342,6 @@ void configuration::save() json << ",\"override_foveation_pitch\":" << override_foveation_pitch; json << ",\"override_foveation_distance\":" << override_foveation_distance; json << ",\"first_run\":" << std::boolalpha << first_run; + json << ",\"locale\":" << json_string(locale); json << "}"; } diff --git a/client/configuration.h b/client/configuration.h index 8d34faae..d8dfbf6f 100644 --- a/client/configuration.h +++ b/client/configuration.h @@ -56,16 +56,7 @@ public: bool fb_lower_body = false; bool fb_hip = true; - // Snapdragon Game Super Resolution - struct sgsr_settings - { - bool enabled = false; - float upscaling_factor = 1.5; - bool use_edge_direction = true; - float edge_threshold = 4.0; - float edge_sharpness = 2.0; - }; - sgsr_settings sgsr{}; + bool enable_stream_gui = true; // XR_FB_composition_layer_settings extension flags struct openxr_post_processing_settings @@ -83,6 +74,8 @@ public: bool first_run = true; + std::string locale; + bool check_feature(feature f) const; void set_feature(feature f, bool state); @@ -90,7 +83,6 @@ private: mutable std::mutex mutex; std::map features; - void parse_sgsr_options(simdjson::simdjson_result root); void parse_openxr_post_processing_options(simdjson::simdjson_result root); public: diff --git a/client/decoder/android/android_decoder.cpp b/client/decoder/android/android_decoder.cpp index 2a091ad4..bde67eff 100644 --- a/client/decoder/android/android_decoder.cpp +++ b/client/decoder/android/android_decoder.cpp @@ -61,6 +61,7 @@ const char * mime(wivrn::video_codec codec) return "video/av01"; } assert(false); + __builtin_unreachable(); } void check(media_status_t status, const char * msg) @@ -72,6 +73,26 @@ void check(media_status_t status, const char * msg) } } +struct android_blit_handle : public decoder::blit_handle +{ + std::shared_ptr vk_data; + std::shared_ptr image_reader; + AImage_ptr aimage; + android_blit_handle( + const wivrn::from_headset::feedback & feedback, + const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info, + vk::ImageView image_view, + vk::Image image, + vk::ImageLayout & current_layout, + decltype(vk_data) vk_data, + decltype(image_reader) image_reader, + decltype(aimage) aimage) : + decoder::blit_handle(feedback, view_info, image_view, image, current_layout), + vk_data(vk_data), + image_reader(image_reader), + aimage(std::move(aimage)) {} +}; + } // namespace namespace wivrn::android @@ -85,7 +106,7 @@ decoder::decoder( uint8_t stream_index, std::weak_ptr weak_scene, shard_accumulator * accumulator) : - description(description), stream_index(stream_index), fps(fps), device(device), weak_scene(weak_scene), accumulator(accumulator) + wivrn::decoder(description), stream_index(stream_index), fps(fps), device(device), weak_scene(weak_scene), accumulator(accumulator) { spdlog::info("hbm_mutex.native_handle() = {}", (void *)hbm_mutex.native_handle()); @@ -222,7 +243,7 @@ void decoder::push_data(std::span> data, uint64_t frame current_input_buffer = input_buffer{}; } -void decoder::frame_completed(wivrn::from_headset::feedback & feedback, const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info) +void decoder::frame_completed(const wivrn::from_headset::feedback & feedback, const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info) { if (not media_codec) { @@ -255,7 +276,7 @@ void decoder::on_image_available(AImageReader * reader) assert(reader == image_reader.get()); // Executed on image reader thread - decltype(blit_handle::aimage) image; + decltype(android_blit_handle::aimage) image; try { AImage * tmp; @@ -280,13 +301,13 @@ void decoder::on_image_available(AImageReader * reader) auto vk_data = map_hardware_buffer(image.get()); - auto handle = std::make_shared( + auto handle = std::make_shared( info->feedback, info->view_info, - vk_data->image_view, + *vk_data->image_view, *vk_data->vimage, - &vk_data->layout, - vk_data, + vk_data->layout, + std::move(vk_data), image_reader, std::move(image)); @@ -388,7 +409,8 @@ std::shared_ptr decoder::map_hardware_buffer(AI if (!*ycbcr_sampler || memcmp(&ahb_format, &format_properties, sizeof(format_properties))) { memcpy(&ahb_format, &format_properties, sizeof(format_properties)); - extent = {buffer_desc.width, buffer_desc.height}; + extent_ = {buffer_desc.width, buffer_desc.height}; + spdlog::info("decoded image size: {}x{}", buffer_desc.width, buffer_desc.height); create_sampler(buffer_desc, ahb_format); hardware_buffer_map.clear(); // TODO tell the reprojector to recreate the pipeline @@ -514,11 +536,6 @@ void decoder::on_media_output_available(AMediaCodec * media_codec, void * userda }); } -void decoder::blit_handle::deleter::operator()(AImage * aimage) -{ - AImage_delete(aimage); -} - static bool hardware_accelerated(AMediaCodec * media_codec) { // MediaCodecInfo has isHardwareAccelerated, but this does not exist in NDK. @@ -542,9 +559,8 @@ static bool hardware_accelerated(AMediaCodec * media_codec) return true; } -std::vector decoder::supported_codecs() +void decoder::supported_codecs(std::vector & result) { - std::vector result; // Make sure we update this code when codecs are changed static_assert(magic_enum::enum_count() == 3); @@ -563,8 +579,6 @@ std::vector decoder::supported_codecs() spdlog::info("video codec {}: {}supported", magic_enum::enum_name(codec), supported ? "" : "NOT "); } - - return result; } } // namespace wivrn::android diff --git a/client/decoder/android/android_decoder.h b/client/decoder/android/android_decoder.h index 63926935..3cfa3cb4 100644 --- a/client/decoder/android/android_decoder.h +++ b/client/decoder/android/android_decoder.h @@ -19,6 +19,7 @@ #pragma once +#include "decoder/decoder.h" #include "utils/sync_queue.h" #include "wivrn_packets.h" #include @@ -59,31 +60,12 @@ class stream; namespace wivrn::android { -class decoder +class decoder : public wivrn::decoder { public: struct mapped_hardware_buffer; - struct blit_handle - { - struct deleter - { - void operator()(AImage *); - }; - wivrn::from_headset::feedback feedback; - wivrn::to_headset::video_stream_data_shard::view_info_t view_info; - vk::raii::ImageView & image_view; - vk::Image image = nullptr; - vk::ImageLayout * current_layout = nullptr; - - std::shared_ptr vk_data; - - std::shared_ptr image_reader; - AImage_ptr aimage; - }; - private: - wivrn::to_headset::video_stream_description::item description; uint8_t stream_index; float fps; @@ -92,7 +74,6 @@ private: vk::AndroidHardwareBufferFormatPropertiesANDROID ahb_format; vk::raii::SamplerYcbcrConversion ycbcr_conversion = nullptr; vk::raii::Sampler ycbcr_sampler = nullptr; - vk::Extent2D extent{}; std::mutex hbm_mutex; std::shared_ptr image_reader; @@ -146,33 +127,20 @@ public: uint8_t stream_index, std::weak_ptr scene, shard_accumulator * accumulator); - - decoder(const decoder &) = delete; - decoder(decoder &&) = delete; ~decoder(); - void push_data(std::span> data, uint64_t frame_index, bool partial); + void push_data(std::span> data, uint64_t frame_index, bool partial) override; void frame_completed( - wivrn::from_headset::feedback & feedback, - const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info); + const wivrn::from_headset::feedback & feedback, + const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info) override; - const auto & desc() const - { - return description; - } - - vk::Sampler sampler() + vk::Sampler sampler() override { return *ycbcr_sampler; } - vk::Extent2D image_size() - { - return extent; - } - - static std::vector supported_codecs(); + static void supported_codecs(std::vector &); }; } // namespace wivrn::android diff --git a/client/decoder/decoder.cpp b/client/decoder/decoder.cpp new file mode 100644 index 00000000..3fcd7e54 --- /dev/null +++ b/client/decoder/decoder.cpp @@ -0,0 +1,67 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 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 "decoder.h" + +#ifdef __ANDROID__ +#include "decoder/android/android_decoder.h" +#else +#include "decoder/ffmpeg/ffmpeg_decoder.h" +#endif + +wivrn::decoder::~decoder() = default; + +std::shared_ptr wivrn::decoder::make( + vk::raii::Device & device, + vk::raii::PhysicalDevice & phys_dev, + const wivrn::to_headset::video_stream_description::item & description, + float fps, + uint8_t stream_index, + std::weak_ptr scene, + shard_accumulator * acc) +{ +#ifdef __ANDROID__ + return std::make_shared( + device, + phys_dev, + description, + fps, + stream_index, + scene, + acc); +#else + return std::make_shared( + device, + phys_dev, + description, + stream_index, + scene, + acc); +#endif +} + +std::vector wivrn::decoder::supported_codecs() +{ + std::vector res; +#ifdef __ANDROID__ + android::decoder::supported_codecs(res); +#else + ffmpeg::decoder::supported_codecs(res); +#endif + return res; +} diff --git a/client/decoder/decoder.h b/client/decoder/decoder.h new file mode 100644 index 00000000..44497327 --- /dev/null +++ b/client/decoder/decoder.h @@ -0,0 +1,79 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 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 +#include +#include +#include + +namespace scenes +{ +class stream; +} + +namespace wivrn +{ +class shard_accumulator; +class decoder +{ +public: + struct blit_handle + { + wivrn::from_headset::feedback feedback; + wivrn::to_headset::video_stream_data_shard::view_info_t view_info; + vk::ImageView image_view = nullptr; + vk::Image image = nullptr; + vk::ImageLayout & current_layout; + }; + + const wivrn::to_headset::video_stream_description::item description; + +protected: + decoder(const wivrn::to_headset::video_stream_description::item & description) : + description(description) {} + vk::Extent2D extent_; // Must be populated when sampler is set + +public: + static std::shared_ptr make( + vk::raii::Device &, + vk::raii::PhysicalDevice &, + const wivrn::to_headset::video_stream_description::item & description, + float fps, + uint8_t stream_index, + std::weak_ptr, + shard_accumulator *); + virtual ~decoder(); + virtual void push_data(std::span> data, uint64_t frame_index, bool partial) = 0; + + virtual void frame_completed( + const from_headset::feedback & feedback, + const to_headset::video_stream_data_shard::view_info_t & view_info) = 0; + + virtual vk::Sampler sampler() = 0; + const vk::Extent2D extent() + { + return extent_; + } + + static std::vector supported_codecs(); +}; +} // namespace wivrn diff --git a/client/decoder/ffmpeg/ffmpeg_decoder.cpp b/client/decoder/ffmpeg/ffmpeg_decoder.cpp index 09416a28..7f960b37 100644 --- a/client/decoder/ffmpeg/ffmpeg_decoder.cpp +++ b/client/decoder/ffmpeg/ffmpeg_decoder.cpp @@ -61,24 +61,53 @@ static AVCodecID codec_id(wivrn::video_codec codec) __builtin_unreachable(); } -decoder::blit_handle::~blit_handle() +struct decoder::ffmpeg_blit_handle : public wivrn::decoder::blit_handle { - std::unique_lock lock(self->mutex); - if (image_index < 0) - return; + int image_index; + wivrn::ffmpeg::decoder * self; - self->free_images.push_back(image_index); -} + ffmpeg_blit_handle( + const wivrn::from_headset::feedback & feedback, + const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info, + vk::ImageView image_view, + vk::Image image, + vk::ImageLayout & current_layout, + int image_index, + wivrn::ffmpeg::decoder * self) : + wivrn::decoder::blit_handle{ + feedback, + view_info, + image_view, + image, + current_layout, + }, + image_index(image_index), + self(self) + {} + + ~ffmpeg_blit_handle() + { + std::unique_lock lock(self->mutex); + if (image_index < 0) + return; + + self->free_images.push_back(image_index); + } +}; decoder::decoder( vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, const wivrn::to_headset::video_stream_description::item & description, - float fps, uint8_t stream_index, std::weak_ptr scene, shard_accumulator * accumulator) : - device(device), description(description), codec(nullptr, free_codec_context), sws(nullptr, sws_freeContext), weak_scene(scene), accumulator(accumulator) + wivrn::decoder(description), + device(device), + codec(nullptr, free_codec_context), + sws(nullptr, sws_freeContext), + weak_scene(scene), + accumulator(accumulator) { free_images.resize(image_count); @@ -108,7 +137,7 @@ decoder::decoder( decoded_images[i].image = image_allocation(device, image_info, alloc_info); decoded_images[i].image.map(); - extent = vk::Extent2D{description.width, description.height}; + extent_ = vk::Extent2D{description.width, description.height}; vk::ImageSubresource resource; resource.aspectMask = vk::ImageAspectFlagBits::eColor; @@ -221,12 +250,12 @@ void decoder::frame_completed(const wivrn::from_headset::feedback & feedback, co if (res == 0) throw std::runtime_error{"sws_scale failed"}; - auto handle = std::make_shared( + auto handle = std::make_shared( feedback, view_info, - decoded_images[index].image_view, - (vk::Image)decoded_images[index].image, - &decoded_images[index].current_layout, + *decoded_images[index].image_view, + decoded_images[index].image, + decoded_images[index].current_layout, index, this); @@ -234,13 +263,11 @@ void decoder::frame_completed(const wivrn::from_headset::feedback & feedback, co scene->push_blit_handle(accumulator, std::move(handle)); } -std::vector decoder::supported_codecs() +void decoder::supported_codecs(std::vector & res) { - return { - wivrn::video_codec::h264, - wivrn::video_codec::h265, - wivrn::video_codec::av1, - }; + res.push_back(wivrn::video_codec::h264); + res.push_back(wivrn::video_codec::h265); + res.push_back(wivrn::video_codec::av1); } } // namespace wivrn::ffmpeg diff --git a/client/decoder/ffmpeg/ffmpeg_decoder.h b/client/decoder/ffmpeg/ffmpeg_decoder.h index 33190af8..9bc121d5 100644 --- a/client/decoder/ffmpeg/ffmpeg_decoder.h +++ b/client/decoder/ffmpeg/ffmpeg_decoder.h @@ -19,6 +19,7 @@ #pragma once +#include "decoder/decoder.h" #include "vk/allocation.h" #include "wivrn_packets.h" #include @@ -46,24 +47,10 @@ class stream; namespace wivrn::ffmpeg { -class decoder +class decoder : public wivrn::decoder { -public: - struct blit_handle - { - wivrn::from_headset::feedback feedback; - wivrn::to_headset::video_stream_data_shard::view_info_t view_info; - vk::raii::ImageView & image_view; - vk::Image image = nullptr; - vk::ImageLayout * current_layout = nullptr; - - int image_index; - decoder * self; - - ~blit_handle(); - }; - private: + struct ffmpeg_blit_handle; static const int image_count = 12; struct image { @@ -78,11 +65,8 @@ private: vk::raii::Sampler rgb_sampler = nullptr; std::array decoded_images; - vk::Extent2D extent{}; std::vector free_images; - wivrn::to_headset::video_stream_description::item description; - std::unique_ptr codec; std::unique_ptr sws; std::vector packet; @@ -96,35 +80,21 @@ public: decoder(vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, const wivrn::to_headset::video_stream_description::item & description, - float fps, uint8_t stream_index, std::weak_ptr scene, shard_accumulator * accumulator); - decoder(const decoder &) = delete; - decoder(decoder &&) = delete; - - void push_data(std::span> data, uint64_t frame_index, bool partial); + void push_data(std::span> data, uint64_t frame_index, bool partial) override; void frame_completed( const wivrn::from_headset::feedback & feedback, - const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info); + const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info) override; - const auto & desc() const - { - return description; - } - - vk::Sampler sampler() + vk::Sampler sampler() override { return *rgb_sampler; } - vk::Extent2D image_size() - { - return extent; - } - - static std::vector supported_codecs(); + static void supported_codecs(std::vector &); }; } // namespace wivrn::ffmpeg diff --git a/client/decoder/shard_accumulator.cpp b/client/decoder/shard_accumulator.cpp index 6b6106ce..c570fa93 100644 --- a/client/decoder/shard_accumulator.cpp +++ b/client/decoder/shard_accumulator.cpp @@ -186,7 +186,7 @@ void shard_accumulator::try_submit_frame(uint16_t shard_idx) payload.emplace_back(data_shards[idx]->payload); bool frame_complete = last_idx == data_shards.size() and data_shards.back()->flags & video_stream_data_shard::end_of_frame; - decoder->push_data(payload, data_shards[shard_idx]->frame_idx, not frame_complete); + decoder_->push_data(payload, data_shards[shard_idx]->frame_idx, not frame_complete); if (not frame_complete) return; @@ -206,7 +206,7 @@ void shard_accumulator::try_submit_frame(uint16_t shard_idx) } // Try to extract a frame - decoder->frame_completed(current.feedback, *data_shards.front()->view_info); + decoder_->frame_completed(current.feedback, *data_shards.front()->view_info); send_feedback(current.feedback); diff --git a/client/decoder/shard_accumulator.h b/client/decoder/shard_accumulator.h index 4777de7f..a0145e22 100644 --- a/client/decoder/shard_accumulator.h +++ b/client/decoder/shard_accumulator.h @@ -19,27 +19,30 @@ #pragma once -#include -#include - -#ifdef __ANDROID__ -#include "decoder/android/android_decoder.h" -using decoder_impl = ::wivrn::android::decoder; -#else -#include "decoder/ffmpeg/ffmpeg_decoder.h" -using decoder_impl = ::wivrn::ffmpeg::decoder; -#endif - +#include "decoder.h" #include "wivrn_packets.h" + +#include #include #include +#include + +namespace xr +{ +class instance; +} + +namespace scenes +{ +class stream; +} namespace wivrn { class shard_accumulator { - std::shared_ptr decoder; + std::shared_ptr decoder_; public: using data_shard = wivrn::to_headset::video_stream_data_shard; @@ -50,7 +53,7 @@ public: void reset(uint64_t frame_index); bool empty() const; - std::optional insert(data_shard &&); + std::optional insert(data_shard &&, xr::instance & instance); wivrn::from_headset::feedback feedback{}; @@ -70,19 +73,22 @@ private: shard_set current; shard_set next; std::weak_ptr weak_scene; + xr::instance & instance; public: explicit shard_accumulator( vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, + xr::instance & instance, const wivrn::to_headset::video_stream_description::item & description, float fps, std::weak_ptr scene, uint8_t stream_index) : - decoder(std::make_shared(device, physical_device, description, fps, stream_index, scene, this)), + decoder_(decoder::make(device, physical_device, description, fps, stream_index, scene, this)), current(stream_index), next(stream_index), - weak_scene(scene) + weak_scene(scene), + instance(instance) { next.reset(1); } @@ -91,20 +97,20 @@ public: auto & desc() const { - return decoder->desc(); + return decoder_->description; } vk::Sampler sampler() { - return decoder->sampler(); + return decoder_->sampler(); } - vk::Extent2D image_size() + const vk::Extent2D extent() { - return decoder->image_size(); + return decoder_->extent(); } - using blit_handle = decoder_impl::blit_handle; + using blit_handle = decoder::blit_handle; private: void try_submit_frame(std::optional shard_idx); diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index 53d59862..7a2daabb 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -490,22 +490,22 @@ static std::vector find_font(std::u16string sample_text, const std: void imgui_context::initialize_fonts() { - std::u16string sample_text = u"Hello world"; - - const auto & locale = application::get_messages_info(); - auto it = glyph_set_per_language.find(locale.language + "_" + locale.country); - if (it == glyph_set_per_language.end()) - it = glyph_set_per_language.find(locale.language); - - if (it != glyph_set_per_language.end()) - for (char16_t c: it->second) - sample_text += c; - - // Load Fonts - auto fonts = find_font(sample_text, application::get_messages_info().language); - for (auto & i: fonts) + std::vector fonts; + for (auto & [code, glyphs]: glyph_set_per_language) { - spdlog::info("Font {}", i); + std::u16string sample_text = u"Hello world"; + + for (char16_t c: glyphs) + sample_text += c; + auto language = code.substr(0, code.find("_")); + + // Load Fonts + for (auto && i: find_font(sample_text, language)) + { + spdlog::info("Font for {} {}", code, i); + if (not std::ranges::contains(fonts, i)) + fonts.push_back(std::move(i)); + } } asset font_awesome_regular("Font Awesome 6 Free-Regular-400.otf"); diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index d944c559..e67831ce 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -34,7 +34,6 @@ #include #include #include -#include #include #include #include @@ -42,8 +41,6 @@ #include #include -extern const std::map> shaders; - // TODO move in lobby? vk::Format scene_renderer::find_usable_image_format( vk::raii::PhysicalDevice physical_device, diff --git a/client/scenes/blitter.cpp b/client/scenes/blitter.cpp new file mode 100644 index 00000000..d5fddc94 --- /dev/null +++ b/client/scenes/blitter.cpp @@ -0,0 +1,364 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 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 "blitter.h" + +#include "application.h" +#include "utils/ranges.h" +#include "vk/pipeline.h" +#include "vk/shader.h" +#include "vk/specialization_constants.h" +#include +#include +#include + +namespace wivrn +{ + +static const uint32_t num_views = 2; + +blitter::blitter(vk::raii::Device & device, size_t view) : + device(device), view(view) +{ +} + +void blitter::reset(const to_headset::video_stream_description & desc) +{ + using channels_t = to_headset::video_stream_description::channels_t; + this->desc = desc; + + current = {}; + target = image_allocation(); + image_view = nullptr; + rp = nullptr; + fb = nullptr; + sampler = nullptr; + pipelines.clear(); + passthrough_rgb = passthrough_a = -1; + + auto w = desc.width / num_views; + for (auto [i, item]: utils::enumerate(desc.items)) + { + if (item.offset_x <= view * w and + item.offset_y == 0 and + item.offset_x + item.width * item.subsampling >= (view + 1) * w and + item.height * item.subsampling >= desc.height) + { + spdlog::info("Stream {} is eligible for blit-less path on view {}", i, view); + switch (item.channels) + { + case channels_t::colour: + passthrough_rgb = i; + break; + case channels_t::alpha: + passthrough_a = i; + break; + } + const bool alpha = item.channels == to_headset::video_stream_description::channels_t::alpha; + auto & r = alpha ? current.rect_a : current.rect_rgb; + r = vk::Rect2D{ + .offset = { + .x = int32_t(view * w) - item.offset_x, + .y = 0, + }, + }; + } + } + + if (passthrough_rgb != -1 and passthrough_a != -1) + return; + + target = image_allocation( + device, + vk::ImageCreateInfo{ + .imageType = vk::ImageType::e2D, + .format = vk::Format::eB8G8R8A8Srgb, + .extent = { + .width = w, + .height = desc.height, + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment, + }, + { + .usage = VMA_MEMORY_USAGE_AUTO, + }, + std::format("blit image {}", view)); + + image_view = device.createImageView(vk::ImageViewCreateInfo{ + .image = vk::Image(target), + .viewType = vk::ImageViewType::e2D, + .format = target.info().format, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .levelCount = 1, + .layerCount = 1, + }}); + + // render pass + { + vk::AttachmentReference color_ref{ + .attachment = 0, + .layout = vk::ImageLayout::eColorAttachmentOptimal, + }; + + vk::SubpassDescription subpass{ + .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, + .colorAttachmentCount = 1, + .pColorAttachments = &color_ref, + }; + + vk::AttachmentDescription color_desc{ + .format = target.info().format, + .loadOp = vk::AttachmentLoadOp::eDontCare, + .finalLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + }; + + rp = device.createRenderPass(vk::RenderPassCreateInfo{ + .attachmentCount = 1, + .pAttachments = &color_desc, + .subpassCount = 1, + .pSubpasses = &subpass, + }); + } + + fb = device.createFramebuffer( + vk::FramebufferCreateInfo{ + .renderPass = *rp, + .attachmentCount = 1, + .pAttachments = &*image_view, + .width = w, + .height = desc.height, + .layers = 1, + }); + + sampler = device.createSampler(vk::SamplerCreateInfo{ + .magFilter = vk::Filter::eLinear, + .minFilter = vk::Filter::eLinear, + .addressModeU = vk::SamplerAddressMode::eClampToBorder, + .addressModeV = vk::SamplerAddressMode::eClampToBorder, + .addressModeW = vk::SamplerAddressMode::eClampToBorder, + .borderColor = vk::BorderColor::eFloatOpaqueBlack, + }); + + pipelines.resize(desc.items.size()); + for (auto [i, item]: utils::enumerate(desc.items)) + { + pipelines[i].used = item.offset_x < (view + 1) * w and + item.offset_x + item.width * item.subsampling > view * w; + } + + current.rgb = *image_view; + current.sampler_rgb = *sampler; + current.rect_rgb = vk::Rect2D{.extent = {w, desc.height}}; + current.layout_rgb = vk::ImageLayout::eShaderReadOnlyOptimal; +} + +void blitter::begin(vk::raii::CommandBuffer & cmd) +{ + assert(not desc.items.empty()); + if (*fb == VK_NULL_HANDLE) + { + current.rgb = nullptr; + current.a = nullptr; + current.sampler_rgb = nullptr; + current.sampler_a = nullptr; + return; + } + + current.rgb = *image_view; + current.sampler_rgb = *sampler; + + cmd.beginRenderPass( + { + .renderPass = *rp, + .framebuffer = *fb, + .renderArea = { + .offset = {0, 0}, + .extent = {target.info().extent.width, target.info().extent.height}, + }, + }, + vk::SubpassContents::eInline); +} + +void blitter::push_image(vk::raii::CommandBuffer & cmd, uint8_t stream, vk::Sampler sampler, const vk::Extent2D & extent_, vk::ImageView image, vk::ImageLayout layout) +{ + if (stream == passthrough_rgb) + { + current.rgb = image; + current.sampler_rgb = sampler; + current.layout_rgb = layout; + current.rect_rgb.extent = vk::Extent2D{ + extent_.width * desc.items[stream].subsampling, + extent_.height * desc.items[stream].subsampling, + }; + return; + } + if (stream == passthrough_a) + { + current.a = image; + current.sampler_a = sampler; + current.layout_a = layout; + current.rect_a.extent = vk::Extent2D{ + extent_.width * desc.items[stream].subsampling, + extent_.height * desc.items[stream].subsampling, + }; + return; + } + if (pipelines.empty()) + return; + + assert(stream < pipelines.size()); + auto & p = pipelines[stream]; + if (not p.used) + return; + + const auto & extent = target.info().extent; + const auto & description = desc.items[stream]; + if (not *p.pipeline) + { + const bool alpha = description.channels == to_headset::video_stream_description::channels_t::alpha; + vk::DescriptorSetLayoutBinding sampler_layout_binding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eFragment, + .pImmutableSamplers = &sampler, + }; + + p.set_layout = device.createDescriptorSetLayout(vk::DescriptorSetLayoutCreateInfo{ + .flags = vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR, + .bindingCount = 1, + .pBindings = &sampler_layout_binding, + }); + + auto vert_constants = make_specialization_constants( + float(description.width) / extent_.width, + float(description.height) / extent_.height); + + auto frag_constants = make_specialization_constants( + VkBool32(alpha)); + + // Create graphics pipeline + vk::raii::ShaderModule vertex_shader = load_shader(device, "stream.vert"); + vk::raii::ShaderModule fragment_shader = load_shader(device, "stream.frag"); + + p.layout = device.createPipelineLayout(vk::PipelineLayoutCreateInfo{ + .setLayoutCount = 1, + .pSetLayouts = &*p.set_layout, + }); + + vk::pipeline_builder pipeline_info{ + .Stages = {{ + .stage = vk::ShaderStageFlagBits::eVertex, + .module = *vertex_shader, + .pName = "main", + .pSpecializationInfo = vert_constants, + }, + { + .stage = vk::ShaderStageFlagBits::eFragment, + .module = *fragment_shader, + .pName = "main", + .pSpecializationInfo = frag_constants, + }}, + .VertexBindingDescriptions = {}, + .VertexAttributeDescriptions = {}, + .InputAssemblyState = {{ + .topology = vk::PrimitiveTopology::eTriangleStrip, + }}, + // With vk::DynamicState::eViewport, vk::DynamicState::eScissor the number of viewports + // and scissors is still used, put a vector with one element + .Viewports = {{}}, + .Scissors = {{}}, + .RasterizationState = {{ + .polygonMode = vk::PolygonMode::eFill, + .lineWidth = 1, + }}, + .MultisampleState = {{ + .rasterizationSamples = vk::SampleCountFlagBits::e1, + }}, + .ColorBlendAttachments = { + {.colorWriteMask = alpha ? vk::ColorComponentFlagBits::eA + : vk::ColorComponentFlagBits::eA | vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB}}, + .DynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor}, + .layout = *p.layout, + .renderPass = *rp, + .subpass = 0, + }; + + p.pipeline = device.createGraphicsPipeline(application::get_pipeline_cache(), pipeline_info); + spdlog::info("Created blit pipeline for stream {}, view {}", stream, view); + } + + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, *p.pipeline); + + vk::DescriptorImageInfo image_info{ + .imageView = image, + .imageLayout = layout, + }; + cmd.pushDescriptorSetKHR( + vk::PipelineBindPoint::eGraphics, + *p.layout, + 0, + vk::WriteDescriptorSet{ + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = &image_info, + }); + + int x0 = description.offset_x - view * extent.width; + int y0 = description.offset_y; + int x1 = x0 + description.width * description.subsampling; + int y1 = y0 + description.height * description.subsampling; + + cmd.setViewport( + 0, + vk::Viewport{ + .x = (float)x0, + .y = (float)y0, + .width = float(description.width * description.subsampling), + .height = float(description.height * description.subsampling), + .minDepth = 0, + .maxDepth = 1, + }); + + x0 = std::clamp(x0, 0, extent.width); + x1 = std::clamp(x1, 0, extent.width); + y0 = std::clamp(y0, 0, extent.height); + y1 = std::clamp(y1, 0, extent.height); + + cmd.setScissor( + 0, + vk::Rect2D{ + .offset = {.x = x0, .y = y0}, + .extent = {.width = uint32_t(x1 - x0), .height = uint32_t(y1 - y0)}, + }); + cmd.draw(3, 1, 0, 0); +} + +blitter::output blitter::end(vk::raii::CommandBuffer & cmd) +{ + if (*fb) + cmd.endRenderPass(); + return current; +} + +} // namespace wivrn diff --git a/client/scenes/blitter.h b/client/scenes/blitter.h new file mode 100644 index 00000000..26685c72 --- /dev/null +++ b/client/scenes/blitter.h @@ -0,0 +1,72 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 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/allocation.h" +#include "wivrn_packets.h" +#include + +namespace wivrn +{ +class blitter +{ +public: + struct output + { + vk::ImageView rgb; + vk::Sampler sampler_rgb; + vk::Rect2D rect_rgb; + vk::ImageLayout layout_rgb; + vk::ImageView a; + vk::Sampler sampler_a; + vk::Rect2D rect_a; + vk::ImageLayout layout_a; + }; + +private: + vk::raii::Device & device; + size_t view; + to_headset::video_stream_description desc; + // indices to simply passthrough, if -1 image needs to be blitted + int passthrough_rgb = -1; + int passthrough_a = -1; + image_allocation target; + vk::raii::ImageView image_view = nullptr; + vk::raii::RenderPass rp = nullptr; + vk::raii::Framebuffer fb = nullptr; + vk::raii::Sampler sampler = nullptr; + struct pipeline_t + { + vk::raii::DescriptorSetLayout set_layout = nullptr; + vk::raii::PipelineLayout layout = nullptr; + vk::raii::Pipeline pipeline = nullptr; + bool used = false; // true if we need this image for blitting + }; + std::vector pipelines; + output current; + +public: + blitter(vk::raii::Device & device, size_t view); + + void reset(const to_headset::video_stream_description & desc); + void begin(vk::raii::CommandBuffer &); + void push_image(vk::raii::CommandBuffer & buf, uint8_t stream, vk::Sampler sampler, const vk::Extent2D &, vk::ImageView image, vk::ImageLayout); + output end(vk::raii::CommandBuffer &); +}; +} // namespace wivrn diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index b6137db1..5ff2efa0 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -17,6 +17,7 @@ * along with this program. If not, see . */ +#include #define IMGUI_DEFINE_MATH_OPERATORS #ifdef __ANDROID__ @@ -139,7 +140,7 @@ static void InputText(const char * label, std::string & text, const ImVec2 & siz return 0; }; - ImGui::InputTextEx(label, nullptr, text.data(), text.size(), size, flags | ImGuiInputTextFlags_CallbackResize, callback, &text); + ImGui::InputTextEx(label, nullptr, text.data(), text.size() + 1, size, flags | ImGuiInputTextFlags_CallbackResize, callback, &text); } static void display_recentering_tip(imgui_context & ctx, const std::string & tip) @@ -771,6 +772,43 @@ void scenes::lobby::gui_settings() ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(20, 20)); + { + auto language_name = [&](const std::locale & loc = std::locale()) { + return boost::locale::pgettext("language selection, replace with the name of the language", "English", loc); + }; + std::vector> languages; + for (const auto & msg_info: get_locales()) + { + std::string code = msg_info.language; + if (not msg_info.country.empty()) + code += "_" + msg_info.country; + std::locale loc(std::locale(), boost::locale::gnu_gettext::create_messages_facet(msg_info)); + languages.emplace_back(language_name(loc), loc, std::move(code)); + } + std::ranges::sort(languages, [](auto & l, auto & r) { + return una::casesens::collate_utf8(std::get<0>(l), std::get<0>(r)) < 0; + }); + if (ImGui::BeginCombo(_S("Language"), config.locale.empty() ? _S("System language") : language_name().c_str())) + { + if (ImGui::Selectable(_S("System language"), config.locale.empty(), ImGuiSelectableFlags_SelectOnRelease)) + { + config.locale.clear(); + config.save(); + application::instance().load_locale(); + } + for (const auto & [lang, locale, code]: languages) + { + if (ImGui::Selectable(lang.c_str(), code == config.locale, ImGuiSelectableFlags_SelectOnRelease)) + { + config.locale = code; + config.save(); + application::instance().load_locale(); + } + } + ImGui::EndCombo(); + } + } + if (instance.has_extension(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME)) { const auto & refresh_rates = session.get_refresh_rates(); @@ -1034,89 +1072,6 @@ void scenes::lobby::gui_post_processing() ImGui::Unindent(); } - { - // SGSR - { - if (ImGui::Checkbox(_S("Enable Snapdragon Game Super Resolution"), &config.sgsr.enabled)) - { - config.save(); - } - imgui_ctx->vibrate_on_hover(); - if (ImGui::IsItemHovered()) - { - if (application::get_openxr_post_processing_supported()) - imgui_ctx->tooltip(_("On this headset, this setting has been fully superseded by the native Sharpening setting above.\nOnly enable if you know what you're doing.")); - else - imgui_ctx->tooltip(_("Client-side upscaling and sharpening, adds a performance cost on the headset")); - } - if (application::get_openxr_post_processing_supported()) - { - ImGui::SameLine(); - ImGui::TextColored(ImColor(0xf9, 0x73, 0x06) /*orange*/, ICON_FA_TRIANGLE_EXCLAMATION); - } - } - - { - ImGui::BeginDisabled(not config.sgsr.enabled); - ImGui::Indent(); - { - const auto current = config.sgsr.upscaling_factor; - const auto width = stream_view.recommendedImageRectWidth * config.resolution_scale; - const auto height = stream_view.recommendedImageRectHeight * config.resolution_scale; - auto intScale = int(current * 100); - const auto slider = ImGui::SliderInt( - _("Upscaling factor").append("##upscaling_factor").c_str(), - &intScale, - 100, - 200, - fmt::format(_F("%d%% - {}x{} per eye"), int(width * current), int(height * current)).c_str()); - if (slider) - { - config.sgsr.upscaling_factor = intScale * 0.01; - config.save(); - } - imgui_ctx->vibrate_on_hover(); - if (width * current > stream_view.maxImageRectWidth or height * current > stream_view.maxImageRectHeight) - { - ImGui::TextColored(ImColor(0xf9, 0x73, 0x06) /*orange*/, ICON_FA_TRIANGLE_EXCLAMATION); - ImGui::SameLine(); - ImGui::Text("%s", fmt::format(_F("Resolution larger than {}x{} may not be supported by the headset"), stream_view.maxImageRectWidth, stream_view.maxImageRectHeight).c_str()); - } - } - { - if (ImGui::Checkbox(_S("Use edge direction"), &config.sgsr.use_edge_direction)) - { - config.save(); - } - imgui_ctx->vibrate_on_hover(); - if (ImGui::IsItemHovered()) - imgui_ctx->tooltip(_("Adds an additional performance cost")); - } - { - const float current = config.sgsr.edge_threshold; - int intScale = int(current); - if (ImGui::SliderInt(_S("Edge threshold"), &intScale, 1, 16, "%d.0")) - { - config.sgsr.edge_threshold = float(intScale); - config.save(); - } - imgui_ctx->vibrate_on_hover(); - if (ImGui::IsItemHovered()) - imgui_ctx->tooltip(fmt::format(_F("Recommended: {:.1f}"), 4.0)); - } - { - if (ImGui::SliderFloat(_S("Edge sharpness"), &config.sgsr.edge_sharpness, 1.0, 2.0, "%.2f")) - { - config.save(); - } - imgui_ctx->vibrate_on_hover(); - if (ImGui::IsItemHovered()) - imgui_ctx->tooltip(fmt::format(_F("Recommended: {:.1f}"), 2.0)); - } - ImGui::Unindent(); - ImGui::EndDisabled(); - } - } ImGui::PopStyleVar(); } @@ -1347,7 +1302,7 @@ void scenes::lobby::gui_licenses() ImGui::Text("%s", _("Licenses").c_str()); ImGui::PopFont(); - const auto components = {"WiVRn", "FontAwesome", "openxr-loader", "simdjson", "SGSR"}; + const auto components = {"WiVRn", "FontAwesome", "openxr-loader", "simdjson"}; if (not license) { selected_item = *components.begin(); diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index dc20f14e..e79c1305 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -17,11 +17,9 @@ * along with this program. If not, see . */ #include "constants.h" -#include "utils/overloaded.h" -#include "xr/fb_body_tracker.h" +#include "xr/body_tracker.h" +#include "xr/face_tracker.h" #include "xr/fb_face_tracker2.h" -#include "xr/htc_body_tracker.h" -#include "xr/pico_body_tracker.h" #include "xr/space.h" #include #include @@ -40,8 +38,6 @@ #include "utils/contains.h" #include "utils/named_thread.h" #include "utils/ranges.h" -#include "vk/pipeline.h" -#include "vk/shader.h" #include "wivrn_packets.h" #include #include @@ -49,6 +45,11 @@ #include #include +#include "wivrn_config.h" +#if WIVRN_FEATURE_RENDERDOC +#include "vk/renderdoc.h" +#endif + using namespace wivrn; // clang-format off @@ -151,7 +152,8 @@ static const std::array supported_depth_formats{ }; scenes::stream::stream() : - scene_impl(supported_color_formats, supported_depth_formats) + scene_impl(supported_color_formats, supported_depth_formats), + blitters{blitter(device, 0), blitter(device, 1)} { } @@ -189,7 +191,11 @@ std::shared_ptr scenes::stream::create(std::unique_ptrnetwork_session = std::move(network_session); self->network_session->send_control([&]() { - from_headset::headset_info_packet info{}; + from_headset::headset_info_packet info{ + .language = application::get_messages_info().language, + .country = application::get_messages_info().country, + .variant = application::get_messages_info().variant, + }; auto view = self->system.view_configuration_views(self->viewconfig)[0]; view = override_view(view, guess_model()); @@ -251,46 +257,49 @@ std::shared_ptr scenes::stream::create(std::unique_ptrsystem.face_tracker_supported()) + { + case xr::face_tracker_type::none: + info.face_tracking = from_headset::face_type::none; + break; + case xr::face_tracker_type::fb: + case xr::face_tracker_type::pico: + info.face_tracking = from_headset::face_type::fb2; + break; + case xr::face_tracker_type::htc: + info.face_tracking = from_headset::face_type::htc; + break; + } } info.num_generic_trackers = 0; if (config.check_feature(feature::body_tracking)) { - info.num_generic_trackers = std::visit(utils::overloaded{ - [&](std::monostate &) { - return size_t(0); - }, - [&](auto & b) { - return b.count(); - }, - }, - application::get_body_tracker()); + switch (self->system.body_tracker_supported()) + { + case xr::body_tracker_type::none: + break; + case xr::body_tracker_type::fb: + info.num_generic_trackers = xr::fb_body_tracker::get_whitelisted_joints(config.fb_lower_body, config.fb_hip).size(); + break; + case xr::body_tracker_type::htc: + info.num_generic_trackers = application::get_generic_trackers().size(); + break; + case xr::body_tracker_type::pico: + info.num_generic_trackers = xr::pico_body_tracker::joint_whitelist.size(); + break; + } } info.palm_pose = application::space(xr::spaces::palm_left) or application::space(xr::spaces::palm_right); - info.passthrough = self->system.passthrough_supported() != xr::system::passthrough_type::no_passthrough; + info.passthrough = self->system.passthrough_supported() != xr::passthrough_type::none; info.system_name = std::string(self->system.properties().systemName); audio::get_audio_description(info); if (not(config.check_feature(feature::microphone))) info.microphone = {}; - info.supported_codecs = decoder_impl::supported_codecs(); + info.supported_codecs = decoder::supported_codecs(); return info; }()); @@ -311,15 +320,6 @@ std::shared_ptr scenes::stream::create(std::unique_ptrnetwork_session->send_control(from_headset::get_application_list{ - .language = info.language, - .country = info.country, - .variant = info.variant, - }); - } - { const auto & config = application::get_config(); self->override_foveation_enable = config.override_foveation_enable; @@ -363,7 +363,7 @@ std::shared_ptr scenes::stream::create(std::unique_ptrhaptics_actions.emplace(id, haptics_action{ .action = action.first, - .path = application::string_to_path(path), + .path = self->instance.string_to_path(path), }); } } @@ -394,7 +394,7 @@ std::shared_ptr scenes::stream::create(std::unique_ptrget_default_material()); + loader.emplace(device, physical_device, queue, queue_family_index, renderer->get_default_material()); std::string profile = controller_name(); input.emplace( @@ -470,8 +470,11 @@ void scenes::stream::on_focused() swapchain_imgui, std::vector{vp}); - plots_toggle_1 = get_action("plots_toggle_1").first; - plots_toggle_2 = get_action("plots_toggle_2").first; + if (application::get_config().enable_stream_gui) + { + plots_toggle_1 = get_action("plots_toggle_1").first; + plots_toggle_2 = get_action("plots_toggle_2").first; + } recenter_left = get_action("recenter_left").first; recenter_right = get_action("recenter_right").first; foveation_pitch = get_action("foveation_pitch").first; @@ -494,6 +497,8 @@ void scenes::stream::on_unfocused() loader.reset(); renderer.reset(); clear_swapchains(); + left_hand.reset(); + right_hand.reset(); imgui_ctx.reset(); swapchain_imgui = xr::swapchain(); @@ -524,16 +529,16 @@ void scenes::stream::push_blit_handle(shard_accumulator * decoder, std::shared_p { if (decoder != decoders[stream].decoder.get()) return; - handle->feedback.received_from_decoder = application::now(); + handle->feedback.received_from_decoder = instance.now(); std::swap(handle, decoders[stream].latest_frames[handle->feedback.frame_index % decoders[stream].latest_frames.size()]); } if (state_ != state::streaming and std::ranges::all_of(decoders, [](accumulator_images & i) { - return i.alpha() or not i.frames().empty(); + return i.alpha() or not i.empty(); })) { state_ = state::streaming; - spdlog::info("Stream scene ready at t={}", application::now()); + spdlog::info("Stream scene ready at t={}", instance.now()); } } @@ -548,15 +553,14 @@ bool scenes::stream::accumulator_images::alpha() const return decoder->desc().channels == wivrn::to_headset::video_stream_description::channels_t::alpha; } -std::vector scenes::stream::accumulator_images::frames() const +bool scenes::stream::accumulator_images::empty() const { - std::vector result; for (const auto & frame: latest_frames) { if (frame) - result.push_back(frame->feedback.frame_index); + return false; } - return result; + return true; } std::vector> scenes::stream::common_frame(XrTime display_time) @@ -766,138 +770,17 @@ void scenes::stream::render(const XrFrameState & frame_state) } if (state_ == state::stalled) - application::pop_scene(); - - assert(swapchain); - for (auto & i: decoders) { - if (auto sampler = i.decoder->sampler(); sampler and not *i.blit_pipeline) - { - // Create blit pipeline - // Create VkDescriptorSetLayout with an immutable sampler - vk::DescriptorSetLayoutBinding sampler_layout_binding{ - .binding = 0, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment, - .pImmutableSamplers = &sampler, - }; + network_session->send_control(from_headset::get_application_list{ + .language = application::get_messages_info().language, + .country = application::get_messages_info().country, + .variant = application::get_messages_info().variant, + }); - vk::DescriptorSetLayoutCreateInfo layout_info{ - .bindingCount = 1, - .pBindings = &sampler_layout_binding, - }; - - i.descriptor_set_layout = vk::raii::DescriptorSetLayout(device, layout_info); - i.descriptor_set = device.allocateDescriptorSets( - vk::DescriptorSetAllocateInfo{ - .descriptorPool = *blit_descriptor_pool, - .descriptorSetCount = 1, - .pSetLayouts = &*i.descriptor_set_layout, - })[0] - .release(); - - const auto & description = i.decoder->desc(); - vk::Extent2D image_size = i.decoder->image_size(); - std::array useful_size{ - float(description.width) / image_size.width, - float(description.height) / image_size.height, - }; - spdlog::info("useful size: {}x{} with buffer {}x{}", - description.width, - description.height, - image_size.width, - image_size.height); - - std::array specialization_constants_desc{ - vk::SpecializationMapEntry{ - .constantID = 0, - .offset = 0, - .size = sizeof(float), - }, - vk::SpecializationMapEntry{ - .constantID = 1, - .offset = sizeof(float), - .size = sizeof(float), - }}; - - vk::SpecializationInfo vert_specialization_info; - vert_specialization_info.setMapEntries(specialization_constants_desc); - vert_specialization_info.setData(useful_size); - - std::array constants = { - need_srgb_conversion(guess_model()), - i.alpha(), - }; - std::array frag_specialization_constant_desc = { - vk::SpecializationMapEntry{ - .constantID = 0, - .offset = 0, - .size = sizeof(constants[0]), - }, - vk::SpecializationMapEntry{ - .constantID = 1, - .offset = sizeof(constants[0]), - .size = sizeof(constants[1]), - }, - }; - vk::SpecializationInfo frag_specialization_info; - frag_specialization_info.setMapEntries(frag_specialization_constant_desc); - frag_specialization_info.setData(constants); - - // Create graphics pipeline - vk::raii::ShaderModule vertex_shader = load_shader(device, "stream.vert"); - vk::raii::ShaderModule fragment_shader = load_shader(device, "stream.frag"); - - vk::PipelineLayoutCreateInfo pipeline_layout_info{ - .setLayoutCount = 1, - .pSetLayouts = &*i.descriptor_set_layout, - }; - - i.blit_pipeline_layout = vk::raii::PipelineLayout(device, pipeline_layout_info); - - vk::pipeline_builder pipeline_info{ - .Stages = {{ - .stage = vk::ShaderStageFlagBits::eVertex, - .module = *vertex_shader, - .pName = "main", - .pSpecializationInfo = &vert_specialization_info, - }, - { - .stage = vk::ShaderStageFlagBits::eFragment, - .module = *fragment_shader, - .pName = "main", - .pSpecializationInfo = &frag_specialization_info, - }}, - .VertexBindingDescriptions = {}, - .VertexAttributeDescriptions = {}, - .InputAssemblyState = {{ - .topology = vk::PrimitiveTopology::eTriangleStrip, - }}, - // With vk::DynamicState::eViewport, vk::DynamicState::eScissor the number of viewports - // and scissors is still used, put a vector with one element - .Viewports = {{}}, - .Scissors = {{}}, - .RasterizationState = {{ - .polygonMode = vk::PolygonMode::eFill, - .lineWidth = 1, - }}, - .MultisampleState = {{ - .rasterizationSamples = vk::SampleCountFlagBits::e1, - }}, - .ColorBlendAttachments = { - {.colorWriteMask = i.alpha() ? vk::ColorComponentFlagBits::eA - : vk::ColorComponentFlagBits::eA | vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB}}, - .DynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor}, - .layout = *i.blit_pipeline_layout, - .renderPass = *blit_render_pass, - .subpass = 0, - }; - - i.blit_pipeline = vk::raii::Pipeline(device, application::get_pipeline_cache(), pipeline_info); - } + application::pop_scene(); } + assert(swapchain); if (device.waitForFences(*fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout) throw std::runtime_error("Vulkan fence timeout"); @@ -928,11 +811,13 @@ void scenes::stream::render(const XrFrameState & frame_state) std::array image_indices; +#if WIVRN_FEATURE_RENDERDOC + renderdoc_begin(*vk_instance); +#endif command_buffer.reset(); - - vk::CommandBufferBeginInfo begin_info; - begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; - command_buffer.begin(begin_info); + command_buffer.begin(vk::CommandBufferBeginInfo{ + .flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit, + }); // Keep a reference to the resources needed to blit the images until vkWaitForFences @@ -947,13 +832,12 @@ void scenes::stream::render(const XrFrameState & frame_state) std::array foveation{}; bool use_alpha = false; - // Blit images from the decoders - for (auto [i, blit_handle]: std::views::zip(decoders, current_blit_handles)) + for (auto & blit_handle: current_blit_handles) { - if (not blit_handle or not *i.blit_pipeline) + if (not blit_handle) continue; - blit_handle->feedback.blitted = application::now(); + blit_handle->feedback.blitted = instance.now(); if (blit_handle->feedback.blitted - blit_handle->feedback.received_from_decoder > 1'000'000'000) state_ = stream::state::stalled; ++blit_handle->feedback.times_displayed; @@ -964,27 +848,12 @@ void scenes::stream::render(const XrFrameState & frame_state) foveation = blit_handle->view_info.foveation; use_alpha = blit_handle->view_info.alpha; - vk::DescriptorImageInfo image_info{ - .imageView = *blit_handle->image_view, - .imageLayout = vk::ImageLayout::eGeneral, - }; - - vk::WriteDescriptorSet descriptor_write{ - .dstSet = i.descriptor_set, - .dstBinding = 0, - .dstArrayElement = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = &image_info, - }; - - device.updateDescriptorSets(descriptor_write, {}); - if (*blit_handle->current_layout != vk::ImageLayout::eGeneral) + if (blit_handle->current_layout == vk::ImageLayout::eUndefined) { vk::ImageMemoryBarrier barrier{ .srcAccessMask = vk::AccessFlagBits::eNone, .dstAccessMask = vk::AccessFlagBits::eMemoryRead, - .oldLayout = *blit_handle->current_layout, + .oldLayout = vk::ImageLayout::eUndefined, .newLayout = vk::ImageLayout::eGeneral, .image = blit_handle->image, .subresourceRange = { @@ -995,72 +864,22 @@ void scenes::stream::render(const XrFrameState & frame_state) }; command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {}, {}, {}, barrier); - *blit_handle->current_layout = vk::ImageLayout::eGeneral; + blit_handle->current_layout = vk::ImageLayout::eGeneral; } } - uint16_t x_offset = 0; - for (auto & out: decoder_output) + // Blit images from the decoders + std::array blitted; + for (auto [i, b]: utils::enumerate(blitters)) { - command_buffer.beginRenderPass( - { - .renderPass = *blit_render_pass, - .framebuffer = *out.frame_buffer, - .renderArea = { - .offset = {0, 0}, - .extent = decoder_out_size, - }, - .clearValueCount = 0, - }, - vk::SubpassContents::eInline); - - for (const auto & decoder: decoders) + b.begin(command_buffer); + for (auto [j, blit_handle]: utils::enumerate(current_blit_handles)) { - if (not *decoder.blit_pipeline) + if (not blit_handle) continue; - if (decoder.alpha() and not use_alpha) - continue; - - command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *decoder.blit_pipeline); - - const auto & description = decoder.decoder->desc(); - int x0 = description.offset_x - x_offset; - int y0 = description.offset_y; - int x1 = x0 + description.width * description.subsampling; - int y1 = y0 + description.height * description.subsampling; - - vk::Viewport viewport{ - .x = (float)x0, - .y = (float)y0, - .width = float(description.width * description.subsampling), - .height = float(description.height * description.subsampling), - .minDepth = 0, - .maxDepth = 1, - }; - - x0 = std::clamp(x0, 0, decoder_out_size.width); - x1 = std::clamp(x1, 0, decoder_out_size.width); - y0 = std::clamp(y0, 0, decoder_out_size.height); - y1 = std::clamp(y1, 0, decoder_out_size.height); - - vk::Rect2D scissor{ - .offset = {.x = x0, .y = y0}, - .extent = {.width = (uint32_t)(x1 - x0), .height = (uint32_t)(y1 - y0)}, - }; - - command_buffer.setViewport(0, viewport); - command_buffer.setScissor(0, scissor); - - command_buffer.bindDescriptorSets( - vk::PipelineBindPoint::eGraphics, - *decoder.blit_pipeline_layout, - 0, - decoder.descriptor_set, - nullptr); - command_buffer.draw(3, 1, 0, 0); + b.push_image(command_buffer, j, decoders[j].decoder->sampler(), decoders[j].decoder->extent(), blit_handle->image_view, blit_handle->current_layout); } - command_buffer.endRenderPass(); - x_offset += decoder_out_size.width; + blitted[i] = b.end(command_buffer); } command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1); @@ -1071,7 +890,7 @@ void scenes::stream::render(const XrFrameState & frame_state) int32_t max_height = 0; for (size_t i = 0; i < view_count; ++i) { - extents[i] = reprojector->defoveated_size(foveation[i]); + extents[i] = defoveator->defoveated_size(foveation[i]); max_width = std::max(max_width, extents[i].width); max_height = std::max(max_height, extents[i].height); } @@ -1101,7 +920,7 @@ void scenes::stream::render(const XrFrameState & frame_state) // defoveate the image int image_index = swapchain.acquire(); swapchain.wait(); - reprojector->reproject(command_buffer, foveation, image_index); + defoveator->defoveate(command_buffer, foveation, blitted, image_index); command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 2); @@ -1109,6 +928,9 @@ void scenes::stream::render(const XrFrameState & frame_state) vk::SubmitInfo submit_info; submit_info.setCommandBuffers(*command_buffer); queue.lock()->submit(submit_info, *fence); +#if WIVRN_FEATURE_RENDERDOC + renderdoc_end(*vk_instance); +#endif swapchain.release(); std::vector layer_view(view_count); @@ -1275,119 +1097,15 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript } video_stream_description = description; - - const uint32_t video_width = description.width / view_count; - const uint32_t video_height = description.height; - - // Create renderpass - { - vk::AttachmentDescription color_desc{ - .format = vk::Format::eA8B8G8R8SrgbPack32, - .samples = vk::SampleCountFlagBits::e1, - .loadOp = vk::AttachmentLoadOp::eDontCare, - .storeOp = vk::AttachmentStoreOp::eStore, - .initialLayout = vk::ImageLayout::eUndefined, - .finalLayout = vk::ImageLayout::eShaderReadOnlyOptimal, - }; - - vk::AttachmentReference color_ref{ - .attachment = 0, - .layout = vk::ImageLayout::eColorAttachmentOptimal, - }; - - vk::SubpassDescription subpass{ - .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, - }; - subpass.setColorAttachments(color_ref); - - vk::RenderPassCreateInfo renderpass_info{ - .flags = {}, - }; - renderpass_info.setAttachments(color_desc); - renderpass_info.setSubpasses(subpass); - - blit_render_pass = vk::raii::RenderPass(device, renderpass_info); - } - - // Create outputs for the decoders - decoder_out_size = vk::Extent2D{video_width, video_height}; - { - decoder_out_format = vk::Format::eA8B8G8R8SrgbPack32; - - vk::ImageCreateInfo image_info{ - .flags = vk::ImageCreateFlags{}, - .imageType = vk::ImageType::e2D, - .format = vk::Format::eA8B8G8R8SrgbPack32, - .extent = {video_width, video_height, 1}, - .mipLevels = 1, - .arrayLayers = view_count, - .samples = vk::SampleCountFlagBits::e1, - .tiling = vk::ImageTiling::eOptimal, - .usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment, - .sharingMode = vk::SharingMode::eExclusive, - .initialLayout = vk::ImageLayout::eUndefined, - }; - - VmaAllocationCreateInfo alloc_info{ - .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - }; - - decoder_out_image = image_allocation{device, image_info, alloc_info}; - - vk::ImageViewCreateInfo image_view_info{ - .image = vk::Image{decoder_out_image}, - .viewType = vk::ImageViewType::e2D, - .format = vk::Format::eA8B8G8R8SrgbPack32, - .components = {}, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }; - - for (uint32_t view = 0; view < view_count; ++view) - { - auto & output = decoder_output[view]; - - image_view_info.subresourceRange.baseArrayLayer = view; - output.image_view = vk::raii::ImageView(device, image_view_info); - - output.frame_buffer = vk::raii::Framebuffer( - device, - vk::FramebufferCreateInfo{ - .renderPass = *blit_render_pass, - .attachmentCount = 1, - .pAttachments = &*output.image_view, - .width = decoder_out_size.width, - .height = decoder_out_size.height, - .layers = 1, - }); - } - } - - { - vk::DescriptorPoolSize pool_size{ - .type = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = uint32_t(2 * description.items.size()), - }; - blit_descriptor_pool = vk::raii::DescriptorPool( - device, - vk::DescriptorPoolCreateInfo{ - .maxSets = uint32_t(2 * description.items.size()), - .poolSizeCount = 1, - .pPoolSizes = &pool_size, - }); - } + for (auto & b: blitters) + b.reset(description); for (const auto & [stream_index, item]: utils::enumerate(description.items)) { spdlog::info("Creating decoder size {}x{} offset {},{}", item.width, item.height, item.offset_x, item.offset_y); decoders.push_back(accumulator_images{ - .decoder = std::make_unique(device, physical_device, item, description.fps, shared_from_this(), stream_index), + .decoder = std::make_unique(device, physical_device, instance, item, description.fps, shared_from_this(), stream_index), }); } } @@ -1400,15 +1118,6 @@ void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint const uint32_t video_width = video_stream_description->width / view_count; const uint32_t video_height = video_stream_description->height; - const configuration::sgsr_settings sgsr = application::get_config().sgsr; - if (sgsr.enabled) - { - const float upscaling_factor = sgsr.upscaling_factor; - spdlog::info("Using SGSR with an upscale factor of {}", upscaling_factor); - swapchain_width *= upscaling_factor; - swapchain_height *= upscaling_factor; - } - auto views = system.view_configuration_views(viewconfig); swapchain = xr::swapchain(session, device, swapchain_format, swapchain_width, swapchain_height, 1, views.size()); @@ -1425,12 +1134,9 @@ void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint for (auto & image: swapchain.images()) swapchain_images.push_back(image.image); - reprojector.emplace( + defoveator.emplace( device, physical_device, - decoder_out_image, - vk::Extent2D{.width = video_width, .height = video_height}, - 2, swapchain_images, extent, swapchain.format()); diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 6f506ab7..64cafea0 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -23,8 +23,9 @@ #include "decoder/shard_accumulator.h" #include "render/imgui_impl.h" #include "scene.h" +#include "scenes/blitter.h" #include "scenes/input_profile.h" -#include "stream_reprojection.h" +#include "stream_defoveator.h" #include "utils/thread_safe.h" #include "wifi_lock.h" #include "wivrn_client.h" @@ -48,6 +49,13 @@ public: }; static const size_t image_buffer_size = 3; + struct app + { + std::string id; + std::string name; + std::vector image; + }; + private: static const size_t view_count = 2; @@ -56,16 +64,12 @@ private: struct accumulator_images { std::unique_ptr decoder; - vk::raii::DescriptorSetLayout descriptor_set_layout = nullptr; - vk::DescriptorSet descriptor_set = nullptr; - vk::raii::PipelineLayout blit_pipeline_layout = nullptr; - vk::raii::Pipeline blit_pipeline = nullptr; - // latest frames from oldest to most recent + // latest frames, rolling buffer std::array, image_buffer_size> latest_frames; std::shared_ptr frame(uint64_t id) const; bool alpha() const; - std::vector frames() const; + bool empty() const; }; wifi_lock::wifi wifi; @@ -77,9 +81,9 @@ private: std::unique_ptr network_session; std::atomic exiting = false; std::thread network_thread; - std::mutex tracking_control_mutex; - to_headset::tracking_control tracking_control{}; + thread_safe tracking_control{}; std::array, 2> interaction_profiles; // left and right hand + std::atomic interaction_profile_changed = false; std::atomic recenter_requested = false; std::atomic display_time_phase = 0; std::atomic display_time_period = 0; @@ -90,21 +94,10 @@ private: std::shared_mutex decoder_mutex; std::optional video_stream_description; std::vector decoders; // Locked by decoder_mutex - vk::raii::DescriptorPool blit_descriptor_pool = nullptr; - vk::raii::RenderPass blit_render_pass = nullptr; - vk::Extent2D decoder_out_size; - vk::Format decoder_out_format; - image_allocation decoder_out_image; + std::array blitters; - struct renderpass_output - { - vk::raii::ImageView image_view = nullptr; - vk::raii::Framebuffer frame_buffer = nullptr; - }; - std::array decoder_output; - - std::optional reprojector; + std::optional defoveator; vk::raii::Fence fence = nullptr; vk::raii::CommandBuffer command_buffer = nullptr; @@ -125,6 +118,8 @@ private: std::optional