Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Vindicus999
2026-01-29 23:53:28 +00:00
48 changed files with 1249 additions and 788 deletions
-2
View File
@@ -228,8 +228,6 @@ if (WIVRN_BUILD_WIVRNCTL)
endif()
# Common dependencies
FetchContent_Declare(boostpfr EXCLUDE_FROM_ALL SYSTEM URL https://github.com/boostorg/pfr/archive/refs/tags/2.2.0.tar.gz
URL_HASH SHA256=6f490ec1383de5855dcf801c23f0a967f888eb6e1440b6ca0bf36c12d4ae7ac7)
FetchContent_Declare(boost EXCLUDE_FROM_ALL SYSTEM URL https://github.com/boostorg/boost/releases/download/boost-1.89.0/boost-1.89.0-cmake.tar.xz
URL_HASH SHA256=67acec02d0d118b5de9eb441f5fb707b3a1cdd884be00ca24b9a73c995511f74)
+1
View File
@@ -200,6 +200,7 @@ public:
void operator()(to_headset::haptics &&);
void operator()(to_headset::timesync_query &&);
void operator()(to_headset::tracking_control &&);
void operator()(to_headset::feature_control &&);
void operator()(to_headset::audio_stream_description &&);
void operator()(to_headset::video_stream_description &&);
void operator()(to_headset::refresh_rate_change &&);
+3 -9
View File
@@ -338,13 +338,10 @@ void scenes::stream::gui_performance_metrics()
ImPlot::PopStyleColor(5);
{
ImGui::Text(
"%s",
ImGui::TextUnformatted(
fmt::format(
_F("Estimated motion to photons latency: {}ms"),
std::chrono::duration_cast<std::chrono::milliseconds>(
tracking_control.lock()->max_offset)
.count())
tracking_control.lock()->motions_to_photons / 1'000'000)
.c_str());
if (is_gui_interactable())
@@ -373,10 +370,7 @@ void scenes::stream::gui_compact_view()
f(_S("CPU time"), compact_cpu_time * 1000, "ms");
f(_S("GPU time"), compact_gpu_time * 1000, "ms");
f(_S("Motion to photon latency"),
std::chrono::duration_cast<std::chrono::microseconds>(
tracking_control.lock()->max_offset)
.count() *
1e-3f,
tracking_control.lock()->motions_to_photons / 1'000'000.f,
"ms");
ImGui::EndTable();
}
+13
View File
@@ -59,6 +59,19 @@ void scenes::stream::operator()(to_headset::video_stream_data_shard && shard)
decoders[idx].decoder->push_shard(std::move(shard));
}
void scenes::stream::operator()(to_headset::feature_control && control)
{
switch (control.f)
{
case wivrn::to_headset::feature_control::hid_input:
hid_forwarding = control.state;
return;
case wivrn::to_headset::feature_control::microphone:
if (audio_handle)
audio_handle->set_mic_state(control.state);
return;
}
}
void scenes::stream::operator()(to_headset::audio_stream_description && desc)
{
audio_handle.emplace(desc, *network_session, instance);
+223 -267
View File
@@ -26,6 +26,7 @@
#include "xr/fb_body_tracker.h"
#include "xr/to_string.h"
#include <magic_enum.hpp>
#include <magic_enum_containers.hpp>
#include <ranges>
#include <spdlog/spdlog.h>
#include <thread>
@@ -34,11 +35,6 @@
#include "android/battery.h"
#endif
using tid = to_headset::tracking_control::id;
static const XrDuration min_tracking_period = 2'000'000;
static const XrDuration max_tracking_period = 5'000'000;
static uint8_t cast_flags(XrSpaceLocationFlags location, XrSpaceVelocityFlags velocity)
{
uint8_t flags = 0;
@@ -65,19 +61,6 @@ static uint8_t cast_flags(XrSpaceLocationFlags location, XrSpaceVelocityFlags ve
namespace
{
class timer
{
xr::instance & instance;
XrTime start = instance.now();
public:
timer(xr::instance & instance) :
instance(instance) {}
XrDuration count()
{
return instance.now() - start;
}
};
from_headset::tracking::pose locate_space(device_id device, XrSpace space, XrSpace reference, XrTime time)
{
@@ -148,6 +131,8 @@ public:
std::vector<from_headset::tracking::pose> & out)
{
assert(devices.size() == spaces.size());
if (devices.empty())
return;
if (locate_spaces)
{
locations.resize(spaces.size());
@@ -293,7 +278,9 @@ void scenes::stream::tracking()
const XrDuration battery_check_interval = 30'000'000'000; // 30s
#endif
std::vector<std::pair<device_id, XrSpace>> spaces;
magic_enum::containers::array<device_id, XrSpace> spaces{};
const auto & config = application::get_config();
{
std::vector ids{
@@ -311,80 +298,27 @@ void scenes::stream::tracking()
ids.insert(ids.end(), {device_id::LEFT_PINCH_POSE, device_id::LEFT_POKE, device_id::RIGHT_PINCH_POSE, device_id::RIGHT_POKE});
}
if (config.check_feature(feature::eye_gaze))
ids.emplace_back(device_id::EYE_GAZE);
for (auto id: ids)
{
if (XrSpace space = application::space(device_to_space(id)))
spaces.emplace_back(id, space);
spaces[id] = space;
else
spdlog::warn("Missing space for device {}", magic_enum::enum_name(id));
}
}
auto enabled = [&](const to_headset::tracking_control & control, device_id id) -> bool {
if (is_gui_interactable())
{
switch (id)
{
case device_id::HEAD:
case device_id::EYE_GAZE:
return true;
default:
return false;
}
}
switch (id)
{
case device_id::HEAD:
case device_id::EYE_GAZE:
return true;
case device_id::LEFT_AIM:
return control.enabled[size_t(tid::left_aim)];
case device_id::LEFT_GRIP:
return control.enabled[size_t(tid::left_grip)];
case device_id::LEFT_PALM:
return control.enabled[size_t(tid::left_palm)];
case device_id::LEFT_PINCH_POSE:
return control.enabled[size_t(tid::left_pinch)];
case device_id::LEFT_POKE:
return control.enabled[size_t(tid::left_poke)];
case device_id::RIGHT_AIM:
return control.enabled[size_t(tid::right_aim)];
case device_id::RIGHT_GRIP:
return control.enabled[size_t(tid::right_grip)];
case device_id::RIGHT_PALM:
return control.enabled[size_t(tid::right_palm)];
case device_id::RIGHT_PINCH_POSE:
return control.enabled[size_t(tid::right_pinch)];
case device_id::RIGHT_POKE:
return control.enabled[size_t(tid::right_poke)];
default:
break;
}
throw std::runtime_error("enabled called on unhandled device " + std::string(magic_enum::enum_name(id)));
};
const auto & config = application::get_config();
if (config.check_feature(feature::eye_gaze))
spaces.push_back({device_id::EYE_GAZE, application::space(xr::spaces::eye_gaze)});
XrSpace view_space = application::space(xr::spaces::view);
XrSpace world_space = application::space(xr::spaces::world);
XrDuration tracking_period = min_tracking_period; // target period for 20% busy time
XrDuration current_tracking_period = tracking_period; // divider of frame period
int period_adjust = 0;
XrTime t0 = instance.now();
XrTime last_hand_sample = t0;
XrTime last_body_sample = t0;
std::vector<from_headset::tracking> tracking;
std::vector<from_headset::tracking> tracking_pool; // pre-allocated objects
from_headset::tracking tracking;
std::vector<from_headset::hand_tracking> hands;
std::vector<from_headset::body_tracking> body;
std::vector<XrView> views;
std::vector<from_headset::trackings> merged_tracking;
std::vector<serialization_packet> packets;
const bool hand_tracking = config.check_feature(feature::hand_tracking);
@@ -401,173 +335,238 @@ void scenes::stream::tracking()
on_interaction_profile_changed({});
decltype(to_headset::tracking_control::pattern) pattern;
size_t pattern_position = 0;
XrDuration frame_duration;
XrTime pattern_begin = instance.now();
while (not exiting)
{
try
{
tracking.clear();
if (pattern_position == pattern.size())
{
// Upper limit to 200FPS
frame_duration = std::max<XrDuration>(5'000'000, display_time_period);
// Wait for next frame
XrTime now = instance.now();
pattern_begin = display_time_phase + (std::max(pattern_begin + frame_duration, now) / frame_duration) * frame_duration;
std::this_thread::sleep_for(std::chrono::nanoseconds(pattern_begin - now));
pattern_position = 0;
// Check if a new pattern has been received
if (auto locked = tracking_control.lock(); pattern.empty() or not locked->pattern.empty())
{
pattern.clear();
std::swap(pattern, locked->pattern);
pattern_position = 0;
// Ensure head tracking is always done
if (not std::ranges::contains(pattern, device_id::HEAD, &to_headset::tracking_control::sample::device))
pattern.push_back({.device = device_id::HEAD});
// FIXME: eye tracking shouldn't had a special case
// eye-tracked foveation needs eye and head pose in the same tracking packet
if (spaces[device_id::EYE_GAZE])
{
size_t sz = pattern.size();
for (size_t i = 0; i < sz; ++i)
{
if (pattern[i].device == device_id::HEAD)
pattern.push_back({
.device = device_id::EYE_GAZE,
.prediction_ns = pattern[i].prediction_ns,
});
}
}
if (hand_tracking)
{
if (std::ranges::contains(pattern, device_id::LEFT_HAND, &to_headset::tracking_control::sample::device))
{
if (not left_hand)
left_hand = session.create_hand_tracker(XR_HAND_LEFT_EXT);
}
else
left_hand.reset();
if (std::ranges::contains(pattern, device_id::RIGHT_HAND, &to_headset::tracking_control::sample::device))
{
if (not right_hand)
right_hand = session.create_hand_tracker(XR_HAND_RIGHT_EXT);
}
else
right_hand.reset();
}
if (face_tracking)
{
if (std::ranges::contains(pattern, device_id::FACE, &to_headset::tracking_control::sample::device))
{
if (std::holds_alternative<std::monostate>(face_tracker))
face_tracker = xr::make_face_tracker(instance, system, session);
}
else
face_tracker.emplace<std::monostate>();
}
if (body_tracking)
{
if (std::ranges::contains(pattern, device_id::BODY, &to_headset::tracking_control::sample::device))
{
if (std::holds_alternative<std::monostate>(body_tracker))
body_tracker = xr::make_body_tracker(
instance,
system,
session,
application::get_generic_trackers(),
config.fb_lower_body,
config.fb_hip);
}
else
body_tracker.emplace<std::monostate>();
}
std::ranges::sort(pattern, std::less{}, [frame_duration](const auto & i) { return -i.prediction_ns % frame_duration; });
spdlog::info("Tracking pattern ({}µs):", frame_duration / 1'000);
for (const auto & [device, pred]: pattern)
{
spdlog::info("\tt+{}µs {} ({}µs)",
(frame_duration - (pred % frame_duration)) / 1'000,
magic_enum::enum_name(device),
pred / 1'000);
}
}
}
hands.clear();
body.clear();
XrTime now = instance.now();
if (now < t0)
XrTime t0 = pattern_begin + frame_duration - (pattern[pattern_position].prediction_ns % frame_duration);
if (t0 > now + 500)
std::this_thread::sleep_for(std::chrono::nanoseconds(t0 - now));
// If thread can't keep up, skip timestamps
t0 = std::max(t0, now);
timer t(instance);
int samples = 0;
auto control = *tracking_control.lock();
bool interaction_profile_changed = this->interaction_profile_changed.exchange(false);
if (control.enabled[size_t(tid::left_hand)])
{
if (not left_hand and system.hand_tracking_supported())
left_hand = session.create_hand_tracker(XR_HAND_LEFT_EXT);
}
else
left_hand.reset();
if (control.enabled[size_t(tid::right_hand)])
{
if (not right_hand and system.hand_tracking_supported())
right_hand = session.create_hand_tracker(XR_HAND_RIGHT_EXT);
}
else
right_hand.reset();
if (face_tracking and control.enabled[size_t(tid::face)])
{
if (std::holds_alternative<std::monostate>(face_tracker))
face_tracker = xr::make_face_tracker(instance, system, session);
}
else
face_tracker.emplace<std::monostate>();
if (body_tracking and control.enabled[size_t(tid::generic_tracker)])
{
if (std::holds_alternative<std::monostate>(body_tracker))
body_tracker = xr::make_body_tracker(
instance,
system,
session,
application::get_generic_trackers(),
config.fb_lower_body,
config.fb_hip);
}
else
body_tracker.emplace<std::monostate>();
if (interaction_profile_changed)
if (auto htc = std::get_if<xr::htc_body_tracker>(&body_tracker))
htc->update_active();
XrDuration prediction = std::clamp<XrDuration>(control.max_offset.count(), 0, 80'000'000);
auto period = std::max<XrDuration>(display_time_period.load(), 1'000'000);
for (XrDuration Δt = display_time_phase - t0 % period + (control.min_offset.count() / period) * period;
Δt <= prediction + period / 2;
Δt += period, ++samples)
tracking.interaction_profiles = {
interaction_profiles[0].load(),
interaction_profiles[1].load(),
};
tracking.production_timestamp = t0;
tracking.timestamp = t0 + pattern[pattern_position].prediction_ns;
tracking.view_flags = {};
tracking.views = {};
tracking.state_flags = {};
tracking.device_poses.clear();
if (recenter_requested.exchange(false))
tracking.state_flags = wivrn::from_headset::tracking::recentered;
try
{
auto & packet = from_pool(tracking, tracking_pool);
packet.production_timestamp = t0;
packet.timestamp = t0 + Δt;
try
for (; pattern_position < pattern.size(); ++pattern_position)
{
packet.view_flags = session.locate_views(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, t0 + Δt, view_space, views);
assert(views.size() == packet.views.size());
const auto & item = pattern[pattern_position];
auto at_time = t0 + item.prediction_ns;
for (auto [i, j]: std::views::zip(views, packet.views))
switch (item.device)
{
j.pose = i.pose;
j.fov = i.fov;
}
packet.state_flags = 0;
if (recenter_requested.exchange(false))
packet.state_flags = wivrn::from_headset::tracking::recentered;
// Hand tracking data are very large, send fewer samples than other items
if (hand_tracking and t0 >= last_hand_sample + period and
(Δt == 0 or Δt >= prediction - 2 * period))
{
last_hand_sample = t0;
if (left_hand)
{
auto joints = locate_hands(*left_hand, world_space, t0 + Δt);
hands.emplace_back(
t0,
t0 + Δt,
from_headset::hand_tracking::left,
joints);
}
if (right_hand)
{
auto joints = locate_hands(*right_hand, world_space, t0 + Δt);
hands.emplace_back(
t0,
t0 + Δt,
from_headset::hand_tracking::right,
joints);
}
}
packet.device_poses.clear();
for (auto [device, space]: spaces)
{
if (enabled(control, device))
locate_spaces.add_space(device, space, t0 + Δt, packet.device_poses);
}
locate_spaces.resolve(session, t0 + Δt, packet.device_poses);
std::visit(utils::overloaded{
[](std::monostate &) {},
[&](auto & b) {
if (t0 >= last_body_sample + period and
(Δt == 0 or Δt >= prediction - 2 * period))
{
last_body_sample = t0;
if (control.enabled[size_t(tid::generic_tracker)])
{
case device_id::HEAD:
// Don't merge items that are too far from the current one
if (std::abs(tracking.timestamp - at_time) > 1'000'000)
goto subpattern_end;
tracking.view_flags = session.locate_views(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, tracking.timestamp, view_space, views);
assert(views.size() == tracking.views.size());
for (auto [i, j]: std::views::zip(views, tracking.views))
{
j.pose = i.pose;
j.fov = i.fov;
}
locate_spaces.add_space(item.device, view_space, tracking.timestamp, tracking.device_poses);
break;
case wivrn::device_id::LEFT_GRIP:
case wivrn::device_id::LEFT_AIM:
case wivrn::device_id::LEFT_PALM:
case wivrn::device_id::RIGHT_GRIP:
case wivrn::device_id::RIGHT_AIM:
case wivrn::device_id::RIGHT_PALM:
case wivrn::device_id::LEFT_PINCH_POSE:
case wivrn::device_id::LEFT_POKE:
case wivrn::device_id::RIGHT_PINCH_POSE:
case wivrn::device_id::RIGHT_POKE:
case wivrn::device_id::EYE_GAZE:
// Don't merge items that are too far from the current one
if (std::abs(tracking.timestamp - at_time) > 1'000'000)
goto subpattern_end;
locate_spaces.add_space(item.device, spaces[item.device], tracking.timestamp, tracking.device_poses);
break;
case wivrn::device_id::LEFT_HAND:
if (left_hand)
{
hands.emplace_back(
t0,
at_time,
from_headset::hand_tracking::left,
locate_hands(*left_hand, world_space, tracking.timestamp));
}
break;
case wivrn::device_id::RIGHT_HAND:
if (right_hand)
{
hands.emplace_back(
t0,
at_time,
from_headset::hand_tracking::right,
locate_hands(*right_hand, world_space, tracking.timestamp));
}
break;
case wivrn::device_id::BODY:
std::visit(utils::overloaded{
[](std::monostate &) {},
[&](auto & b) {
body.push_back(from_headset::body_tracking{
.production_timestamp = t0,
.timestamp = t0 + Δt,
.poses = b.locate_spaces(t0 + Δt, world_space),
.production_timestamp = tracking.production_timestamp,
.timestamp = at_time,
.poses = b.locate_spaces(at_time, world_space),
});
}
}
},
},
body_tracker);
std::visit(utils::overloaded{
[](std::monostate &) {},
[&](auto & ft) {
ft.get_weights(t0 + Δt, packet.face.emplace<typename std::remove_reference_t<decltype(ft)>::packet_type>());
},
},
face_tracker);
},
},
body_tracker);
break;
case wivrn::device_id::FACE:
std::visit(utils::overloaded{
[](std::monostate &) {},
[&](auto & ft) {
ft.get_weights(at_time, tracking.face.emplace<typename std::remove_reference_t<decltype(ft)>::packet_type>());
},
},
face_tracker);
default:
break;
}
}
catch (const std::system_error & e)
{
if (e.code().category() != xr::error_category() or
e.code().value() != XR_ERROR_TIME_INVALID)
throw;
}
} // end prediction loop
XrDuration busy_time = t.count();
// Target: polling between 1 and 5ms, with 20% busy time
tracking_period = std::clamp<XrDuration>(std::lerp(tracking_period, busy_time * 5, 0.1), min_tracking_period, max_tracking_period);
subpattern_end:
locate_spaces.resolve(session, tracking.timestamp, tracking.device_poses);
}
catch (const std::system_error & e)
{
if (e.code().category() != xr::error_category() or
e.code().value() != XR_ERROR_TIME_INVALID)
throw;
}
#ifdef __ANDROID__
if (next_battery_check < now and control.enabled[size_t(tid::battery)])
// FIXME: switch to event based
if (next_battery_check < now)
{
timer t2(instance);
auto status = get_battery_status();
network_session->send_stream(from_headset::battery{
.charge = status.charge.value_or(-1),
@@ -576,37 +575,19 @@ void scenes::stream::tracking()
});
next_battery_check = now + battery_check_interval;
XrDuration battery_dur = t2.count();
spdlog::info("Battery check took: {}", battery_dur);
}
#endif
merged_tracking.clear();
size_t current_size = 1400;
for (auto & item: tracking)
{
size_t size = serialized_size(item);
if (size + current_size > 1400)
{
merged_tracking.emplace_back().interaction_profiles = {
interaction_profiles[0].load(),
interaction_profiles[1].load(),
};
current_size = 0;
}
current_size += size;
merged_tracking.back().items.emplace_back(std::move(item));
}
packets.resize(std::max(packets.size(), merged_tracking.size() + hands.size() + body.size()));
packets.resize(std::max(packets.size(), 1 + hands.size() + body.size()));
size_t packet_count = 0;
for (const auto & i: merged_tracking)
if (not tracking.device_poses.empty())
{
auto & packet = packets[packet_count++];
packet.clear();
wivrn_session::stream_socket_t::serialize(packet, i);
wivrn_session::stream_socket_t::serialize(packet, tracking);
}
for (const auto & i: hands)
{
if (i.joints)
@@ -627,22 +608,6 @@ void scenes::stream::tracking()
}
network_session->send_stream(std::span(packets.data(), packet_count));
for (auto & item: merged_tracking)
std::ranges::move(item.items, std::back_inserter(tracking_pool));
if (period_adjust == 0)
{
if (auto p = real_display_period.load())
{
period_adjust = (p / tracking_period);
current_tracking_period = p / period_adjust;
}
}
else
--period_adjust;
t0 += current_tracking_period;
}
catch (std::exception & e)
{
@@ -654,16 +619,7 @@ void scenes::stream::tracking()
void scenes::stream::operator()(to_headset::tracking_control && packet)
{
auto locked = tracking_control.lock();
auto m = size_t(to_headset::tracking_control::id::microphone);
if (audio_handle)
audio_handle->set_mic_state(packet.enabled[m]);
auto n = size_t(wivrn::to_headset::tracking_control::id::hid_input);
hid_forwarding = packet.enabled[n];
*locked = packet;
locked->min_offset = std::min(locked->min_offset, locked->max_offset);
*tracking_control.lock() = std::move(packet);
}
static device_id derived_from(device_id target)
+2
View File
@@ -64,6 +64,8 @@ void xr::fb_face_tracker2::get_weights(XrTime time, wivrn::from_headset::trackin
.confidences = out_expressions.confidences.data(),
};
out_expressions.timestamp = time;
if (XR_SUCCEEDED(xrGetFaceExpressionWeights2FB(id, &info, &expression_weights)))
{
out_expressions.is_valid = expression_weights.isValid;
+2
View File
@@ -62,6 +62,8 @@ void xr::htc_face_tracker::get_weights(XrTime time, packet_type & out_expression
.sampleTime = time,
};
out_expressions.timestamp = time;
if (eye)
{
expressions.expressionCount = out_expressions.eye.size();
+1
View File
@@ -56,6 +56,7 @@ struct xr::pico_face_tracker::impl
void get_weights(XrTime time, wivrn::from_headset::tracking::fb_face2 & out_expressions)
{
out_expressions.timestamp = time;
out_expressions.is_valid = false;
out_expressions.is_eye_following_blendshapes_valid = false;
+1 -3
View File
@@ -1,10 +1,8 @@
if (WIVRN_USE_SYSTEM_BOOST)
add_library(Boost::pfr ALIAS Boost::headers)
elseif (WIVRN_BUILD_CLIENT)
else()
set(BOOST_INCLUDE_LIBRARIES locale url pfr)
FetchContent_MakeAvailable(boost)
else()
FetchContent_MakeAvailable(boostpfr)
endif()
if (GIT_DESC)
+130
View File
@@ -0,0 +1,130 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/pfr.hpp>
#include <concepts>
#include <fstream>
#include <string>
#include <type_traits>
#if __has_include(<boost/pfr/core_name.hpp>)
#define BOOST_HAS_CORE_NAME
#endif
namespace details
{
template <class>
struct is_stdarray : public std::false_type
{};
template <class T, size_t N>
struct is_stdarray<std::array<T, N>> : public std::true_type
{};
template <typename T>
inline constexpr bool is_stdarray_v = is_stdarray<T>::value;
template <typename T, typename Enable = void>
struct csv_logger_traits;
template <typename T>
struct csv_logger_traits<T, std::enable_if_t<std::is_aggregate_v<T> && !is_stdarray_v<T>>>
{
#ifdef BOOST_HAS_CORE_NAME
static void write_header(std::ostream & out, const std::string & name, bool first = true)
{
boost::pfr::for_each_field_with_name(T{}, [&](std::string_view member_name, const auto & value) {
csv_logger_traits<std::remove_cvref_t<decltype(value)>>::write_header(out, name + "." + (std::string)member_name, first);
first = false;
});
}
#endif
static void write_line(std::ostream & out, const T & value, bool first = true)
{
boost::pfr::for_each_field(value, [&](const auto & member) {
csv_logger_traits<std::remove_cvref_t<decltype(member)>>::write_line(out, member, first);
first = false;
});
}
};
template <typename T>
struct csv_logger_traits<T, std::enable_if_t<is_stdarray_v<T>>>
{
static void write_header(std::ostream & out, const std::string & name, bool first = true)
{
for (int i = 0; i < std::tuple_size_v<T>; i++)
{
csv_logger_traits<std::tuple_element_t<0, T>>::write_header(out, name + "[" + std::to_string(i) + "]", first and i == 0);
}
}
static void write_line(std::ostream & out, const T & value, bool first = true)
{
for (int i = 0; i < std::tuple_size_v<T>; i++)
{
csv_logger_traits<std::tuple_element_t<0, T>>::write_line(out, value[i], first and i == 0);
}
}
};
template <typename T>
struct csv_logger_traits<T, std::enable_if_t<!std::is_aggregate_v<T>>>
{
static void write_header(std::ostream & out, std::string_view name, bool first = true)
{
if (not first)
out << ",";
out << name.substr(1);
}
static void write_line(std::ostream & out, const T & value, bool first = true)
{
if (not first)
out << ",";
out << value;
}
};
} // namespace details
template <typename T, typename Stream = std::ofstream>
requires std::derived_from<Stream, std::ostream>
class csv_logger
{
Stream stream;
public:
template <typename... Args>
csv_logger(Args &&... args) : stream(std::forward<Args>(args)...)
{
#ifdef BOOST_HAS_CORE_NAME
details::csv_logger_traits<T>::write_header(stream, "");
stream << std::endl;
#endif
}
void write(const T & data)
{
details::csv_logger_traits<T>::write_line(stream, data);
stream << std::endl;
}
};
+3
View File
@@ -19,10 +19,13 @@
#pragma once
#include <cstdint>
namespace wivrn
{
// Default port for server to listen, both TCP and UDP
static const int default_port = 9757;
static const int64_t max_extrapolation_ns = 80'000'000;
} // namespace wivrn
#cmakedefine01 WIVRN_USE_NVENC
+27 -31
View File
@@ -129,6 +129,10 @@ enum class device_id : uint8_t
RIGHT_GRASP_VALUE, // /user/hand/right/input/grasp_ext/value
RIGHT_GRASP_READY, // /user/hand/right/input/grasp_ext/ready_ext
EYE_GAZE, // /user/eyes_ext/input/gaze_ext/pose
LEFT_HAND, // identify hand tracking
RIGHT_HAND, // identify hand tracking
BODY, // identify body tracking
FACE, // identify face tracking
};
enum class interaction_profile : uint8_t
@@ -300,6 +304,9 @@ struct tracking
XrFovf fov;
};
// /user/hand/left and /user/hand/right
std::array<interaction_profile, 2> interaction_profiles;
XrTime production_timestamp;
XrTime timestamp;
XrViewStateFlags view_flags;
@@ -321,6 +328,7 @@ struct tracking
struct fb_face2
{
XrTime timestamp;
std::array<float, XR_FACE_EXPRESSION2_COUNT_FB> weights;
std::array<float, XR_FACE_CONFIDENCE2_COUNT_FB> confidences;
bool is_valid;
@@ -330,6 +338,7 @@ struct tracking
struct htc_face
{
XrTime timestamp;
XrTime eye_sample_time;
XrTime lip_sample_time;
std::array<float, XR_FACIAL_EXPRESSION_EYE_COUNT_HTC> eye;
@@ -341,13 +350,6 @@ struct tracking
std::variant<std::monostate, android_face, fb_face2, htc_face> face;
};
struct trackings
{
// /user/hand/left and /user/hand/right
std::array<interaction_profile, 2> interaction_profiles;
std::vector<tracking> items;
};
struct derived_pose
{
device_id source;
@@ -555,7 +557,6 @@ using packets = std::variant<
audio_data,
handshake,
tracking,
trackings,
derived_pose,
hand_tracking,
body_tracking,
@@ -705,31 +706,25 @@ struct timesync_query
struct tracking_control
{
enum class id
struct sample
{
left_aim,
left_grip,
left_palm,
left_pinch,
left_poke,
right_aim,
right_grip,
right_palm,
right_pinch,
right_poke,
left_hand,
right_hand,
face,
generic_tracker,
hid_input,
battery,
microphone,
last = microphone,
device_id device;
XrDuration prediction_ns;
};
std::chrono::nanoseconds min_offset;
std::chrono::nanoseconds max_offset;
std::array<bool, size_t(id::last) + 1> enabled;
std::vector<sample> pattern;
XrDuration motions_to_photons;
};
struct feature_control
{
enum feature
{
hid_input,
microphone,
};
feature f;
bool state;
};
struct refresh_rate_change
@@ -780,6 +775,7 @@ using packets = std::variant<
haptics,
timesync_query,
tracking_control,
feature_control,
refresh_rate_change,
application_list,
application_icon,
+3 -4
View File
@@ -396,9 +396,9 @@ modules:
WIVRN_SRC2
WIVRN_SRC3
- type: archive
url: BOOSTPFR_URL
dest: deps/boostpfr-src
sha256: BOOSTPFR_SHA256
url: BOOST_URL
dest: deps/boost-src
sha256: BOOST_SHA256
- type: git
url: https://gitlab.freedesktop.org/monado/monado
tag: MONADO_COMMIT
@@ -406,4 +406,3 @@ modules:
- type: shell
commands:
- cd deps/monado-src && ../../patches/apply.sh ../../patches/monado/*
- cd deps/boostpfr-src && ../../patches/apply.sh ../../flatpak/boostpfr-gcc-12-internal-compiler-error.patch
@@ -0,0 +1,40 @@
From 38b1b5dbeff17e65e136af337a1385e9e14f8723 Mon Sep 17 00:00:00 2001
From: no name <git-am@invalid>
Date: Thu, 15 Jan 2026 12:13:06 +0100
Subject: [PATCH] Don't get pose data for fast path
---
src/xrt/compositor/main/comp_renderer.c | 17 +++++++++--------
1 file changed, 9 insertions(+), 8 deletions(-)
diff --git a/src/xrt/compositor/main/comp_renderer.c b/src/xrt/compositor/main/comp_renderer.c
index 40b219cef..febd35faa 100644
--- a/src/xrt/compositor/main/comp_renderer.c
+++ b/src/xrt/compositor/main/comp_renderer.c
@@ -994,14 +994,15 @@ dispatch_compute(struct comp_renderer *r,
struct xrt_pose world_poses_scanout_begin[XRT_MAX_VIEWS];
struct xrt_pose world_poses_scanout_end[XRT_MAX_VIEWS];
struct xrt_pose eye_poses[XRT_MAX_VIEWS];
- calc_pose_data( //
- r, //
- fov_source, //
- fovs, //
- world_poses_scanout_begin, //
- world_poses_scanout_end, //
- eye_poses, //
- render->r->view_count); //
+ if (!c->base.frame_params.one_projection_layer_fast_path)
+ calc_pose_data( //
+ r, //
+ fov_source, //
+ fovs, //
+ world_poses_scanout_begin, //
+ world_poses_scanout_end, //
+ eye_poses, //
+ render->r->view_count); //
// Target Vulkan resources..
VkImage target_image = r->c->target->images[r->acquired_buffer].handle;
--
2.52.0
+4 -3
View File
@@ -98,6 +98,10 @@ if (WIVRN_BUILD_SERVER)
driver/app_pacer.cpp
driver/clock_offset.cpp
driver/configuration.cpp
driver/hand_joints_list.cpp
driver/pose_list.cpp
driver/tracking_control.cpp
driver/view_list.cpp
driver/wivrn_hmd.cpp
driver/wivrn_pacer.cpp
driver/wivrn_comp_target.cpp
@@ -109,9 +113,6 @@ if (WIVRN_BUILD_SERVER)
driver/wivrn_generic_tracker.cpp
driver/wivrn_foveation.cpp
driver/wivrn_uinput.cpp
driver/pose_list.cpp
driver/view_list.cpp
driver/hand_joints_list.cpp
driver/wivrn_session.cpp
driver/wivrn_connection.cpp
driver/xrt_cast.cpp
+16 -2
View File
@@ -354,10 +354,24 @@ void pipewire_device::mic_state_changed(void * self_v, pw_stream_state old, pw_s
case PW_STREAM_STATE_UNCONNECTED:
case PW_STREAM_STATE_CONNECTING:
case PW_STREAM_STATE_PAUSED:
self->session.set_enabled(to_headset::tracking_control::id::microphone, false);
try
{
self->session.send_control(to_headset::feature_control{to_headset::feature_control::microphone, false});
}
catch (std::exception & e)
{
U_LOG_W("failed to update microphone state: %s", e.what());
}
return;
case PW_STREAM_STATE_STREAMING:
self->session.set_enabled(to_headset::tracking_control::id::microphone, true);
try
{
self->session.send_control(to_headset::feature_control{to_headset::feature_control::microphone, true});
}
catch (std::exception & e)
{
U_LOG_W("failed to update microphone state: %s", e.what());
}
return;
}
}
+1 -1
View File
@@ -426,7 +426,7 @@ struct pulse_device : public audio_device
if (not mic_pipe)
throw std::system_error(errno, std::system_category(), "failed to open mic pipe " + microphone->socket.string());
mic_thread = std::thread([this]() { run_mic(); });
session.set_enabled(to_headset::tracking_control::id::microphone, true);
session.send_control(to_headset::feature_control{to_headset::feature_control::microphone, true});
}
if (info.speaker)
+8 -3
View File
@@ -28,6 +28,11 @@ namespace wivrn
static const size_t num_samples = 100;
std::chrono::steady_clock::time_point clock_offset_estimator::next() const
{
return next_sample;
}
void clock_offset_estimator::reset()
{
std::lock_guard lock(mutex);
@@ -38,12 +43,12 @@ void clock_offset_estimator::reset()
sample_interval = std::chrono::milliseconds(10);
}
void clock_offset_estimator::request_sample(wivrn_connection & connection)
void clock_offset_estimator::request_sample(std::chrono::steady_clock::time_point now, wivrn_connection & connection)
{
if (std::chrono::steady_clock::now() < next_sample)
if (now < next_sample)
return;
next_sample = std::chrono::steady_clock::now() + sample_interval.load();
next_sample = now + sample_interval.load();
connection.send_stream(
wivrn::to_headset::timesync_query{
.query = XrTime(os_monotonic_get_ns()),
+2 -1
View File
@@ -65,8 +65,9 @@ class clock_offset_estimator
std::atomic<std::chrono::milliseconds> sample_interval = std::chrono::milliseconds(10);
public:
std::chrono::steady_clock::time_point next() const;
void reset();
void request_sample(wivrn_connection & connection);
void request_sample(std::chrono::steady_clock::time_point now, wivrn_connection & connection);
void add_sample(const wivrn::from_headset::timesync_response & sample);
clock_offset get_offset();
+7 -8
View File
@@ -37,7 +37,10 @@ static xrt_hand_joint_value interpolate(const xrt_hand_joint_value & a, const xr
xrt_hand_joint_set hand_joints_list::interpolate(const xrt_hand_joint_set & a, const xrt_hand_joint_set & b, float t)
{
xrt_hand_joint_set j = a;
xrt_hand_joint_set j = {
.hand_pose = pose_list::interpolate(a.hand_pose, b.hand_pose, t),
.is_active = a.is_active,
};
for (int i = 0; i < XRT_HAND_JOINT_COUNT; i++)
{
j.values.hand_joint_set_default[i] = ::wivrn::interpolate(a.values.hand_joint_set_default[i], b.values.hand_joint_set_default[i], t);
@@ -47,10 +50,7 @@ xrt_hand_joint_set hand_joints_list::interpolate(const xrt_hand_joint_set & a, c
xrt_hand_joint_set hand_joints_list::extrapolate(const xrt_hand_joint_set & a, const xrt_hand_joint_set & b, int64_t ta, int64_t tb, int64_t t)
{
xrt_hand_joint_set j = t <= ta ? a : b;
// Only extrapolate the hand pose, individual joints are too noisy
j.hand_pose = pose_list::extrapolate(a.hand_pose, b.hand_pose, ta, tb, t);
return j;
return t <= ta ? a : b;
}
static xrt_space_relation_flags cast_flags(uint8_t in_flags)
@@ -120,14 +120,13 @@ static xrt_hand_joint_set convert_joints(const std::optional<std::array<from_hea
return output_joints;
}
bool hand_joints_list::update_tracking(const from_headset::hand_tracking & tracking, const clock_offset & offset)
void hand_joints_list::update_tracking(const from_headset::hand_tracking & tracking, const clock_offset & offset)
{
if (tracking.hand == hand_id)
return add_sample(
add_sample(
tracking.production_timestamp,
tracking.timestamp,
convert_joints(tracking.joints),
offset);
return true;
}
} // namespace wivrn
+1 -1
View File
@@ -38,6 +38,6 @@ public:
hand_joints_list(int hand_id) :
hand_id(hand_id) {}
bool update_tracking(const wivrn::from_headset::hand_tracking & tracking, const clock_offset & offset);
void update_tracking(const wivrn::from_headset::hand_tracking & tracking, const clock_offset & offset);
};
} // namespace wivrn
+7 -19
View File
@@ -20,7 +20,7 @@
#pragma once
#include "clock_offset.h"
#include "os/os_time.h"
#include "util/u_time.h"
#include <algorithm>
#include <cstddef>
#include <mutex>
@@ -40,21 +40,15 @@ class history
std::array<TimedData, MaxSamples> data{};
std::mutex mutex;
XrTime last_request;
protected:
history() :
last_request(os_monotonic_get_ns()) {}
// return true if object is active (last request is not too old)
bool add_sample(XrTime produced_timestamp, XrTime timestamp, const Data & sample, const clock_offset & offset)
void add_sample(XrTime produced_timestamp, XrTime timestamp, const Data & sample, const clock_offset & offset)
{
XrTime produced = offset.from_headset(produced_timestamp);
XrTime t = offset.from_headset(timestamp);
std::lock_guard lock(mutex);
bool active = produced - last_request < 1'000'000'000;
TimedData * target = data.data();
if (offset)
{
@@ -62,7 +56,7 @@ protected:
{
// Discard reordered packets
if (item.produced_timestamp > produced)
return active;
return;
if (std::abs(item.at_timestamp_ns - t) < 2'000'000)
{
@@ -75,16 +69,13 @@ protected:
}
}
*target = TimedData(sample, produced, t);
return active;
}
public:
std::pair<std::chrono::nanoseconds, Data> get_at(XrTime at_timestamp_ns)
std::pair<XrTime, Data> get_at(XrTime at_timestamp_ns)
{
std::lock_guard lock(mutex);
last_request = os_monotonic_get_ns();
TimedData * before = nullptr;
TimedData * after = nullptr;
@@ -110,24 +101,22 @@ public:
if (before)
produced = std::max(produced, before->produced_timestamp);
std::chrono::nanoseconds ex(std::max<XrDuration>(0, at_timestamp_ns - produced));
if (before and after)
{
float t = float(after->at_timestamp_ns - at_timestamp_ns) /
(after->at_timestamp_ns - before->at_timestamp_ns);
return {ex, Derived::interpolate(*before, *after, t)};
return {produced, Derived::interpolate(*before, *after, t)};
}
if (before)
{
if (at_timestamp_ns > before->at_timestamp_ns + U_TIME_1S_IN_NS)
return {};
return {ex, *before};
return {produced, *before};
}
if (after)
return {ex, *after};
return {produced, *after};
return {};
}
@@ -135,7 +124,6 @@ public:
{
std::lock_guard lock(mutex);
data.fill({});
last_request = os_monotonic_get_ns();
}
};
} // namespace wivrn
+177
View File
@@ -0,0 +1,177 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2025 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
// xlib sucks
#ifdef Success
#undef Success
#endif
#include <Eigen/Cholesky>
#include <Eigen/Core>
#include <Eigen/QR>
#include <algorithm>
#include <limits>
#include <optional>
#include <ranges>
#include "openxr/openxr.h"
template <int N, bool quaternion = false, int polynomial_order = 2, int stored_samples = 30>
class polynomial_interpolator
{
public:
using value_type = Eigen::Vector<float, N>;
struct sample
{
XrTime production_timestamp = std::numeric_limits<XrTime>::lowest();
XrTime timestamp;
std::optional<value_type> y;
std::optional<value_type> dy;
};
XrDuration window = 30'000'000; // time span of samples to use for extrapolation
float time_constant = 0.001; // duration (s) to convert velocities into positions
private:
std::array<sample, stored_samples> data;
public:
polynomial_interpolator() = default;
polynomial_interpolator(XrDuration window, float time_constant) : window(window), time_constant(time_constant) {}
void reset()
{
data.fill({});
}
void add_sample(const sample & s)
{
sample * oldest = nullptr;
for (auto & i: data)
{
// Avoid samples too close to each other
if (std::abs(i.timestamp - s.timestamp) < 2'000'000)
{
if (i.production_timestamp < s.production_timestamp)
i = s;
return;
}
if ((not oldest) or oldest->production_timestamp > i.production_timestamp)
oldest = &i;
}
*oldest = s;
if constexpr (quaternion)
{
if (s.y)
{
sample * closest = nullptr;
for (auto & i: data)
{
if (&i == oldest or not i.y)
continue;
if (not closest)
closest = &i;
else if (std::abs(closest->timestamp - s.timestamp) > std::abs(i.timestamp - s.timestamp))
closest = &i;
}
if (closest and closest->y->dot(*s.y) < 0)
*oldest->y *= -1;
}
}
}
sample get_at(XrTime timestamp)
{
Eigen::Matrix<float, 2 * stored_samples, polynomial_order + 1> A;
Eigen::Matrix<float, 2 * stored_samples, N> b;
XrTime production_timestamp = std::numeric_limits<XrTime>::lowest();
int row = 0;
for (const auto && [i, sample]: std::ranges::enumerate_view(data))
{
if (not sample.y)
continue;
int abs_Δt = std::abs(sample.timestamp - timestamp);
float weight = 1. / (1. + std::pow(abs_Δt / float(window), 3.));
production_timestamp = std::max(production_timestamp, sample.production_timestamp);
float Δt = (sample.timestamp - timestamp) * 1.e-9;
float Δtⁱ = 1;
for (int i = 0; i <= polynomial_order; ++i)
{
A(row, i) = weight * Δtⁱ;
Δtⁱ *= Δt;
}
b.template block<1, N>(row, 0) = *sample.y * weight;
row++;
if (sample.dy.has_value())
{
A(row, 0) = 0;
Δtⁱ = 1;
for (int i = 1; i <= polynomial_order; ++i)
{
A(row, i) = weight * time_constant * i * Δtⁱ;
Δtⁱ *= Δt;
}
b.template block<1, N>(row, 0) = *sample.dy * weight * time_constant;
row++;
}
}
// Not enough data to extrapolate
if (row < 2)
{
auto closest = std::ranges::min_element(data, std::less{}, [&](const auto & sample) {
if (not sample.y)
return std::numeric_limits<XrDuration>::max();
return std::abs(sample.timestamp - timestamp);
});
if (closest->y and std::abs(closest->production_timestamp - timestamp) < 1'000'000'000)
return *closest;
return {};
}
auto Aprime = A.block(0, 0, row, polynomial_order + 1);
auto bprime = b.block(0, 0, row, N);
Eigen::Matrix<float, N, polynomial_order + 1> sol;
if (row <= polynomial_order)
// Underdetermined case
sol = Eigen::ColPivHouseholderQR<decltype(Aprime)>{Aprime}.solve(bprime).transpose();
else
sol = (Aprime.transpose() * Aprime).ldlt().solve(Aprime.transpose() * bprime).transpose();
return sample{
.production_timestamp = production_timestamp,
.timestamp = timestamp,
.y = sol.template block<N, 1>(0, 0),
.dy = sol.template block<N, 1>(0, 1),
};
}
};
+176 -21
View File
@@ -18,12 +18,18 @@
*/
#include "pose_list.h"
#include "driver/clock_offset.h"
#include "driver/polynomial_interpolator.h"
#include "math/m_api.h"
#include "math/m_eigen_interop.hpp"
#include "math/m_space.h"
#include "math/m_vec3.h"
#include "os/os_time.h"
#include "xrt/xrt_defines.h"
#include "xrt_cast.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <iostream>
#include <magic_enum.hpp>
using namespace xrt::auxiliary::math;
@@ -86,19 +92,26 @@ xrt_space_relation pose_list::extrapolate(const xrt_space_relation & a, const xr
return res;
}
bool pose_list::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset)
pose_list::pose_list(wivrn::device_id id) : device(id)
{
if (auto dump = std::getenv("WIVRN_DUMP"); dump and dump == std::string_view("list"))
std::cerr << "WIVRN_DUMP_" << magic_enum::enum_name(id) << std::endl;
if (auto dump = std::getenv(std::format("WIVRN_DUMP_{}", magic_enum::enum_name(id)).c_str()))
dumper.emplace(dump);
}
void pose_list::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset)
{
if (source)
return false;
return;
for (const auto & pose: tracking.device_poses)
{
if (pose.device != device)
continue;
return add_sample(tracking.production_timestamp, tracking.timestamp, convert_pose(pose), offset);
return add_sample(tracking.production_timestamp, tracking.timestamp, pose, offset);
}
return true;
}
void pose_list::set_derived(pose_list * source, xrt_pose offset, bool force)
@@ -121,7 +134,7 @@ void pose_list::set_derived(pose_list * source, xrt_pose offset, bool force)
}
}
std::tuple<std::chrono::nanoseconds, xrt_space_relation, device_id> pose_list::get_pose_at(XrTime at_timestamp_ns)
std::tuple<XrTime, xrt_space_relation, device_id> pose_list::get_pose_at(XrTime at_timestamp_ns)
{
if (auto source = this->source.load())
{
@@ -133,24 +146,166 @@ std::tuple<std::chrono::nanoseconds, xrt_space_relation, device_id> pose_list::g
return std::tuple_cat(get_at(at_timestamp_ns), std::make_tuple(device));
}
static xrt_space_relation_flags convert_flags(uint8_t flags)
void pose_list::reset()
{
static_assert(int(from_headset::tracking::position_valid) == XRT_SPACE_RELATION_POSITION_VALID_BIT);
static_assert(int(from_headset::tracking::orientation_valid) == XRT_SPACE_RELATION_ORIENTATION_VALID_BIT);
static_assert(int(from_headset::tracking::linear_velocity_valid) == XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT);
static_assert(int(from_headset::tracking::angular_velocity_valid) == XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT);
static_assert(int(from_headset::tracking::orientation_tracked) == XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT);
static_assert(int(from_headset::tracking::position_tracked) == XRT_SPACE_RELATION_POSITION_TRACKED_BIT);
return xrt_space_relation_flags(flags);
std::lock_guard lock(mutex);
positions.reset();
orientations.reset();
}
xrt_space_relation pose_list::convert_pose(const from_headset::tracking::pose & pose)
void pose_list::add_sample(XrTime production_timestamp, XrTime timestamp, const from_headset::tracking::pose & pose, const clock_offset & offset)
{
return xrt_space_relation{
.relation_flags = convert_flags(pose.flags),
.pose = xrt_cast(pose.pose),
.linear_velocity = xrt_cast(pose.linear_velocity),
.angular_velocity = xrt_cast(pose.angular_velocity),
};
production_timestamp = offset.from_headset(production_timestamp);
timestamp = offset.from_headset(timestamp);
// TODO keep the tracked flag
polynomial_interpolator<3>::sample position{production_timestamp, timestamp};
if (pose.flags & from_headset::tracking::position_valid)
position.y.emplace(
pose.pose.position.x,
pose.pose.position.y,
pose.pose.position.z);
if (pose.flags & from_headset::tracking::linear_velocity_valid)
position.dy.emplace(
pose.linear_velocity.x,
pose.linear_velocity.y,
pose.linear_velocity.z);
polynomial_interpolator<4, true>::sample orientation{production_timestamp, timestamp};
if (pose.flags & from_headset::tracking::orientation_valid)
{
orientation.y.emplace(
pose.pose.orientation.w,
pose.pose.orientation.x,
pose.pose.orientation.y,
pose.pose.orientation.z);
if (pose.flags & from_headset::tracking::angular_velocity_valid)
{
Eigen::Quaternionf q{
pose.pose.orientation.w,
pose.pose.orientation.x,
pose.pose.orientation.y,
pose.pose.orientation.z};
Eigen::Quaternionf ω{
0,
pose.angular_velocity.x,
pose.angular_velocity.y,
pose.angular_velocity.z};
orientation.dy.emplace(0.5 * (ω * q).coeffs());
}
}
std::lock_guard lock(mutex);
positions.add_sample(position);
orientations.add_sample(orientation);
if (dumper)
{
debug_data item{
.in = true,
.production_timestamp = production_timestamp,
.timestamp = timestamp,
.now = os_monotonic_get_ns(),
};
if (position.y)
Eigen::Map<Eigen::Vector<float, 3>>(item.position.data()) = *position.y;
if (position.dy)
Eigen::Map<Eigen::Vector<float, 3>>(item.dposition.data()) = *position.dy;
if (orientation.y)
Eigen::Map<Eigen::Vector<float, 4>>(item.orientation.data()) = *orientation.y;
if (orientation.dy)
Eigen::Map<Eigen::Vector<float, 4>>(item.dorientation.data()) = *orientation.dy;
dumper->write(item);
}
}
std::pair<XrTime, xrt_space_relation> pose_list::get_at(XrTime at_timestamp_ns)
{
std::lock_guard lock(mutex);
xrt_space_relation ret{};
auto flags = [&](int f) {
ret.relation_flags = xrt_space_relation_flags(int(ret.relation_flags) | f);
};
auto position = positions.get_at(at_timestamp_ns);
auto orientation = orientations.get_at(at_timestamp_ns);
if (position.y)
{
flags(XRT_SPACE_RELATION_POSITION_VALID_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT);
ret.pose.position = {
position.y->x(),
position.y->y(),
position.y->z()};
}
if (position.dy)
{
flags(XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT);
ret.linear_velocity = {
position.dy->x(),
position.dy->y(),
position.dy->z()};
}
if (orientation.y)
{
flags(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT);
ret.pose.orientation = {
.x = (*orientation.y)[1],
.y = (*orientation.y)[2],
.z = (*orientation.y)[3],
.w = (*orientation.y)[0]};
if (orientation.dy)
{
Eigen::Quaternionf q{
(*orientation.y)[0],
(*orientation.y)[1],
(*orientation.y)[2],
(*orientation.y)[3]};
Eigen::Quaternionf dq{
(*orientation.dy)[0],
(*orientation.dy)[1],
(*orientation.dy)[2],
(*orientation.dy)[3]};
Eigen::Quaternionf half_ω = dq * q;
flags(XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT);
ret.angular_velocity = {
2 * half_ω.x(),
2 * half_ω.y(),
2 * half_ω.z(),
};
}
}
if (dumper)
{
debug_data item{
.in = false,
.production_timestamp = position.production_timestamp,
.timestamp = at_timestamp_ns,
.now = os_monotonic_get_ns(),
};
if (position.y)
Eigen::Map<Eigen::Vector<float, 3>>(item.position.data()) = *position.y;
if (position.dy)
Eigen::Map<Eigen::Vector<float, 3>>(item.dposition.data()) = *position.dy;
if (orientation.y)
Eigen::Map<Eigen::Vector<float, 4>>(item.orientation.data()) = *orientation.y;
if (orientation.dy)
Eigen::Map<Eigen::Vector<float, 4>>(item.dorientation.data()) = *orientation.dy;
dumper->write(item);
}
return {position.production_timestamp, ret};
}
} // namespace wivrn
+30 -7
View File
@@ -19,21 +19,41 @@
#pragma once
#include "history.h"
#include "polynomial_interpolator.h"
#include "utils/csv_logger.h"
#include "wivrn_packets.h"
#include "xrt/xrt_defines.h"
#include <atomic>
#include <optional>
namespace wivrn
{
struct clock_offset;
class pose_list : public history<pose_list, xrt_space_relation>
class pose_list
{
std::atomic<pose_list *> source = nullptr;
xrt_pose offset;
std::atomic_bool derive_forced = false;
std::mutex mutex;
polynomial_interpolator<3> positions;
polynomial_interpolator<4, true> orientations;
struct debug_data
{
bool in; // true: received data, false: data request
XrTime production_timestamp;
XrTime timestamp;
XrTime now;
std::array<float, 3> position;
std::array<float, 3> dposition;
std::array<float, 4> orientation;
std::array<float, 4> dorientation;
};
std::optional<csv_logger<debug_data>> dumper;
public:
const wivrn::device_id device;
@@ -41,14 +61,17 @@ public:
static xrt_space_relation interpolate(const xrt_space_relation & a, const xrt_space_relation & b, float t);
static xrt_space_relation extrapolate(const xrt_space_relation & a, const xrt_space_relation & b, int64_t ta, int64_t tb, int64_t t);
pose_list(wivrn::device_id id) :
device(id) {}
pose_list(wivrn::device_id id);
bool update_tracking(const wivrn::from_headset::tracking &, const clock_offset & offset);
void update_tracking(const wivrn::from_headset::tracking &, const clock_offset & offset);
void set_derived(pose_list * source, xrt_pose offset, bool force = false);
std::tuple<std::chrono::nanoseconds, xrt_space_relation, device_id> get_pose_at(XrTime at_timestamp_ns);
std::tuple<XrTime, xrt_space_relation, device_id> get_pose_at(XrTime at_timestamp_ns);
static xrt_space_relation convert_pose(const wivrn::from_headset::tracking::pose &);
void reset();
std::pair<XrTime, xrt_space_relation> get_at(XrTime at_timestamp_ns);
private:
void add_sample(XrTime production_timestamp, XrTime timestamp, const from_headset::tracking::pose & pose, const clock_offset & offset);
};
} // namespace wivrn
+105
View File
@@ -0,0 +1,105 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "tracking_control.h"
#include "driver/wivrn_connection.h"
#include "wivrn_config.h"
#include <magic_enum_containers.hpp>
#include <ranges>
bool wivrn::tracking_control::advance(std::chrono::steady_clock::time_point now)
{
if (next > now)
return false;
next += step;
return true;
}
void wivrn::tracking_control::add_request(device_id device, XrTime now, XrTime at_ns, XrTime produced_ns)
{
std::lock_guard lock(mutex);
XrDuration prediction = at_ns - now;
reqs[device].min_prediction = std::min(reqs[device].min_prediction, prediction);
reqs[device].max_prediction = std::max(reqs[device].max_prediction, prediction);
if (produced_ns)
motions_to_photons = std::max(motions_to_photons, at_ns - produced_ns);
if (not std::ranges::contains(last_control.pattern, device, &to_headset::tracking_control::sample::device))
{
last_control.pattern.push_back({.device = device, .prediction_ns = prediction});
cnx.send_control(to_headset::tracking_control(last_control));
}
}
void wivrn::tracking_control::resolve(XrDuration frame_time, XrDuration latency)
{
decltype(this->reqs) reqs;
{
std::lock_guard lock(mutex);
std::swap(reqs, this->reqs);
}
wivrn::to_headset::tracking_control res{};
for (auto [device, req]: std::ranges::enumerate_view(reqs))
{
// Skip unset data
if (req.min_prediction > req.max_prediction)
continue;
XrDuration step = frame_time;
switch (device_id(device))
{
// High frequency polling for those
case device_id::HEAD:
case device_id::LEFT_GRIP:
case device_id::LEFT_AIM:
case device_id::LEFT_PALM:
case device_id::RIGHT_GRIP:
case device_id::RIGHT_AIM:
case device_id::RIGHT_PALM:
case device_id::LEFT_PINCH_POSE:
case device_id::RIGHT_PINCH_POSE:
case device_id::EYE_GAZE:
step = 3'000'000;
default:
break;
}
req.min_prediction = std::clamp(req.min_prediction + latency, 0l, max_extrapolation_ns);
req.max_prediction = std::clamp(req.max_prediction + latency, 0l, max_extrapolation_ns);
for (int64_t t = req.min_prediction; t < req.max_prediction + step; t += step)
{
res.pattern.push_back({
.device = device_id(device),
.prediction_ns = t,
});
}
}
{
std::lock_guard lock(mutex);
res.motions_to_photons = motions_to_photons;
last_control = res;
motions_to_photons = 0;
}
cnx.send_control(std::move(res));
}
+53
View File
@@ -0,0 +1,53 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "wivrn_packets.h"
#include <magic_enum_containers.hpp>
#include <mutex>
namespace wivrn
{
class wivrn_connection;
class tracking_control
{
static constexpr std::chrono::milliseconds step{1000};
struct requests
{
XrDuration min_prediction = std::numeric_limits<XrDuration>::max();
XrDuration max_prediction = std::numeric_limits<XrDuration>::lowest();
};
std::mutex mutex;
magic_enum::containers::array<device_id, requests> reqs;
XrDuration motions_to_photons = 0;
to_headset::tracking_control last_control;
wivrn_connection & cnx;
public:
std::chrono::steady_clock::time_point next;
tracking_control(wivrn_connection & cnx) : cnx(cnx), next(std::chrono::steady_clock::now() + step) {}
bool advance(std::chrono::steady_clock::time_point now);
void add_request(device_id device, int64_t now, int64_t at_ns, int64_t produced_ns);
void resolve(XrDuration frame_time, XrDuration latency);
};
} // namespace wivrn
+26 -31
View File
@@ -18,46 +18,41 @@
*/
#include "view_list.h"
#include "pose_list.h"
#include "xrt_cast.h"
namespace wivrn
{
tracked_views view_list::interpolate(const tracked_views & a, const tracked_views & b, float t)
void view_list::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset)
{
tracked_views result = a;
result.relation = pose_list::interpolate(a.relation, b.relation, t);
return result;
}
if (not std::ranges::contains(tracking.device_poses, device_id::HEAD, &from_headset::tracking::pose::device))
return;
tracked_views view_list::extrapolate(const tracked_views & a, const tracked_views & b, int64_t ta, int64_t tb, int64_t t)
{
tracked_views result = t < ta ? a : b;
result.relation = pose_list::extrapolate(a.relation, b.relation, ta, tb, t);
return result;
}
std::lock_guard lock(mutex);
flags = tracking.view_flags;
bool view_list::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset)
{
for (const auto & pose: tracking.device_poses)
for (size_t eye = 0; eye < 2; ++eye)
{
if (pose.device != device_id::HEAD)
continue;
tracked_views view{};
view.relation = pose_list::convert_pose(pose);
view.flags = tracking.view_flags;
for (size_t eye = 0; eye < 2; ++eye)
{
view.poses[eye] = xrt_cast(tracking.views[eye].pose);
view.fovs[eye] = xrt_cast(tracking.views[eye].fov);
}
return add_sample(tracking.production_timestamp, tracking.timestamp, view, offset);
poses[eye] = xrt_cast(tracking.views[eye].pose);
fovs[eye] = xrt_cast(tracking.views[eye].fov);
}
return true;
head_poses.update_tracking(tracking, offset);
}
std::pair<XrTime, tracked_views> view_list::get_at(XrTime at_timestamp_ns)
{
std::lock_guard lock(mutex);
auto [t, pose] = head_poses.get_at(at_timestamp_ns);
return {
t,
tracked_views{
.flags = flags,
.relation = pose,
.poses = poses,
.fovs = fovs,
},
};
}
} // namespace wivrn
+9 -5
View File
@@ -35,12 +35,16 @@ struct tracked_views
std::array<xrt_fov, 2> fovs;
};
class view_list : public history<view_list, tracked_views>
class view_list
{
public:
static tracked_views interpolate(const tracked_views & a, const tracked_views & b, float t);
static tracked_views extrapolate(const tracked_views & a, const tracked_views & b, int64_t ta, int64_t tb, int64_t t);
pose_list head_poses{device_id::HEAD};
std::mutex mutex;
XrViewStateFlags flags;
std::array<xrt_pose, 2> poses;
std::array<xrt_fov, 2> fovs;
bool update_tracking(const from_headset::tracking & tracking, const clock_offset & offset);
public:
void update_tracking(const from_headset::tracking & tracking, const clock_offset & offset);
std::pair<XrTime, tracked_views> get_at(XrTime at_timestamp_ns);
};
} // namespace wivrn
+4 -7
View File
@@ -31,9 +31,7 @@
#include "xrt/xrt_device.h"
#include "xrt/xrt_results.h"
#include <cmath>
#include <cstdint>
#include <cstring>
namespace wivrn
{
@@ -84,16 +82,15 @@ void wivrn_android_face_tracker::update_tracking(const from_headset::tracking &
.is_valid = face->is_valid,
};
if (not face_list.update_tracking(tracking.production_timestamp, tracking.timestamp, data, offset))
cnx.set_enabled(to_headset::tracking_control::id::face, false);
face_list.update_tracking(face->sample_time, tracking.timestamp, data, offset);
}
xrt_result_t wivrn_android_face_tracker::get_face_tracking(enum xrt_input_name facial_expression_type, int64_t at_timestamp_ns, struct xrt_facial_expression_set * inout_value)
{
if (facial_expression_type == XRT_INPUT_ANDROID_FACE_TRACKING)
{
cnx.set_enabled(to_headset::tracking_control::id::face, true);
auto [_, data] = face_list.get_at(at_timestamp_ns);
auto [production_timestamp, data] = face_list.get_at(at_timestamp_ns);
cnx.add_tracking_request(device_id::FACE, at_timestamp_ns, production_timestamp);
inout_value->face_expression_set_android.state = data.state;
inout_value->face_expression_set_android.is_valid = data.is_valid;
@@ -118,4 +115,4 @@ xrt_result_t wivrn_android_face_tracker::get_face_calibration_state_android(bool
*out_face_is_calibrated = data.is_calibrated;
return XRT_SUCCESS;
}
} // namespace wivrn
} // namespace wivrn
+2 -2
View File
@@ -75,9 +75,9 @@ public:
return result;
}
bool update_tracking(const XrTime & production_timestamp, const XrTime & timestamp, const wivrn_android_face_data & data, const clock_offset & offset)
void update_tracking(const XrTime & production_timestamp, const XrTime & timestamp, const wivrn_android_face_data & data, const clock_offset & offset)
{
return this->add_sample(production_timestamp, timestamp, data, offset);
add_sample(production_timestamp, timestamp, data, offset);
}
};
+11 -4
View File
@@ -632,11 +632,18 @@ static VkResult comp_wivrn_present(struct comp_target * ct,
const auto & frame_params = cn->c->base.frame_params;
view_info.fov[eye] = xrt_cast(frame_params.fovs[eye]);
view_info.pose[eye] = xrt_cast(frame_params.poses[eye]);
if (cn->c->debug.atw_off)
if (cn->c->base.frame_params.one_projection_layer_fast_path)
{
const auto & proj = cn->c->base.layer_accum.layers[0].data.proj;
view_info.pose[eye] = xrt_cast(proj.v[eye].pose);
view_info.fov[eye] = xrt_cast(proj.v[eye].fov);
for (const auto & layer: cn->c->base.layer_accum.layers)
{
if (layer.data.type == XRT_LAYER_PROJECTION)
{
const auto & proj = cn->c->base.layer_accum.layers[0].data.proj;
view_info.pose[eye] = xrt_cast(proj.v[eye].pose);
view_info.fov[eye] = xrt_cast(proj.v[eye].fov);
break;
}
}
}
else
{
+20 -127
View File
@@ -23,12 +23,13 @@
#include "driver/xrt_cast.h"
#include "math/m_api.h"
#include "utils/method.h"
#include "wivrn_config.h"
#include "wivrn_session.h"
#include "os/os_time.h"
#include "util/u_logging.h"
#include <array>
#include <format>
#include <fstream>
#include <magic_enum.hpp>
#include <numbers>
#include <optional>
@@ -570,26 +571,6 @@ make_binding_profiles()
constexpr auto controller_per_hand_binding_profiles = std::to_array({make_binding_profiles<0>(),
make_binding_profiles<1>()});
struct xrt_space_relation_csv_header
{};
std::ostream & operator<<(std::ostream & out, const xrt_space_relation_csv_header &)
{
for (auto [value, name]: magic_enum::enum_entries<xrt_space_relation_flags>())
{
if (value and value != XRT_SPACE_RELATION_BITMASK_ALL)
{
name = name.substr(strlen("XRT_SPACE_RELATION_"));
name = name.substr(0, name.size() - strlen("_BIT"));
out << name << ",";
}
}
out << "x,y,z,";
out << "qw,qx,qy,qz,";
out << "vx,vy,vz,";
out << "avx,avy,avz";
return out;
}
} // namespace
wivrn_controller::wivrn_controller(xrt_device_name name,
@@ -643,12 +624,10 @@ wivrn_controller::wivrn_controller(xrt_device_name name,
math_quat_from_euler_angles(&rotation_angles, &offset.orientation);
palm.set_derived(&grip, offset, true);
cnx->set_enabled(palm.device, false);
}
else if (not cnx->get_info().palm_pose)
{
palm.set_derived(&grip, XRT_POSE_IDENTITY, false);
cnx->set_enabled(palm.device, false);
}
if (name != XRT_DEVICE_EXT_HAND_INTERACTION)
@@ -793,55 +772,34 @@ void wivrn_controller::set_inputs(const from_headset::inputs & inputs, const clo
xrt_result_t wivrn_controller::get_tracked_pose(xrt_input_name name, int64_t at_timestamp_ns, xrt_space_relation * res)
{
std::chrono::nanoseconds extrapolation_time;
XrTime production_timestamp;
device_id device;
XrTime now = os_monotonic_get_ns();
auto target_ns = std::min(at_timestamp_ns, now + max_extrapolation_ns);
switch (name)
{
case XRT_INPUT_TOUCH_AIM_POSE:
case XRT_INPUT_HAND_AIM_POSE:
std::tie(extrapolation_time, *res, device) = aim.get_pose_at(at_timestamp_ns);
std::tie(production_timestamp, *res, device) = aim.get_pose_at(target_ns);
break;
case XRT_INPUT_TOUCH_GRIP_POSE:
case XRT_INPUT_HAND_GRIP_POSE:
std::tie(extrapolation_time, *res, device) = grip.get_pose_at(at_timestamp_ns);
std::tie(production_timestamp, *res, device) = grip.get_pose_at(target_ns);
break;
case XRT_INPUT_GENERIC_PALM_POSE:
std::tie(extrapolation_time, *res, device) = palm.get_pose_at(at_timestamp_ns);
std::tie(production_timestamp, *res, device) = palm.get_pose_at(target_ns);
break;
case XRT_INPUT_HAND_PINCH_POSE:
std::tie(extrapolation_time, *res, device) = pinch_ext.get_pose_at(at_timestamp_ns);
std::tie(production_timestamp, *res, device) = pinch_ext.get_pose_at(target_ns);
break;
case XRT_INPUT_HAND_POKE_POSE:
std::tie(extrapolation_time, *res, device) = poke_ext.get_pose_at(at_timestamp_ns);
std::tie(production_timestamp, *res, device) = poke_ext.get_pose_at(target_ns);
break;
default:
U_LOG_XDEV_UNSUPPORTED_INPUT(this, u_log_get_global_level(), name);
return XRT_ERROR_INPUT_UNSUPPORTED;
}
cnx->set_enabled(device, true);
cnx->add_predict_offset(extrapolation_time);
if (auto out = tracking_dump())
{
auto device = [&] {
switch (name)
{
case XRT_INPUT_TOUCH_AIM_POSE: return aim.device;
case XRT_INPUT_TOUCH_GRIP_POSE: return grip.device;
case XRT_INPUT_GENERIC_PALM_POSE: return palm.device;
case XRT_INPUT_HAND_PINCH_POSE: return pinch_ext.device;
case XRT_INPUT_HAND_POKE_POSE: return poke_ext.device;
default:
assert(false);
__builtin_unreachable();
} }();
*out->lock() << magic_enum::enum_name(device) << ','
<< os_monotonic_get_ns() << ','
<< at_timestamp_ns << ','
<< extrapolation_time.count() << ','
<< "g,"
<< *res << std::endl;
;
}
cnx->add_tracking_request(device, at_timestamp_ns, production_timestamp, now);
return XRT_SUCCESS;
}
@@ -852,10 +810,9 @@ xrt_result_t wivrn_controller::get_hand_tracking(xrt_input_name name, int64_t de
case XRT_INPUT_HT_UNOBSTRUCTED_LEFT:
case XRT_INPUT_HT_UNOBSTRUCTED_RIGHT: {
*out_timestamp_ns = desired_timestamp_ns;
std::chrono::nanoseconds extrapolation_time;
std::tie(extrapolation_time, *out_value) = joints.get_at(desired_timestamp_ns);
cnx->add_predict_offset(extrapolation_time);
cnx->set_enabled(joints.hand_id == 0 ? to_headset::tracking_control::id::left_hand : to_headset::tracking_control::id::right_hand, true);
XrTime production_timestamp;
std::tie(production_timestamp, *out_value) = joints.get_at(desired_timestamp_ns);
cnx->add_tracking_request(joints.hand_id == 0 ? device_id::LEFT_HAND : device_id::RIGHT_HAND, desired_timestamp_ns, production_timestamp);
return XRT_SUCCESS;
}
@@ -878,46 +835,21 @@ void wivrn_controller::set_derived_pose(const from_headset::derived_pose & deriv
auto source = list(derived.source);
auto target = list(derived.target);
if (source and target)
{
target->set_derived(source, xrt_cast(derived.relation));
if (source != target)
cnx->set_enabled(derived.target, false);
}
}
void wivrn_controller::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset)
{
if (not aim.update_tracking(tracking, offset))
cnx->set_enabled(aim.device, false);
if (not grip.update_tracking(tracking, offset))
cnx->set_enabled(grip.device, false);
if (not palm.update_tracking(tracking, offset))
cnx->set_enabled(palm.device, false);
if (not pinch_ext.update_tracking(tracking, offset))
cnx->set_enabled(pinch_ext.device, false);
if (not poke_ext.update_tracking(tracking, offset))
cnx->set_enabled(poke_ext.device, false);
if (auto out = tracking_dump(); out and offset)
{
auto locked = out->lock();
auto now = os_monotonic_get_ns();
for (const auto & pose: tracking.device_poses)
{
if (pose.device == aim.device or pose.device == grip.device or pose.device == palm.device or pose.device == pinch_ext.device or pose.device == poke_ext.device)
*locked << magic_enum::enum_name(pose.device) << ','
<< now << ','
<< offset.from_headset(tracking.timestamp) << ','
<< tracking.timestamp - tracking.production_timestamp << ','
<< "r,"
<< pose_list::convert_pose(pose) << std::endl;
}
}
aim.update_tracking(tracking, offset);
grip.update_tracking(tracking, offset);
palm.update_tracking(tracking, offset);
pinch_ext.update_tracking(tracking, offset);
poke_ext.update_tracking(tracking, offset);
}
void wivrn_controller::update_hand_tracking(const from_headset::hand_tracking & tracking, const clock_offset & offset)
{
if (not joints.update_tracking(tracking, offset))
cnx->set_enabled(joints.hand_id == 0 ? to_headset::tracking_control::id::left_hand : to_headset::tracking_control::id::right_hand, false);
joints.update_tracking(tracking, offset);
}
xrt_result_t wivrn_controller::set_output(xrt_output_name name, const xrt_output_value * value)
@@ -963,43 +895,4 @@ void wivrn_controller::reset_history()
poke_ext.reset();
}
thread_safe<std::ofstream> * wivrn_controller::tracking_dump()
{
static std::unique_ptr<thread_safe<std::ofstream>> res = [] {
if (auto wivrn_dump = std::getenv("WIVRN_DUMP_TRACKING"))
{
U_LOG_I("Controller tracking dump enabled: %s", wivrn_dump);
std::ofstream res;
res.open(wivrn_dump);
res << "device_id,"
"now_ns,"
"timestamp_ns,"
"extrapolation_ns,"
"receive/get,"
<< xrt_space_relation_csv_header{} << std::endl;
return std::make_unique<thread_safe<std::ofstream>>(std::move(res));
}
return std::unique_ptr<thread_safe<std::ofstream>>();
}();
return res.get();
}
} // namespace wivrn
std::ostream & operator<<(std::ostream & out, const xrt_space_relation & rel)
{
const auto & pos = rel.pose.position;
const auto & o = rel.pose.orientation;
const auto & v = rel.linear_velocity;
const auto & av = rel.angular_velocity;
for (const auto & [value, name]: magic_enum::enum_entries<xrt_space_relation_flags>())
{
if (value and value != XRT_SPACE_RELATION_BITMASK_ALL)
out << bool(rel.relation_flags & value) << ',';
}
out << pos.x << ',' << pos.y << ',' << pos.z << ',';
out << o.w << ',' << o.x << ',' << o.y << ',' << o.z << ',';
out << v.x << ',' << v.y << ',' << v.z << ',';
out << av.x << ',' << av.y << ',' << av.z;
return out;
}
-6
View File
@@ -24,9 +24,7 @@
#include "hand_joints_list.h"
#include "pose_list.h"
#include "utils/thread_safe.h"
#include <fstream>
#include <mutex>
#include <vector>
@@ -69,10 +67,6 @@ public:
void update_hand_tracking(const from_headset::hand_tracking &, const clock_offset &);
void reset_history();
static thread_safe<std::ofstream> * tracking_dump();
};
} // namespace wivrn
std::ostream & operator<<(std::ostream & out, const xrt_space_relation & rel);
+6 -5
View File
@@ -21,21 +21,20 @@
#include "wivrn_eye_tracker.h"
#include "wivrn_packets.h"
#include "wivrn_session.h"
#include "xrt/xrt_defines.h"
#include "xrt/xrt_device.h"
#include "util/u_logging.h"
#include "utils/method.h"
#include <cmath>
#include <cstdint>
#include <cstring>
#include <openxr/openxr.h>
namespace wivrn
{
wivrn_eye_tracker::wivrn_eye_tracker(xrt_device * hmd) :
wivrn_eye_tracker::wivrn_eye_tracker(xrt_device * hmd, wivrn_session & cnx) :
xrt_device{
.name = XRT_DEVICE_EYE_GAZE_INTERACTION,
.device_type = XRT_DEVICE_TYPE_EYE_TRACKER,
@@ -55,7 +54,8 @@ wivrn_eye_tracker::wivrn_eye_tracker(xrt_device * hmd) :
.active = true,
.name = XRT_INPUT_GENERIC_EYE_GAZE_POSE,
},
gaze(device_id::EYE_GAZE)
gaze(device_id::EYE_GAZE),
cnx(cnx)
{
}
@@ -68,8 +68,9 @@ xrt_result_t wivrn_eye_tracker::get_tracked_pose(xrt_input_name name, int64_t at
{
if (name == XRT_INPUT_GENERIC_EYE_GAZE_POSE)
{
auto [_, relation] = gaze.get_at(at_timestamp_ns);
auto [production_timestamp, relation] = gaze.get_at(at_timestamp_ns);
*out_relation = relation;
cnx.add_tracking_request(device_id::EYE_GAZE, at_timestamp_ns, production_timestamp);
return XRT_SUCCESS;
}
+3 -1
View File
@@ -30,16 +30,18 @@
namespace wivrn
{
class wivrn_session;
class wivrn_eye_tracker : public xrt_device
{
std::mutex mutex;
xrt_input gaze_input;
pose_list gaze;
wivrn_session & cnx;
public:
using base = xrt_device;
wivrn_eye_tracker(xrt_device * hmd);
wivrn_eye_tracker(xrt_device * hmd, wivrn_session &);
xrt_result_t update_inputs();
void update_tracking(const from_headset::tracking &, const clock_offset &);
+3 -6
View File
@@ -29,9 +29,7 @@
#include "xrt/xrt_device.h"
#include "xrt/xrt_results.h"
#include <cmath>
#include <cstdint>
#include <cstring>
#include <openxr/openxr.h>
namespace wivrn
@@ -81,16 +79,15 @@ void wivrn_fb_face2_tracker::update_tracking(const from_headset::tracking & trac
.time = offset.from_headset(face->time),
};
if (not face_list.update_tracking(tracking.production_timestamp, tracking.timestamp, data, offset))
cnx.set_enabled(to_headset::tracking_control::id::face, false);
face_list.update_tracking(face->timestamp, tracking.timestamp, data, offset);
}
xrt_result_t wivrn_fb_face2_tracker::get_face_tracking(enum xrt_input_name facial_expression_type, int64_t at_timestamp_ns, struct xrt_facial_expression_set * inout_value)
{
if (facial_expression_type == XRT_INPUT_FB_FACE_TRACKING2_VISUAL)
{
cnx.set_enabled(to_headset::tracking_control::id::face, true);
auto [_, data] = face_list.get_at(at_timestamp_ns);
auto [production_timestamp, data] = face_list.get_at(at_timestamp_ns);
cnx.add_tracking_request(device_id::FACE, at_timestamp_ns, production_timestamp);
inout_value->face_expression_set2_fb.is_valid = data.is_valid;
inout_value->face_expression_set2_fb.sample_time_ns = data.time;
+2 -2
View File
@@ -80,9 +80,9 @@ public:
return result;
}
bool update_tracking(const XrTime & production_timestamp, const XrTime & timestamp, const wivrn_fb_face2_data & data, const clock_offset & offset)
void update_tracking(const XrTime & production_timestamp, const XrTime & timestamp, const wivrn_fb_face2_data & data, const clock_offset & offset)
{
return this->add_sample(production_timestamp, timestamp, data, offset);
add_sample(production_timestamp, timestamp, data, offset);
}
};
+8 -20
View File
@@ -30,7 +30,6 @@
#include "xrt/xrt_defines.h"
#include "xrt/xrt_results.h"
#include "xrt_cast.h"
#include <chrono>
#include <format>
using namespace xrt::auxiliary::math;
@@ -71,14 +70,9 @@ xrt_space_relation tracker_pose_list::extrapolate(const xrt_space_relation & a,
return res;
}
bool tracker_pose_list::update_tracking(XrTime produced_timestamp, XrTime timestamp, const from_headset::body_tracking::pose & pose, const clock_offset & offset)
void tracker_pose_list::update_tracking(XrTime produced_timestamp, XrTime timestamp, const from_headset::body_tracking::pose & pose, const clock_offset & offset)
{
return add_sample(produced_timestamp, timestamp, convert_pose(pose), offset);
}
std::pair<std::chrono::nanoseconds, xrt_space_relation> tracker_pose_list::get_pose_at(XrTime at_timestamp_ns)
{
return get_at(at_timestamp_ns);
add_sample(produced_timestamp, timestamp, convert_pose(pose), offset);
}
static xrt_space_relation_flags convert_flags(uint8_t flags)
@@ -121,8 +115,7 @@ wivrn_generic_tracker::wivrn_generic_tracker(int index, xrt_device * hmd, wivrn_
.get_tracked_pose = method_pointer<&wivrn_generic_tracker::get_tracked_pose>,
.destroy = [](xrt_device *) {},
},
cnx(cnx),
index(index)
cnx(cnx)
{
auto unique_name = std::format("WiVRn Generic Tracker #{}", index + 1);
strlcpy(str, unique_name.c_str(), std::size(str));
@@ -140,17 +133,16 @@ xrt_result_t wivrn_generic_tracker::update_inputs()
{
return XRT_SUCCESS;
}
xrt_result_t wivrn_generic_tracker::get_tracked_pose(xrt_input_name name, int64_t at_timestamp_ns, xrt_space_relation * res)
{
std::chrono::nanoseconds extrapolation_time;
XrTime production_timestamp;
if (name == XRT_INPUT_GENERIC_TRACKER_POSE)
{
std::tie(extrapolation_time, *res) = poses.get_pose_at(at_timestamp_ns);
std::tie(production_timestamp, *res) = poses.get_at(at_timestamp_ns);
active = true;
cnx.update_tracker_enabled();
cnx.add_predict_offset(extrapolation_time);
cnx.add_tracking_request(device_id::BODY, at_timestamp_ns, production_timestamp);
return XRT_SUCCESS;
}
@@ -160,10 +152,6 @@ xrt_result_t wivrn_generic_tracker::get_tracked_pose(xrt_input_name name, int64_
void wivrn_generic_tracker::update_tracking(const from_headset::body_tracking & tracking, const from_headset::body_tracking::pose & pose, const clock_offset & offset)
{
if (!poses.update_tracking(tracking.production_timestamp, tracking.timestamp, pose, offset))
{
active = false;
cnx.update_tracker_enabled();
}
poses.update_tracking(tracking.production_timestamp, tracking.timestamp, pose, offset);
}
} // namespace wivrn
+1 -10
View File
@@ -34,9 +34,7 @@ public:
tracker_pose_list() = default;
bool update_tracking(XrTime produced_timestamp, XrTime timestamp, const from_headset::body_tracking::pose & pose, const clock_offset & offset);
std::pair<std::chrono::nanoseconds, xrt_space_relation> get_pose_at(XrTime at_timestamp_ns);
void update_tracking(XrTime produced_timestamp, XrTime timestamp, const from_headset::body_tracking::pose & pose, const clock_offset & offset);
static xrt_space_relation convert_pose(const wivrn::from_headset::body_tracking::pose &);
};
@@ -45,10 +43,8 @@ class wivrn_generic_tracker : public xrt_device
{
tracker_pose_list poses;
xrt_input pose_input;
std::atomic_bool active = false;
wivrn_session & cnx;
int index;
public:
using base = xrt_device;
@@ -58,10 +54,5 @@ public:
xrt_result_t get_tracked_pose(xrt_input_name name, int64_t at_timestamp_ns, xrt_space_relation * out_relation);
void update_tracking(const from_headset::body_tracking & tracking, const from_headset::body_tracking::pose & pose, const clock_offset & offset);
bool is_active()
{
return active;
}
};
} // namespace wivrn
+10 -7
View File
@@ -18,6 +18,8 @@
*/
#include "wivrn_hmd.h"
#include "os/os_time.h"
#include "wivrn_config.h"
#include "wivrn_session.h"
#include "xrt/xrt_defines.h"
@@ -129,9 +131,11 @@ xrt_result_t wivrn_hmd::get_tracked_pose(xrt_input_name name, int64_t at_timesta
return XRT_ERROR_INPUT_UNSUPPORTED;
}
auto [extrapolation_time, view] = views.get_at(at_timestamp_ns);
auto now = os_monotonic_get_ns();
auto target_ns = std::min(now + max_extrapolation_ns, at_timestamp_ns);
auto [production_timestamp, view] = views.get_at(target_ns);
*res = view.relation;
cnx->add_predict_offset(extrapolation_time);
cnx->add_tracking_request(device_id::HEAD, at_timestamp_ns, production_timestamp, now);
return XRT_SUCCESS;
}
@@ -143,7 +147,6 @@ void wivrn_hmd::update_tracking(const from_headset::tracking & tracking, const c
void wivrn_hmd::update_battery(const from_headset::battery & new_battery)
{
// We will only request a new sample if the current one is consumed
cnx->set_enabled(to_headset::tracking_control::id::battery, false);
std::lock_guard lock(mutex);
battery = new_battery;
}
@@ -163,8 +166,10 @@ xrt_result_t wivrn_hmd::get_view_poses(const xrt_vec3 * default_eye_relation,
xrt_fov * out_fovs,
xrt_pose * out_poses)
{
auto [extrapolation_time, view] = views.get_at(at_timestamp_ns);
cnx->add_predict_offset(extrapolation_time);
auto now = os_monotonic_get_ns();
auto target_ns = std::min(now + max_extrapolation_ns, at_timestamp_ns);
auto [production_timestamp, view] = views.get_at(target_ns);
cnx->add_tracking_request(device_id::HEAD, at_timestamp_ns, production_timestamp, now);
int flags = view.relation.relation_flags;
@@ -196,8 +201,6 @@ xrt_result_t wivrn_hmd::get_battery_status(bool * out_present,
bool * out_charging,
float * out_charge)
{
cnx->set_enabled(to_headset::tracking_control::id::battery, true);
std::lock_guard lock(mutex);
*out_present = battery.present;
*out_charging = battery.charging;
+5 -8
View File
@@ -29,9 +29,7 @@
#include "xrt/xrt_device.h"
#include "xrt/xrt_results.h"
#include <cmath>
#include <cstdint>
#include <cstring>
#include <openxr/openxr.h>
namespace wivrn
@@ -89,16 +87,15 @@ void wivrn_htc_face_tracker::update_tracking(const from_headset::tracking & trac
.eye_active = face->eye_active,
.lip_active = face->lip_active};
if (not face_list.update_tracking(tracking.production_timestamp, tracking.timestamp, data, offset))
cnx.set_enabled(to_headset::tracking_control::id::face, false);
face_list.update_tracking(face->timestamp, tracking.timestamp, data, offset);
}
xrt_result_t wivrn_htc_face_tracker::get_face_tracking(enum xrt_input_name facial_expression_type, int64_t at_timestamp_ns, struct xrt_facial_expression_set * inout_value)
{
if (facial_expression_type == XRT_INPUT_HTC_EYE_FACE_TRACKING)
{
cnx.set_enabled(to_headset::tracking_control::id::face, true);
auto [_, data] = face_list.get_at(at_timestamp_ns);
auto [production_timestamp, data] = face_list.get_at(at_timestamp_ns);
cnx.add_tracking_request(device_id::FACE, at_timestamp_ns, production_timestamp);
inout_value->base_expression_set_htc.is_active = data.eye_active;
inout_value->base_expression_set_htc.sample_time_ns = data.eye_sample_time;
@@ -112,8 +109,8 @@ xrt_result_t wivrn_htc_face_tracker::get_face_tracking(enum xrt_input_name facia
}
else if (facial_expression_type == XRT_INPUT_HTC_LIP_FACE_TRACKING)
{
cnx.set_enabled(to_headset::tracking_control::id::face, true);
auto [_, data] = face_list.get_at(at_timestamp_ns);
auto [production_timestamp, data] = face_list.get_at(at_timestamp_ns);
cnx.add_tracking_request(device_id::FACE, at_timestamp_ns, production_timestamp);
inout_value->base_expression_set_htc.is_active = data.lip_active;
inout_value->base_expression_set_htc.sample_time_ns = data.lip_sample_time;
+2 -2
View File
@@ -93,9 +93,9 @@ public:
return result;
}
bool update_tracking(const XrTime & production_timestamp, const XrTime & timestamp, const wivrn_htc_face_data & data, const clock_offset & offset)
void update_tracking(const XrTime & production_timestamp, const XrTime & timestamp, const wivrn_htc_face_data & data, const clock_offset & offset)
{
return this->add_sample(production_timestamp, timestamp, data, offset);
add_sample(production_timestamp, timestamp, data, offset);
}
};
+6
View File
@@ -76,6 +76,12 @@ wivrn_pacer::~wivrn_pacer()
compute_cv.notify_all();
}
uint64_t wivrn_pacer::get_frame_duration()
{
std::lock_guard lock(mutex);
return frame_duration_ns;
}
void wivrn_pacer::set_frame_duration(uint64_t frame_duration_ns)
{
std::lock_guard lock(mutex);
+1
View File
@@ -76,6 +76,7 @@ public:
wivrn_pacer(uint64_t frame_duration);
~wivrn_pacer();
uint64_t get_frame_duration();
void set_frame_duration(uint64_t frame_duration);
void predict(
+81 -109
View File
@@ -111,38 +111,6 @@ bool is_forced_extension(const char * ext_name)
return strstr(val, ext_name);
}
void wivrn::tracking_control_t::send(wivrn_connection & connection, bool now)
{
std::lock_guard lock(mutex);
if (std::chrono::steady_clock::now() < next_sample and not now)
return;
connection.send_stream(to_headset::tracking_control{
.min_offset = std::chrono::nanoseconds(min.exchange(80'000'000)),
.max_offset = std::chrono::nanoseconds(max.exchange(0)),
.enabled = enabled,
});
if (not now)
next_sample += std::chrono::seconds(1);
}
bool wivrn::tracking_control_t::get_enabled(to_headset::tracking_control::id id)
{
std::lock_guard lock(mutex);
return this->enabled[size_t(id)];
}
bool wivrn::tracking_control_t::set_enabled(to_headset::tracking_control::id id, bool enabled)
{
std::lock_guard lock(mutex);
bool changed = enabled != this->enabled[size_t(id)];
if (!changed)
return false;
U_LOG_I("%s tracking: %s", std::string(magic_enum::enum_name(id)).c_str(), enabled ? "enabled" : "disabled");
this->enabled[size_t(id)] = enabled;
return changed;
}
wivrn::wivrn_session::wivrn_session(std::unique_ptr<wivrn_connection> connection, u_system & system) :
xrt_system_devices{
.get_roles = [](xrt_system_devices * self, xrt_system_roles * out_roles) { return ((wivrn_session *)self)->get_roles(out_roles); },
@@ -152,6 +120,7 @@ wivrn::wivrn_session::wivrn_session(std::unique_ptr<wivrn_connection> connection
},
connection(std::move(connection)),
xrt_system(system),
control(*this->connection),
hmd(this, get_info()),
left_controller(XRT_DEVICE_TOUCH_CONTROLLER, 0, &hmd, this),
right_controller(XRT_DEVICE_TOUCH_CONTROLLER, 1, &hmd, this),
@@ -247,7 +216,7 @@ wivrn::wivrn_session::wivrn_session(std::unique_ptr<wivrn_connection> connection
#endif
if (get_info().eye_gaze || is_forced_extension("EXT_eye_gaze_interaction"))
{
eye_tracker = std::make_unique<wivrn_eye_tracker>(&hmd);
eye_tracker = std::make_unique<wivrn_eye_tracker>(&hmd, *this);
static_roles.eyes = eye_tracker.get();
xdevs[xdev_count++] = eye_tracker.get();
}
@@ -328,7 +297,7 @@ wivrn::wivrn_session::wivrn_session(std::unique_ptr<wivrn_connection> connection
try
{
uinput_handler.emplace();
tracking_control.set_enabled(to_headset::tracking_control::id::hid_input, true);
send_control(to_headset::feature_control{to_headset::feature_control::hid_input, true});
}
catch (...)
{
@@ -410,20 +379,23 @@ xrt_result_t wivrn::wivrn_session::create_session(std::unique_ptr<wivrn_connecti
void wivrn_session::start(ipc_server * server)
{
assert(not thread.joinable());
assert(not net_thread.joinable());
mnd_ipc_server = server;
thread = std::jthread([this](auto stop_token) { return run(stop_token); });
net_thread = std::jthread([this](auto stop_token) { return run_net(stop_token); });
worker_thread = std::jthread([this](std::stop_token stop) { return run_worker(stop); });
}
void wivrn_session::stop()
{
thread = std::jthread();
net_thread = std::jthread();
worker_thread = std::jthread();
}
bool wivrn_session::request_stop()
{
assert(mnd_ipc_server);
bool b = thread.request_stop();
bool b = net_thread.request_stop();
worker_thread.request_stop();
ipc_server_stop(mnd_ipc_server);
return b;
}
@@ -444,6 +416,16 @@ void wivrn_session::unset_comp_target()
comp_target = nullptr;
}
void wivrn_session::add_tracking_request(device_id device, int64_t at_ns, int64_t produced_ns, int64_t now)
{
control.add_request(device, now, at_ns, produced_ns);
}
void wivrn_session::add_tracking_request(device_id device, int64_t at_ns, int64_t produced_ns)
{
control.add_request(device, os_monotonic_get_ns(), at_ns, produced_ns);
}
void wivrn_session::operator()(from_headset::headset_info_packet &&)
{
U_LOG_W("unexpected headset info packet, ignoring");
@@ -515,7 +497,8 @@ static xrt_device_name get_name(interaction_profile profile)
}
throw std::runtime_error("invalid interaction profile id " + std::to_string(int(profile)));
}
void wivrn_session::operator()(from_headset::trackings && tracking)
void wivrn_session::operator()(const from_headset::tracking & tracking)
{
auto left = (roles.left == -1 || roles.left == left_controller_index || roles.left == left_hand_interaction_index) ? get_name(tracking.interaction_profiles[0]) : XRT_DEVICE_INVALID;
auto right = (roles.right == -1 || roles.right == right_controller_index || roles.right == right_hand_interaction_index) ? get_name(tracking.interaction_profiles[1]) : XRT_DEVICE_INVALID;
@@ -542,8 +525,6 @@ void wivrn_session::operator()(from_headset::trackings && tracking)
{
left_controller.reset_history();
roles.left = left_controller_index;
set_enabled(device_id::LEFT_PINCH_POSE, false);
set_enabled(device_id::LEFT_POKE, false);
}
else
{
@@ -563,8 +544,6 @@ void wivrn_session::operator()(from_headset::trackings && tracking)
{
right_controller.reset_history();
roles.right = right_controller_index;
set_enabled(device_id::RIGHT_PINCH_POSE, false);
set_enabled(device_id::RIGHT_POKE, false);
}
else
{
@@ -575,12 +554,6 @@ void wivrn_session::operator()(from_headset::trackings && tracking)
++roles.generation_id;
}
for (auto & item: tracking.items)
(*this)(item);
}
void wivrn_session::operator()(const from_headset::tracking & tracking)
{
if (tracking.state_flags & from_headset::tracking::state_flags::recentered)
{
U_LOG_I("recentering requested");
@@ -590,6 +563,12 @@ void wivrn_session::operator()(const from_headset::tracking & tracking)
auto offset = offset_est.get_offset();
if (offset)
{
XrDuration latency = os_monotonic_get_ns() - offset.from_headset(tracking.production_timestamp);
tracking_latency = std::lerp(tracking_latency.load(), latency, 0.1);
}
hmd.update_tracking(tracking, offset);
if (roles.left == left_hand_interaction_index)
left_hand_interaction.update_tracking(tracking, offset);
@@ -689,54 +668,6 @@ void wivrn_session::operator()(from_headset::timesync_response && timesync)
offset_est.add_sample(timesync);
}
static auto to_tracking_control(device_id id)
{
using tid = to_headset::tracking_control::id;
switch (id)
{
case device_id::LEFT_AIM:
return tid::left_aim;
case device_id::LEFT_GRIP:
return tid::left_grip;
case device_id::LEFT_PALM:
return tid::left_palm;
case device_id::LEFT_PINCH_POSE:
return tid::left_pinch;
case device_id::LEFT_POKE:
return tid::left_poke;
case device_id::RIGHT_AIM:
return tid::right_aim;
case device_id::RIGHT_GRIP:
return tid::right_grip;
case device_id::RIGHT_PALM:
return tid::right_palm;
case device_id::RIGHT_PINCH_POSE:
return tid::right_pinch;
case device_id::RIGHT_POKE:
return tid::right_poke;
default:
break;
}
__builtin_unreachable();
}
void wivrn_session::set_enabled(to_headset::tracking_control::id id, bool enabled)
{
tracking_control.set_enabled(id, enabled);
}
void wivrn_session::set_enabled(device_id id, bool enabled)
{
if (tracking_control.set_enabled(to_tracking_control(id), enabled) and enabled)
tracking_control.send(*connection, true);
}
void wivrn_session::update_tracker_enabled()
{
bool active = std::ranges::any_of(generic_trackers, [](auto & t) { return t->is_active(); });
if (tracking_control.set_enabled(to_headset::tracking_control::id::generic_tracker, active) and active)
tracking_control.send(*connection, true);
}
void wivrn_session::operator()(from_headset::feedback && feedback)
{
clock_offset o = offset_est.get_offset();
@@ -999,10 +930,18 @@ struct refresh_rate_adjuster
settings(settings)
{}
bool advance(std::chrono::steady_clock::time_point now)
{
if (next > now)
return false;
next += period;
return true;
}
void adjust(wivrn_connection & cnx)
{
auto locked = settings.lock();
if (locked->preferred_refresh_rate != 0 or info.available_refresh_rates.size() < 2 or std::chrono::steady_clock::now() < next)
if (locked->preferred_refresh_rate != 0 or info.available_refresh_rates.size() < 2)
return;
// Maximum refresh rate the application can reach
@@ -1021,7 +960,6 @@ struct refresh_rate_adjuster
cnx.send_control(to_headset::refresh_rate_change{.fps = requested});
last = requested;
}
next += period;
}
void reset()
@@ -1030,31 +968,65 @@ struct refresh_rate_adjuster
}
};
void wivrn_session::run(std::stop_token stop)
void wivrn_session::run_net(std::stop_token stop)
{
while (not stop.stop_requested())
{
try
{
connection->poll(*this, 20);
}
catch (const std::exception & e)
{
U_LOG_E("Exception in network thread: %s", e.what());
worker_thread = std::jthread();
reconnect(stop);
worker_thread = std::jthread([this](std::stop_token stop) { return run_worker(stop); });
}
}
}
void wivrn_session::run_worker(std::stop_token stop)
{
refresh_rate_adjuster refresh(connection->info(), settings, app_pacers);
while (not stop.stop_requested())
{
try
{
offset_est.request_sample(*connection);
tracking_control.send(*connection);
std::this_thread::sleep_until(std::min(
{
refresh.next,
control.next,
offset_est.next(),
}));
auto now = std::chrono::steady_clock::now();
offset_est.request_sample(now, *connection);
const bool do_refresh = refresh.advance(now);
const bool do_control = control.advance(now);
if (do_refresh or do_control)
{
std::shared_lock lock(comp_target_mutex);
if (comp_target)
{
if (comp_target->requested_refresh_rate == 0)
refresh.adjust(*connection);
if (do_refresh)
{
{
scoped_lock lock(xrt_system.sessions.mutex);
if (xrt_system.sessions.count == 0)
comp_target->requested_refresh_rate = 0;
}
if (comp_target->requested_refresh_rate == 0)
refresh.adjust(*connection);
}
if (do_control)
control.resolve(comp_target->pacer.get_frame_duration(), tracking_latency);
}
}
poll_session_loss();
connection->poll(*this, 20);
}
catch (const std::exception & e)
{
U_LOG_E("Exception in network thread: %s", e.what());
reconnect(stop);
refresh.reset();
U_LOG_E("Exception in worker thread: %s", e.what());
}
}
}
@@ -1147,12 +1119,12 @@ void wivrn_session::reconnect(std::stop_token stop)
void wivrn_session::poll_session_loss()
{
assert(mnd_ipc_server);
scoped_lock lock(mnd_ipc_server->global_state.lock);
auto locked = session_loss.lock();
auto now = os_monotonic_get_ns();
if (locked->empty())
return;
auto it = locked->begin();
scoped_lock lock(mnd_ipc_server->global_state.lock);
while (it != locked->end() and it->second <= now)
{
for (auto & t: mnd_ipc_server->threads)
+9 -50
View File
@@ -21,6 +21,7 @@
#include "clock_offset.h"
#include "driver/app_pacer.h"
#include "tracking_control.h"
#include "utils/thread_safe.h"
#include "wivrn_connection.h"
#include "wivrn_controller.h"
@@ -30,7 +31,6 @@
#include "wivrn_uinput.h"
#include "xrt/xrt_results.h"
#include "xrt/xrt_system.h"
#include <atomic>
#include <fstream>
#include <map>
#include <memory>
@@ -55,43 +55,6 @@ struct audio_device;
struct wivrn_comp_target;
struct wivrn_comp_target_factory;
class tracking_control_t
{
using T = std::chrono::nanoseconds::rep;
std::atomic<T> min;
std::atomic<T> max;
std::chrono::steady_clock::time_point next_sample;
std::mutex mutex;
decltype(to_headset::tracking_control::enabled) enabled;
public:
tracking_control_t() :
next_sample(std::chrono::steady_clock::now())
{
enabled.fill(true);
}
void add(std::chrono::nanoseconds s)
{
auto sample = s.count();
T prev = max;
while (prev < sample and max.compare_exchange_weak(prev, sample))
{
}
if (sample > 0)
{
prev = min;
while (prev > sample and min.compare_exchange_weak(prev, sample))
{
}
}
}
void send(wivrn_connection & connection, bool now = false);
bool get_enabled(to_headset::tracking_control::id id);
// Return true if value changed
bool set_enabled(to_headset::tracking_control::id id, bool enabled);
};
class wivrn_session : public xrt_system_devices
{
friend wivrn_comp_target_factory;
@@ -111,7 +74,7 @@ class wivrn_session : public xrt_system_devices
.gamepad = -1,
};
tracking_control_t tracking_control;
tracking_control control;
wivrn_hmd hmd;
wivrn_controller left_controller;
@@ -133,6 +96,7 @@ class wivrn_session : public xrt_system_devices
wivrn_comp_target * comp_target;
clock_offset_estimator offset_est;
std::atomic<XrDuration> tracking_latency; // production to reception time
std::mutex csv_mutex;
std::ofstream feedback_csv;
@@ -145,7 +109,8 @@ class wivrn_session : public xrt_system_devices
// when sessions shall be destroyed, key is client id, value is timestamp
thread_safe<std::map<uint32_t, int64_t>> session_loss;
std::jthread thread;
std::jthread net_thread;
std::jthread worker_thread;
wivrn_session(std::unique_ptr<wivrn_connection> connection, u_system &);
@@ -183,14 +148,8 @@ public:
return hmd;
}
void add_predict_offset(std::chrono::nanoseconds off)
{
tracking_control.add(off);
}
void set_enabled(to_headset::tracking_control::id id, bool enabled);
void set_enabled(device_id id, bool enabled);
void update_tracker_enabled();
void add_tracking_request(device_id, int64_t at_ns, int64_t produced_ns, int64_t now);
void add_tracking_request(device_id, int64_t at_ns, int64_t produced_ns);
void operator()(from_headset::crypto_handshake &&) {}
void operator()(from_headset::pin_check_1 &&) {}
@@ -198,7 +157,6 @@ public:
void operator()(from_headset::headset_info_packet &&);
void operator()(const from_headset::settings_changed &);
void operator()(from_headset::handshake &&) {}
void operator()(from_headset::trackings &&);
void operator()(const from_headset::tracking &);
void operator()(from_headset::derived_pose &&);
void operator()(from_headset::hand_tracking &&);
@@ -247,7 +205,8 @@ public:
void dump_time(const std::string & event, uint64_t frame, int64_t time, uint8_t stream = -1, const char * extra = "");
private:
void run(std::stop_token stop);
void run_net(std::stop_token stop);
void run_worker(std::stop_token stop);
void reconnect(std::stop_token stop);
void poll_session_loss();
+4 -4
View File
@@ -59,8 +59,8 @@ if __name__ == "__main__":
monado_commit = open(os.path.join(root, "monado-rev")).read()
boostpfr_url = cmake.get("boostpfr", "URL")
boostpfr_sha256 = cmake.get("boostpfr", "URL_HASH").split("=")[-1]
boost_url = cmake.get("boost", "URL")
boost_sha256 = cmake.get("boost", "URL_HASH").split("=")[-1]
try:
git_commit = subprocess.check_output(
@@ -93,8 +93,8 @@ if __name__ == "__main__":
template = template.replace("WIVRN_GIT_DESC", git_desc)
template = template.replace("WIVRN_GIT_COMMIT", git_commit)
template = template.replace("BOOSTPFR_URL", boostpfr_url)
template = template.replace("BOOSTPFR_SHA256", boostpfr_sha256)
template = template.replace("BOOST_URL", boost_url)
template = template.replace("BOOST_SHA256", boost_sha256)
template = template.replace("MONADO_COMMIT", monado_commit)
with open(os.path.join(args.out, "io.github.wivrn.wivrn.yml"), "w") as f: