diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index e03ba258..b9417e68 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -64,8 +64,7 @@ body: attributes: label: Vulkan Info description: Provide the output of `vulkaninfo --summary` command. - render: text - placeholder: Attach the output as a file here. + placeholder: Add the output of vulkaninfo command here... - type: dropdown id: hmd @@ -91,5 +90,4 @@ body: attributes: label: ADB Logs description: Provide the output of `adb logcat` command. - render: plain - placeholder: Attach the output of adb logcat as a file. + placeholder: Add the output of adb logcat command here... diff --git a/CMakeLists.txt b/CMakeLists.txt index 6842a8fb..585c3434 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -43,12 +43,12 @@ option(WIVRN_USE_X264 "Enable x264 software encoder" ON) option(WIVRN_USE_PIPEWIRE "Enable pipewire backend" ON) option(WIVRN_USE_PULSEAUDIO "Enable pulseaudio backend" OFF) -set(OVR_COMPAT_SEARCH_PATH "/opt/xrizer:/usr/local/lib/OpenComposite:/usr/lib/OpenComposite:/opt/OpenComposite:/opt/opencomposite" +set(OVR_COMPAT_SEARCH_PATH "/usr/local/lib/OpenComposite:/usr/lib/OpenComposite:/opt/OpenComposite:/opt/opencomposite:/opt/xrizer" CACHE STRING "List of places to search for the OpenVR compatibility layer, separated by :") option(WIVRN_FEATURE_DEBUG_GUI "Enable Monado debug GUI" OFF) option(WIVRN_FEATURE_RENDERDOC "Support renderdoc" OFF) -set(WIVRN_FEATURE_SOLARXR OFF) # Will be added back when merged in upstream Monado +option(WIVRN_FEATURE_SOLARXR "Enable SolarXR driver" OFF) option(WIVRN_FEATURE_STEAMVR_LIGHTHOUSE "Enable SteamVR Lighthouse driver" OFF) option(WIVRN_CHECK_CAPSYSNICE "Check if CAP_SYS_NICE is available at startup" ON) diff --git a/client/application.cpp b/client/application.cpp index 50d77654..b0433274 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,7 +26,6 @@ #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" @@ -68,6 +67,7 @@ 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,7 +134,8 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/facebook/touch_controller_pro", - .required_extensions = {XR_FB_TOUCH_CONTROLLER_PRO_EXTENSION_NAME}, + .required_extensions = {"XR_FB_touch_controller_pro"}, + .max_version = XR_MAKE_VERSION(1, 1, 0), .input_sources = { "/user/hand/left/output/haptic", "/user/hand/left/output/haptic_trigger_fb", @@ -246,7 +247,8 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/meta/touch_controller_plus", - .required_extensions = {XR_META_TOUCH_CONTROLLER_PLUS_EXTENSION_NAME}, + .required_extensions = {"XR_META_touch_controller_plus"}, + .max_version = XR_MAKE_VERSION(1, 1, 0), .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -647,7 +649,6 @@ VkBool32 application::vulkan_debug_report_callback( } #ifndef NDEBUG - bool my_error = true; if (level >= spdlog::level::warn) { bool validation_layer_found = false; @@ -658,13 +659,10 @@ VkBool32 application::vulkan_debug_report_callback( if (validation_layer_found && i.library != "libVkLayer_khronos_validation.so") spdlog::log(level, "{:#016x}: {} + {:#x}", i.pc, i.library, i.pc - i.library_base); - - if (i.library == "libopenxr_loader.so") - my_error = false; } } - if (level >= spdlog::level::err and my_error) + if (level >= spdlog::level::err) abort(); #endif @@ -969,8 +967,7 @@ void application::initialize_actions() std::vector sources; for (auto & profile: interaction_profiles) { - profile.available = std::ranges::all_of(profile.required_extensions, [&](auto & ext) { return xr_instance.has_extension(ext); }) and - profile.min_version <= api_version; + profile.available = utils::contains_all(xr_extensions, profile.required_extensions) and profile.min_version <= api_version and profile.max_version > api_version; if (profile.profile_name.ends_with("khr/simple_controller")) { @@ -1351,47 +1348,50 @@ 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 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 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(); + auto & facet = std::use_facet(loc); + messages_info.language = facet.language(); + messages_info.country = facet.country(); + messages_info.encoding = "UTF-8"; #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 = open_locale_file; + 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; + }; + loc = std::locale(loc, boost::locale::gnu_gettext::create_messages_facet(messages_info)); std::locale::global(loc); diff --git a/client/configuration.cpp b/client/configuration.cpp index 6698a9c9..abe7f15e 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["enable_stream_gui"]; val.is_bool()) - enable_stream_gui = val.get_bool(); + if (auto val = root["sgsr"]; val.is_object()) + parse_sgsr_options(val.get_object()); if (auto val = root["openxr_post_processing"]; val.is_object()) parse_openxr_post_processing_options(val.get_object()); @@ -254,9 +254,6 @@ 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) { @@ -267,11 +264,31 @@ 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 = {}; @@ -287,6 +304,17 @@ 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; @@ -329,6 +357,8 @@ 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; @@ -342,6 +372,5 @@ 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 d8dfbf6f..8d34faae 100644 --- a/client/configuration.h +++ b/client/configuration.h @@ -56,7 +56,16 @@ public: bool fb_lower_body = false; bool fb_hip = true; - bool enable_stream_gui = 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{}; // XR_FB_composition_layer_settings extension flags struct openxr_post_processing_settings @@ -74,8 +83,6 @@ public: bool first_run = true; - std::string locale; - bool check_feature(feature f) const; void set_feature(feature f, bool state); @@ -83,6 +90,7 @@ 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/shard_accumulator.h b/client/decoder/shard_accumulator.h index a0145e22..4777de7f 100644 --- a/client/decoder/shard_accumulator.h +++ b/client/decoder/shard_accumulator.h @@ -19,30 +19,27 @@ #pragma once -#include "decoder.h" -#include "wivrn_packets.h" - #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 "wivrn_packets.h" #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; @@ -53,7 +50,7 @@ public: void reset(uint64_t frame_index); bool empty() const; - std::optional insert(data_shard &&, xr::instance & instance); + std::optional insert(data_shard &&); wivrn::from_headset::feedback feedback{}; @@ -73,22 +70,19 @@ 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_(decoder::make(device, physical_device, description, fps, stream_index, scene, this)), + decoder(std::make_shared(device, physical_device, description, fps, stream_index, scene, this)), current(stream_index), next(stream_index), - weak_scene(scene), - instance(instance) + weak_scene(scene) { next.reset(1); } @@ -97,20 +91,20 @@ public: auto & desc() const { - return decoder_->description; + return decoder->desc(); } vk::Sampler sampler() { - return decoder_->sampler(); + return decoder->sampler(); } - const vk::Extent2D extent() + vk::Extent2D image_size() { - return decoder_->extent(); + return decoder->image_size(); } - using blit_handle = decoder::blit_handle; + using blit_handle = decoder_impl::blit_handle; private: void try_submit_frame(std::optional shard_idx); diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index e79c1305..dc20f14e 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -17,9 +17,11 @@ * along with this program. If not, see . */ #include "constants.h" -#include "xr/body_tracker.h" -#include "xr/face_tracker.h" +#include "utils/overloaded.h" +#include "xr/fb_body_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 @@ -38,6 +40,8 @@ #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 @@ -45,11 +49,6 @@ #include #include -#include "wivrn_config.h" -#if WIVRN_FEATURE_RENDERDOC -#include "vk/renderdoc.h" -#endif - using namespace wivrn; // clang-format off @@ -152,8 +151,7 @@ static const std::array supported_depth_formats{ }; scenes::stream::stream() : - scene_impl(supported_color_formats, supported_depth_formats), - blitters{blitter(device, 0), blitter(device, 1)} + scene_impl(supported_color_formats, supported_depth_formats) { } @@ -191,11 +189,7 @@ 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{ - .language = application::get_messages_info().language, - .country = application::get_messages_info().country, - .variant = application::get_messages_info().variant, - }; + from_headset::headset_info_packet info{}; auto view = self->system.view_configuration_views(self->viewconfig)[0]; view = override_view(view, guess_model()); @@ -257,49 +251,46 @@ 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.face_tracking = std::visit(utils::overloaded{ + [](std::monostate &) { + return from_headset::face_type::none; + }, + [](xr::fb_face_tracker2 &) { + return from_headset::face_type::fb2; + }, + [](xr::htc_face_tracker &) { + return from_headset::face_type::htc; + }, + [](xr::pico_face_tracker &) { + return from_headset::face_type::fb2; + }, + }, + application::get_face_tracker()); } info.num_generic_trackers = 0; if (config.check_feature(feature::body_tracking)) { - 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.num_generic_trackers = std::visit(utils::overloaded{ + [&](std::monostate &) { + return size_t(0); + }, + [&](auto & b) { + return b.count(); + }, + }, + application::get_body_tracker()); } info.palm_pose = application::space(xr::spaces::palm_left) or application::space(xr::spaces::palm_right); - info.passthrough = self->system.passthrough_supported() != xr::passthrough_type::none; + info.passthrough = self->system.passthrough_supported() != xr::system::passthrough_type::no_passthrough; 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::supported_codecs(); + info.supported_codecs = decoder_impl::supported_codecs(); return info; }()); @@ -320,6 +311,15 @@ 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 = self->instance.string_to_path(path), + .path = application::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, application::queue_family_index(), renderer->get_default_material()); std::string profile = controller_name(); input.emplace( @@ -470,11 +470,8 @@ void scenes::stream::on_focused() swapchain_imgui, std::vector{vp}); - 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; - } + 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; @@ -497,8 +494,6 @@ void scenes::stream::on_unfocused() loader.reset(); renderer.reset(); clear_swapchains(); - left_hand.reset(); - right_hand.reset(); imgui_ctx.reset(); swapchain_imgui = xr::swapchain(); @@ -529,16 +524,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 = instance.now(); + handle->feedback.received_from_decoder = application::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.empty(); + return i.alpha() or not i.frames().empty(); })) { state_ = state::streaming; - spdlog::info("Stream scene ready at t={}", instance.now()); + spdlog::info("Stream scene ready at t={}", application::now()); } } @@ -553,14 +548,15 @@ bool scenes::stream::accumulator_images::alpha() const return decoder->desc().channels == wivrn::to_headset::video_stream_description::channels_t::alpha; } -bool scenes::stream::accumulator_images::empty() const +std::vector scenes::stream::accumulator_images::frames() const { + std::vector result; for (const auto & frame: latest_frames) { if (frame) - return false; + result.push_back(frame->feedback.frame_index); } - return true; + return result; } std::vector> scenes::stream::common_frame(XrTime display_time) @@ -770,17 +766,138 @@ void scenes::stream::render(const XrFrameState & frame_state) } if (state_ == state::stalled) - { - 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, - }); - 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, + }; + + 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); + } + } + if (device.waitForFences(*fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout) throw std::runtime_error("Vulkan fence timeout"); @@ -811,13 +928,11 @@ void scenes::stream::render(const XrFrameState & frame_state) std::array image_indices; -#if WIVRN_FEATURE_RENDERDOC - renderdoc_begin(*vk_instance); -#endif command_buffer.reset(); - command_buffer.begin(vk::CommandBufferBeginInfo{ - .flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit, - }); + + vk::CommandBufferBeginInfo begin_info; + begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; + command_buffer.begin(begin_info); // Keep a reference to the resources needed to blit the images until vkWaitForFences @@ -832,12 +947,13 @@ void scenes::stream::render(const XrFrameState & frame_state) std::array foveation{}; bool use_alpha = false; - for (auto & blit_handle: current_blit_handles) + // Blit images from the decoders + for (auto [i, blit_handle]: std::views::zip(decoders, current_blit_handles)) { - if (not blit_handle) + if (not blit_handle or not *i.blit_pipeline) continue; - blit_handle->feedback.blitted = instance.now(); + blit_handle->feedback.blitted = application::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; @@ -848,12 +964,27 @@ void scenes::stream::render(const XrFrameState & frame_state) foveation = blit_handle->view_info.foveation; use_alpha = blit_handle->view_info.alpha; - if (blit_handle->current_layout == vk::ImageLayout::eUndefined) + 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) { vk::ImageMemoryBarrier barrier{ .srcAccessMask = vk::AccessFlagBits::eNone, .dstAccessMask = vk::AccessFlagBits::eMemoryRead, - .oldLayout = vk::ImageLayout::eUndefined, + .oldLayout = *blit_handle->current_layout, .newLayout = vk::ImageLayout::eGeneral, .image = blit_handle->image, .subresourceRange = { @@ -864,22 +995,72 @@ 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; } } - // Blit images from the decoders - std::array blitted; - for (auto [i, b]: utils::enumerate(blitters)) + uint16_t x_offset = 0; + for (auto & out: decoder_output) { - b.begin(command_buffer); - for (auto [j, blit_handle]: utils::enumerate(current_blit_handles)) + 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) { - if (not blit_handle) + if (not *decoder.blit_pipeline) continue; - b.push_image(command_buffer, j, decoders[j].decoder->sampler(), decoders[j].decoder->extent(), blit_handle->image_view, blit_handle->current_layout); + 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); } - blitted[i] = b.end(command_buffer); + command_buffer.endRenderPass(); + x_offset += decoder_out_size.width; } command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1); @@ -890,7 +1071,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] = defoveator->defoveated_size(foveation[i]); + extents[i] = reprojector->defoveated_size(foveation[i]); max_width = std::max(max_width, extents[i].width); max_height = std::max(max_height, extents[i].height); } @@ -920,7 +1101,7 @@ void scenes::stream::render(const XrFrameState & frame_state) // defoveate the image int image_index = swapchain.acquire(); swapchain.wait(); - defoveator->defoveate(command_buffer, foveation, blitted, image_index); + reprojector->reproject(command_buffer, foveation, image_index); command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 2); @@ -928,9 +1109,6 @@ 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); @@ -1097,15 +1275,119 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript } video_stream_description = description; - for (auto & b: blitters) - b.reset(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 (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, instance, item, description.fps, shared_from_this(), stream_index), + .decoder = std::make_unique(device, physical_device, item, description.fps, shared_from_this(), stream_index), }); } } @@ -1118,6 +1400,15 @@ 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()); @@ -1134,9 +1425,12 @@ void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint for (auto & image: swapchain.images()) swapchain_images.push_back(image.image); - defoveator.emplace( + reprojector.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 64cafea0..6f506ab7 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -23,9 +23,8 @@ #include "decoder/shard_accumulator.h" #include "render/imgui_impl.h" #include "scene.h" -#include "scenes/blitter.h" #include "scenes/input_profile.h" -#include "stream_defoveator.h" +#include "stream_reprojection.h" #include "utils/thread_safe.h" #include "wifi_lock.h" #include "wivrn_client.h" @@ -49,13 +48,6 @@ 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; @@ -64,12 +56,16 @@ private: struct accumulator_images { std::unique_ptr decoder; - // latest frames, rolling buffer + 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 std::array, image_buffer_size> latest_frames; std::shared_ptr frame(uint64_t id) const; bool alpha() const; - bool empty() const; + std::vector frames() const; }; wifi_lock::wifi wifi; @@ -81,9 +77,9 @@ private: std::unique_ptr network_session; std::atomic exiting = false; std::thread network_thread; - thread_safe tracking_control{}; + std::mutex tracking_control_mutex; + to_headset::tracking_control 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; @@ -94,10 +90,21 @@ 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; - std::array blitters; + vk::Extent2D decoder_out_size; + vk::Format decoder_out_format; + image_allocation decoder_out_image; - std::optional defoveator; + struct renderpass_output + { + vk::raii::ImageView image_view = nullptr; + vk::raii::Framebuffer frame_buffer = nullptr; + }; + std::array decoder_output; + + std::optional reprojector; vk::raii::Fence fence = nullptr; vk::raii::CommandBuffer command_buffer = nullptr; @@ -118,8 +125,6 @@ private: std::optional