move stuff in common, clang-format, update copyright

This commit is contained in:
Guillaume Meunier
2022-11-13 11:00:04 +01:00
parent 294c4f81ba
commit 4baf2b17eb
62 changed files with 2291 additions and 2846 deletions
+13 -8
View File
@@ -3,18 +3,23 @@ FetchContent_Declare(boostpfr URL https://github.com/boostorg/pfr/archive/refs/t
FetchContent_MakeAvailable(boostpfr)
execute_process(COMMAND git describe --always OUTPUT_VARIABLE GIT_VERSION)
string(STRIP ${GIT_VERSION} GIT_VERSION)
add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/version.cpp
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/version.cpp
COMMAND ${CMAKE_COMMAND}
-D GIT_EXECUTABLE=${GIT_EXECUTABLE}
-D INPUT_FILE=${CMAKE_SOURCE_DIR}/common/version.cpp.in
-D OUTPUT_FILE=${CMAKE_BINARY_DIR}/version.cpp
-D INPUT_FILE=${CMAKE_CURRENT_SOURCE_DIR}/version.cpp.in
-D OUTPUT_FILE=${CMAKE_CURRENT_BINARY_DIR}/version.cpp
-P ${CMAKE_SOURCE_DIR}/cmake/GitVersion.cmake
)
file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS "*.cpp")
add_library(wivrn-common STATIC ${CMAKE_BINARY_DIR}/version.cpp ${LOCAL_SOURCES})
configure_file(wivrn_config.h.in wivrn_config.h)
target_include_directories(wivrn-common PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
add_library(wivrn-common STATIC
wivrn_sockets.cpp
${CMAKE_CURRENT_BINARY_DIR}/version.cpp
)
target_link_libraries(wivrn-common PUBLIC Boost::pfr)
target_compile_features(wivrn-common PRIVATE cxx_std_20)
target_include_directories(wivrn-common PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
+24
View File
@@ -0,0 +1,24 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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
#cmakedefine WIVRN_HAVE_X264
#cmakedefine WIVRN_HAVE_CUDA
#cmakedefine WIVRN_HAVE_FFMPEG
+251
View File
@@ -0,0 +1,251 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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 <array>
#include <chrono>
#include <cstdint>
#include <netinet/in.h>
#include <optional>
#include <string>
#include <variant>
#include <vector>
#include <openxr/openxr.h>
namespace xrt::drivers::wivrn
{
static const int control_port = 9757;
static const int stream_port = 9757;
enum class device_id : uint8_t
{
HEAD, // /user/head
LEFT_CONTROLLER_HAPTIC, // /user/hand/left/output/haptic
RIGHT_CONTROLLER_HAPTIC, // /user/hand/right/output/haptic
LEFT_GRIP, // /user/hand/left/input/grip/pose
LEFT_AIM, // /user/hand/left/input/aim/pose
RIGHT_GRIP, // /user/hand/right/input/grip/pose
RIGHT_AIM, // /user/hand/right/input/aim/pose
X_CLICK, // /user/hand/left/input/x/click
X_TOUCH, // /user/hand/left/input/x/touch
Y_CLICK, // /user/hand/left/input/y/click
Y_TOUCH, // /user/hand/left/input/y/touch
MENU_CLICK, // /user/hand/left/input/menu/click
LEFT_SQUEEZE_VALUE, // /user/hand/left/input/squeeze/value
LEFT_TRIGGER_VALUE, // /user/hand/left/input/trigger/value
LEFT_TRIGGER_TOUCH, // /user/hand/left/input/trigger/touch
LEFT_THUMBSTICK_X, // /user/hand/left/input/thumbstick/x
LEFT_THUMBSTICK_Y, // /user/hand/left/input/thumbstick/y
LEFT_THUMBSTICK_CLICK, // /user/hand/left/input/thumbstick/click
LEFT_THUMBSTICK_TOUCH, // /user/hand/left/input/thumbstick/touch
LEFT_THUMBREST_TOUCH, // /user/hand/left/input/thumbrest/touch
A_CLICK, // /user/hand/right/input/a/click
A_TOUCH, // /user/hand/right/input/a/touch
B_CLICK, // /user/hand/right/input/b/click
B_TOUCH, // /user/hand/right/input/b/touch
SYSTEM_CLICK, // /user/hand/right/input/system/click
RIGHT_SQUEEZE_VALUE, // /user/hand/right/input/squeeze/value
RIGHT_TRIGGER_VALUE, // /user/hand/right/input/trigger/value
RIGHT_TRIGGER_TOUCH, // /user/hand/right/input/trigger/touch
RIGHT_THUMBSTICK_X, // /user/hand/right/input/thumbstick/x
RIGHT_THUMBSTICK_Y, // /user/hand/right/input/thumbstick/y
RIGHT_THUMBSTICK_CLICK, // /user/hand/right/input/thumbstick/click
RIGHT_THUMBSTICK_TOUCH, // /user/hand/right/input/thumbstick/touch
RIGHT_THUMBREST_TOUCH, // /user/hand/right/input/thumbrest/touch
};
enum video_codec
{
h264,
hevc,
h265 = hevc,
};
namespace from_headset
{
struct headset_info_packet
{
uint32_t recommended_eye_width;
uint32_t recommended_eye_height;
std::vector<float> available_refresh_rates;
float preferred_refresh_rate;
uint32_t microphone_sample_rate;
};
struct tracking
{
enum flags : uint8_t
{
orientation_valid = 1 << 0,
position_valid = 1 << 1,
linear_velocity_valid = 1 << 2,
angular_velocity_valid = 1 << 3,
orientation_tracked = 1 << 4,
position_tracked = 1 << 5
};
struct pose
{
device_id device;
XrPosef pose;
XrVector3f linear_velocity;
XrVector3f angular_velocity;
uint8_t flags;
};
struct view
{
// Relative to XR_REFERENCE_SPACE_TYPE_VIEW
XrPosef pose;
XrFovf fov;
};
uint64_t timestamp;
XrViewStateFlags flags;
std::array<view, 2> views;
std::vector<pose> device_poses;
};
struct inputs
{
struct input_value
{
device_id id;
float value;
};
std::vector<input_value> values;
};
struct timesync_response
{
std::chrono::nanoseconds query;
uint64_t response;
};
struct feedback
{
uint64_t frame_index;
uint8_t stream_index;
// Timestamps
uint64_t received_first_packet;
uint64_t received_last_packet;
uint64_t reconstructed;
uint64_t sent_to_decoder;
uint64_t received_from_decoder;
uint64_t blitted;
uint64_t displayed;
std::array<XrPosef, 2> received_pose;
std::array<XrPosef, 2> real_pose;
uint8_t data_packets;
uint8_t parity_packets;
uint8_t received_data_packets;
uint8_t received_parity_packets;
};
using control_packets = std::variant<headset_info_packet, feedback>;
using stream_packets = std::variant<tracking, inputs, timesync_response>;
} // namespace from_headset
namespace to_headset
{
struct video_stream_description
{
struct item
{
uint16_t width;
uint16_t height;
uint16_t offset_x;
uint16_t offset_y;
video_codec codec;
};
uint16_t width;
uint16_t height;
float fps;
std::vector<item> items;
};
struct video_stream_data_shard
{
inline static const size_t max_payload_size = 1400;
enum flags : uint8_t
{
start_of_slice = 1,
end_of_slice = 1 << 1,
end_of_frame = 1 << 2,
};
// Identifier of stream in video_stream_description
uint8_t stream_item_idx;
// Counter increased for each frame
uint64_t frame_idx;
// Identifier of the shard within the frame
uint16_t shard_idx;
uint8_t flags;
// Actual video data, may contain multiple NAL units
std::vector<uint8_t> payload;
// Position information, must be present on last video shard
struct view_info_t
{
// ns in headset time referential
uint64_t display_time;
std::array<XrPosef, 2> pose;
std::array<XrFovf, 2> fov;
};
std::optional<view_info_t> view_info;
};
struct video_stream_parity_shard
{
uint8_t stream_item_idx;
uint64_t frame_idx;
uint16_t data_shard_count;
uint8_t num_parity_elements;
uint8_t parity_element;
// Parity data
std::vector<uint8_t> payload;
};
struct haptics
{
device_id id;
std::chrono::nanoseconds duration;
float frequency;
float amplitude;
};
struct timesync_query
{
std::chrono::nanoseconds query;
};
using stream_packets = std::variant<video_stream_data_shard, video_stream_parity_shard, haptics, timesync_query>;
using control_packets = std::variant<video_stream_description>;
} // namespace to_headset
} // namespace xrt::drivers::wivrn
+519
View File
@@ -0,0 +1,519 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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 "boost/pfr/core.hpp"
#include "boost/pfr/tuple_size.hpp"
#include <array>
#include <boost/pfr.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <optional>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <variant>
#include <vector>
namespace xrt::drivers::wivrn
{
namespace details
{
struct hash_context
{
// FNV1a hash
static const uint64_t fnv_prime = 0x100000001b3;
static const uint64_t fnv_offset_basis = 0xcbf29ce484222325;
uint64_t hash = fnv_offset_basis;
constexpr uint64_t feed(std::string_view s)
{
for (const char c: s)
hash = (hash ^ c) * fnv_prime;
return hash;
}
constexpr uint64_t feed_unsigned(uint64_t n)
{
if (n >= 10)
feed(n / 10);
char digit[] = "0";
digit[0] += n % 10;
feed(digit);
return hash;
}
constexpr uint64_t feed(int64_t n)
{
if (n < 0)
{
feed("-");
feed_unsigned(static_cast<uint64_t>(-n));
}
else
{
feed_unsigned(static_cast<uint64_t>(n));
}
return hash;
}
};
} // namespace details
template <typename T, typename Enable = void>
struct serialization_traits;
class deserialization_error : public std::runtime_error
{
public:
deserialization_error() :
std::runtime_error("Deserialization error") {}
};
class serialization_packet
{
std::vector<uint8_t> buffer;
public:
serialization_packet() = default;
void write(const void * data, size_t size)
{
size_t index = buffer.size();
buffer.resize(index + size);
memcpy(&buffer[index], data, size);
}
const uint8_t * data() const
{
return buffer.data();
}
size_t size() const
{
return buffer.size();
}
template <typename T>
void serialize(const T & value)
{
serialization_traits<T>::serialize(value, *this);
}
operator std::vector<uint8_t> &&() &&
{
return std::move(buffer);
}
};
class deserialization_packet
{
std::vector<uint8_t> buffer;
size_t read_index;
public:
deserialization_packet() :
read_index(0) {}
explicit deserialization_packet(std::vector<uint8_t> buffer, size_t skip = 0) :
buffer(std::move(buffer)), read_index(skip)
{}
void read(void * data, size_t size)
{
check_remaining_size(size);
memcpy(data, &buffer[read_index], size);
read_index += size;
}
size_t remaining() const
{
return buffer.size() - read_index;
}
bool empty() const
{
return buffer.size() <= read_index;
}
void check_remaining_size(size_t min_size) const
{
if (min_size > remaining())
throw deserialization_error();
}
template <typename T>
T deserialize()
{
return serialization_traits<T>::deserialize(*this);
}
};
template <typename T>
struct serialization_traits<T, std::enable_if_t<std::is_arithmetic_v<T>>>
{
static constexpr void type_hash(details::hash_context & h)
{
if constexpr (std::is_floating_point_v<T>)
h.feed("float");
else if constexpr (std::is_integral_v<T>)
{
if constexpr (std::is_unsigned_v<T>)
h.feed("uint");
else
h.feed("int");
}
h.feed(sizeof(T) * 8);
}
static void serialize(T value, serialization_packet & packet)
{
packet.write(&value, sizeof(value));
}
static T deserialize(deserialization_packet & packet)
{
T value;
packet.read((char *)&value, sizeof(value));
return value;
}
};
template <typename T>
struct serialization_traits<T, std::enable_if_t<std::is_enum_v<T>>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("enum");
h.feed(sizeof(T) * 8);
}
static void serialize(T value, serialization_packet & packet)
{
packet.write(&value, sizeof(value));
}
static T deserialize(deserialization_packet & packet)
{
T value;
packet.read((char *)&value, sizeof(value));
return value;
}
};
template <class>
struct is_stdarray : public std::false_type
{};
template <class T, size_t N>
struct is_stdarray<std::array<T, N>> : public std::true_type
{};
template <typename T>
inline constexpr bool is_stdarray_v = is_stdarray<T>::value;
template <typename T>
struct serialization_traits<T, std::enable_if_t<std::is_aggregate_v<T> && !is_stdarray_v<T>>>
{
template <size_t I>
static constexpr void aux2(details::hash_context & h)
{
if constexpr (I > 0)
h.feed(",");
serialization_traits<boost::pfr::tuple_element_t<I, T>>::type_hash(h);
}
template <size_t... I>
static constexpr void aux1(details::hash_context & h, std::index_sequence<I...>)
{
(aux2<I>(h), ...);
}
static constexpr void type_hash(details::hash_context & h)
{
h.feed("structure{");
aux1(h, std::make_index_sequence<boost::pfr::tuple_size_v<T>>());
h.feed("}");
}
static void serialize(const T & value, serialization_packet & packet)
{
boost::pfr::for_each_field(value, [&](const auto & x) { packet.serialize(x); });
}
static T deserialize(deserialization_packet & packet)
{
T value;
boost::pfr::for_each_field(
value, [&](auto & x) { x = packet.deserialize<std::remove_reference_t<decltype(x)>>(); });
return value;
}
};
template <>
struct serialization_traits<std::string>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("string");
}
static void serialize(const std::string & value, serialization_packet & packet)
{
packet.serialize<uint64_t>(value.size());
packet.write(value.data(), value.size());
}
static std::string deserialize(deserialization_packet & packet)
{
std::string value;
size_t size = packet.deserialize<uint64_t>();
packet.check_remaining_size(size);
value.resize(size);
packet.read(value.data(), size);
return value;
}
};
template <typename T>
struct serialization_traits<std::vector<T>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("vector<");
serialization_traits<T>::type_hash(h);
h.feed(">");
}
static void serialize(const std::vector<T> & value, serialization_packet & packet)
{
packet.serialize<uint64_t>(value.size());
for (const T & i: value)
packet.serialize<T>(i);
}
static std::vector<T> deserialize(deserialization_packet & packet)
{
std::vector<T> value;
size_t size = packet.deserialize<uint64_t>();
packet.check_remaining_size(size);
value.reserve(size);
for (size_t i = 0; i < size; i++)
{
value.emplace_back(packet.deserialize<T>());
}
return value;
}
};
template <typename T>
struct serialization_traits<std::optional<T>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("optional<");
serialization_traits<T>::type_hash(h);
h.feed(">");
}
static void serialize(const std::optional<T> & value, serialization_packet & packet)
{
if (value)
{
packet.serialize<bool>(true);
packet.serialize<T>(*value);
}
else
{
packet.serialize<bool>(false);
}
}
static std::optional<T> deserialize(deserialization_packet & packet)
{
if (packet.deserialize<bool>())
return packet.deserialize<T>();
else
return std::nullopt;
}
};
template <typename T, size_t N>
struct serialization_traits<std::array<T, N>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("array<");
serialization_traits<T>::type_hash(h);
h.feed(",");
h.feed(N);
h.feed(">");
}
static void serialize(const std::array<T, N> & value, serialization_packet & packet)
{
for (const T & i: value)
packet.serialize<T>(i);
}
static std::array<T, N> deserialize(deserialization_packet & packet)
{
std::array<T, N> value;
for (size_t i = 0; i < N; i++)
{
value[i] = packet.deserialize<T>();
}
return value;
}
};
template <typename... T>
struct serialization_traits<std::variant<T...>>
{
template <typename U, typename... V>
static constexpr void type_list_hash(details::hash_context & h)
{
serialization_traits<U>::type_hash(h);
if constexpr (sizeof...(V) > 0)
{
h.feed(",");
type_list_hash<V...>(h);
}
}
static constexpr void type_hash(details::hash_context & h)
{
h.feed("variant<");
type_list_hash<T...>(h);
h.feed(">");
}
static void serialize(const std::variant<T...> & value, serialization_packet & packet)
{
packet.serialize<uint32_t>(value.index());
std::visit([&](const auto & x) { packet.serialize(x); }, value);
}
template <size_t I>
using i_th_type = std::tuple_element_t<I, std::tuple<T...>>;
template <size_t... I>
static std::variant<T...> deserialize_aux(deserialization_packet & packet, size_t type_index, std::index_sequence<I...>)
{
std::variant<T...> value;
((I == type_index ? (void)(value = packet.deserialize<i_th_type<I>>()) : (void)0), ...);
return value;
}
static std::variant<T...> deserialize(deserialization_packet & packet)
{
uint32_t type_index = packet.deserialize<uint32_t>();
if (type_index >= sizeof...(T))
throw deserialization_error();
return deserialize_aux(packet, type_index, std::make_index_sequence<sizeof...(T)>());
}
};
template <typename Rep, typename Period>
struct serialization_traits<std::chrono::duration<Rep, Period>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("duration<");
serialization_traits<Rep>::type_hash(h);
h.feed(",");
h.feed(Period::num);
h.feed("/");
h.feed(Period::den);
h.feed(">");
}
static void serialize(const std::chrono::duration<Rep, Period> & value, serialization_packet & packet)
{
packet.serialize<Rep>(value.count());
}
static std::chrono::duration<Rep, Period> deserialize(deserialization_packet & packet)
{
Rep nsec = packet.deserialize<Rep>();
return std::chrono::duration<Rep, Period>{nsec};
}
};
namespace unit_tests
{
template <typename T>
constexpr uint64_t hash(T s)
{
return details::hash_context{}.feed(s);
}
static_assert(hash("test") == 0xf9e6e6ef197c2b25);
static_assert(hash(1234) == 0x1fabbdf10314a21d);
static_assert(hash(-1234) == 0x77fa1c9653db5a84);
static_assert(hash(0) == 0xaf63ad4c86019caf);
template <typename T>
constexpr uint64_t serialization_type_hash()
{
details::hash_context h;
serialization_traits<T>::type_hash(h);
return h.hash;
}
static_assert(serialization_type_hash<bool>() == hash("uint8"));
static_assert(serialization_type_hash<int>() == hash("int32"));
static_assert(serialization_type_hash<float>() == hash("float32"));
static_assert(serialization_type_hash<double>() == hash("float64"));
static_assert(serialization_type_hash<std::chrono::nanoseconds>() == hash("duration<int64,1/1000000000>"));
static_assert(serialization_type_hash<std::optional<int>>() == hash("optional<int32>"));
static_assert(serialization_type_hash<std::vector<int>>() == hash("vector<int32>"));
static_assert(serialization_type_hash<std::array<int, 42>>() == hash("array<int32,42>"));
static_assert(serialization_type_hash<std::string>() == hash("string"));
static_assert(serialization_type_hash<std::variant<int, float>>() == hash("variant<int32,float32>"));
struct test
{
int x;
float y;
};
static_assert(serialization_type_hash<test>() == hash("structure{int32,float32}"));
} // namespace unit_tests
} // namespace xrt::drivers::wivrn
+343
View File
@@ -0,0 +1,343 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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 "wivrn_sockets.h"
#include <arpa/inet.h>
#include <cassert>
#include <memory>
#include <netdb.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <system_error>
#include <unistd.h>
const char * xrt::drivers::wivrn::invalid_packet::what() const noexcept
{
return "Invalid packet";
}
const char * xrt::drivers::wivrn::socket_shutdown::what() const noexcept
{
return "Socket shutdown";
}
xrt::drivers::wivrn::socket_base::socket_base(xrt::drivers::wivrn::socket_base && other) :
fd(other.fd)
{
other.fd = -1;
}
xrt::drivers::wivrn::socket_base::~socket_base()
{
if (fd >= 0)
::close(fd);
}
xrt::drivers::wivrn::UDP::UDP()
{
fd = socket(AF_INET6, SOCK_DGRAM, 0);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::bind(int port)
{
sockaddr_in6 bind_addr{};
bind_addr.sin6_family = AF_INET6;
bind_addr.sin6_addr = IN6ADDR_ANY_INIT;
bind_addr.sin6_port = htons(port);
if (::bind(fd, (sockaddr *)&bind_addr, sizeof(bind_addr)) < 0)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::connect(in6_addr address, int port)
{
sockaddr_in6 sa;
sa.sin6_family = AF_INET6;
sa.sin6_addr = address;
sa.sin6_port = htons(port);
if (::connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::connect(in_addr address, int port)
{
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr = address;
sa.sin_port = htons(port);
if (::connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::subscribe_multicast(in6_addr address)
{
assert(IN6_IS_ADDR_MULTICAST(&address));
ipv6_mreq subscribe{};
subscribe.ipv6mr_multiaddr = address;
if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &subscribe, sizeof(subscribe)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
}
void xrt::drivers::wivrn::UDP::unsubscribe_multicast(in6_addr address)
{
assert(IN6_IS_ADDR_MULTICAST(&address));
ipv6_mreq subscribe{};
subscribe.ipv6mr_multiaddr = address;
if (setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &subscribe, sizeof(subscribe)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
}
void xrt::drivers::wivrn::UDP::set_receive_buffer_size(int size)
{
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
}
void xrt::drivers::wivrn::TCP::init()
{
int nodelay = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
mutex = std::make_unique<std::mutex>();
}
xrt::drivers::wivrn::TCP::TCP(int fd)
{
this->fd = fd;
init();
}
xrt::drivers::wivrn::TCP::TCP(in6_addr address, int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
sockaddr_in6 sa;
sa.sin6_family = AF_INET6;
sa.sin6_addr = address;
sa.sin6_port = htons(port);
if (connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
init();
}
xrt::drivers::wivrn::TCP::TCP(in_addr address, int port)
{
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr = address;
sa.sin_port = htons(port);
if (connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
init();
}
xrt::drivers::wivrn::TCPListener::TCPListener(int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
if (fd < 0)
{
throw std::system_error{errno, std::generic_category()};
}
int reuse_addr = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
sockaddr_in6 addr{};
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(port);
addr.sin6_addr = in6addr_any;
if (bind(fd, (sockaddr *)&addr, sizeof(addr)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
int backlog = 1;
if (listen(fd, backlog) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
}
std::pair<xrt::drivers::wivrn::TCP, sockaddr_in6>
xrt::drivers::wivrn::TCPListener::accept()
{
sockaddr_in6 addr{};
socklen_t addrlen = sizeof(addr);
int fd2 = ::accept(fd, (sockaddr *)&addr, &addrlen);
if (fd2 < 0)
throw std::system_error{errno, std::generic_category()};
return {TCP{fd2}, addr};
}
// std::pair<xrt::drivers::wivrn::deserialization_packet, sockaddr_in6> xrt::drivers::wivrn::UDP::receive_from_raw()
// {
// std::vector<uint8_t> buffer(2000);
//
// sockaddr_in6 addr;
// socklen_t addrlen = sizeof(addr);
//
// ssize_t received = recvfrom(fd, buffer.data(), buffer.size(), 0, (sockaddr *)&addr, &addrlen);
// if (received < 0)
// throw std::system_error{errno, std::generic_category()};
//
// buffer.resize(received);
//
// return {deserialization_packet{buffer}, addr};
// }
xrt::drivers::wivrn::deserialization_packet xrt::drivers::wivrn::UDP::receive_raw()
{
std::vector<uint8_t> buffer(2000);
ssize_t received = recv(fd, buffer.data(), buffer.size(), 0);
if (received < 0)
throw std::system_error{errno, std::generic_category()};
buffer.resize(received);
return deserialization_packet{buffer};
}
void xrt::drivers::wivrn::UDP::send_raw(const std::vector<uint8_t> & data)
{
if (::send(fd, data.data(), data.size(), 0) < 0)
throw std::system_error{errno, std::generic_category()};
}
xrt::drivers::wivrn::deserialization_packet xrt::drivers::wivrn::TCP::receive_raw()
{
size_t expected_size;
size_t already_received = buffer.size();
if (already_received < 4)
{
expected_size = 4 - buffer.size();
}
else
{
uint32_t payload_size = *reinterpret_cast<uint32_t *>(buffer.data());
expected_size = payload_size + 4 - buffer.size();
}
buffer.resize(already_received + expected_size);
ssize_t received = recv(fd, buffer.data() + already_received, expected_size, MSG_DONTWAIT);
if (received < 0)
throw std::system_error{errno, std::generic_category()};
if (received == 0)
throw socket_shutdown{};
buffer.resize(already_received + received);
if (buffer.size() < 4)
return {};
uint32_t payload_size = *reinterpret_cast<uint32_t *>(buffer.data());
if (buffer.size() < 4 + payload_size)
return {};
assert(buffer.size() == 4 + payload_size);
std::vector<uint8_t> new_buffer;
std::swap(buffer, new_buffer);
return deserialization_packet{std::move(new_buffer), 4};
}
void xrt::drivers::wivrn::TCP::send_raw(const std::vector<uint8_t> & data)
{
std::lock_guard lock(*mutex);
uint32_t size = data.size();
ssize_t sent = ::send(fd, &size, sizeof(size), MSG_NOSIGNAL);
if (sent == 0)
throw socket_shutdown{};
if (sent < 0)
throw std::system_error{errno, std::generic_category()};
assert(sent == sizeof(size));
size_t index = 0;
while (index < data.size())
{
sent = ::send(fd, data.data() + index, data.size() - index, MSG_NOSIGNAL);
if (sent == 0)
throw socket_shutdown{};
if (sent < 0)
throw std::system_error{errno, std::generic_category()};
index += sent;
}
}
+150
View File
@@ -0,0 +1,150 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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_serialization.h"
#include <memory>
#include <mutex>
#include <netinet/ip.h>
#include <stdexcept>
#include <utility>
#include <vector>
namespace xrt::drivers::wivrn
{
class socket_shutdown : public std::exception
{
public:
const char * what() const noexcept override;
};
class invalid_packet : public std::exception
{
public:
const char * what() const noexcept override;
};
template <typename T, typename... Ts>
struct index_of_type
{};
template <typename T, typename... Ts>
struct index_of_type<T, T, Ts...> : std::integral_constant<size_t, 0>
{};
template <typename T, typename T2, typename... Ts>
struct index_of_type<T, T2, Ts...> : std::integral_constant<size_t, 1 + index_of_type<T, Ts...>::value>
{};
static_assert(index_of_type<int, int, float>::value == 0);
static_assert(index_of_type<float, int, float>::value == 1);
class socket_base
{
protected:
int fd = -1;
socket_base() = default;
socket_base(const socket_base &) = delete;
socket_base(socket_base &&);
~socket_base();
public:
int get_fd() const
{
return fd;
}
};
class UDP : public socket_base
{
public:
UDP();
UDP(const UDP &) = delete;
UDP(UDP &&) = default;
deserialization_packet receive_raw();
void send_raw(const std::vector<uint8_t> & data);
void connect(in6_addr address, int port);
void connect(in_addr address, int port);
void bind(int port);
void subscribe_multicast(in6_addr address);
void unsubscribe_multicast(in6_addr address);
void set_receive_buffer_size(int size);
};
class TCP : public socket_base
{
std::vector<uint8_t> buffer;
std::unique_ptr<std::mutex> mutex;
void init();
public:
TCP(in6_addr address, int port);
TCP(in_addr address, int port);
explicit TCP(int fd);
TCP(const TCP &) = delete;
TCP(TCP &&) = default;
deserialization_packet receive_raw();
void send_raw(const std::vector<uint8_t> & data);
};
class TCPListener : public socket_base
{
public:
TCPListener(int port);
TCPListener(const TCPListener &) = delete;
TCPListener(TCPListener &&) = default;
std::pair<TCP, sockaddr_in6> accept();
};
template <typename Socket, typename ReceivedType, typename SentType>
class typed_socket : public Socket
{
public:
template <typename... Args>
typed_socket(Args &&... args) :
Socket(std::forward<Args>(args)...)
{}
std::optional<ReceivedType> receive()
{
deserialization_packet packet = this->receive_raw();
if (packet.empty())
return {};
return packet.deserialize<ReceivedType>();
}
template <typename T = SentType, typename = std::enable_if_t<std::is_same_v<T, SentType>>>
void send(const T & data)
{
serialization_packet p;
p.serialize(data);
this->send_raw(std::move(p));
}
};
} // namespace xrt::drivers::wivrn