Initial audio support

Co-authored-by: Guillaume Meunier <guillaume.meunier@centraliens.net>
This commit is contained in:
Patrick Nicolas
2022-12-03 21:24:55 +01:00
committed by Guillaume Meunier
co-authored by Guillaume Meunier
parent b5417633a1
commit 2b4303272d
17 changed files with 786 additions and 9 deletions
+1
View File
@@ -53,6 +53,7 @@ if (WIVRN_BUILD_SERVER)
endif() endif()
pkg_check_modules(AVAHI IMPORTED_TARGET avahi-client) pkg_check_modules(AVAHI IMPORTED_TARGET avahi-client)
pkg_check_modules(libpulse IMPORTED_TARGET libpulse)
find_package(Eigen3 REQUIRED) find_package(Eigen3 REQUIRED)
endif() endif()
+2 -1
View File
@@ -34,7 +34,8 @@ You will briefly have a "Waiting for connection" screen, followed by "Waiting fo
Now on your computer you can run an OpenXR application, and it will show on your headset, enjoy! Now on your computer you can run an OpenXR application, and it will show on your headset, enjoy!
# TODO # TODO
* Sound support (playback and recording) * Sound support (recording)
* Improve sound playback latency
* SteamVR support with [OpenComposite](https://gitlab.com/znixian/OpenOVR) * SteamVR support with [OpenComposite](https://gitlab.com/znixian/OpenOVR)
* Latency improvement * Latency improvement
* Application launcher * Application launcher
+5 -2
View File
@@ -17,7 +17,8 @@ if(ANDROID)
find_library(ANDROID_LIBRARY NAMES android REQUIRED) find_library(ANDROID_LIBRARY NAMES android REQUIRED)
find_library(MEDIA_LIBRARY NAMES mediandk REQUIRED) find_library(MEDIA_LIBRARY NAMES mediandk REQUIRED)
target_link_libraries(wivrn ${ANDROID_LIBRARY} ${MEDIA_LIBRARY}) find_library(AAUDIO_LIBRARY NAMES aaudio REQUIRED)
target_link_libraries(wivrn ${ANDROID_LIBRARY} ${MEDIA_LIBRARY} ${AAUDIO_LIBRARY})
if(OCULUS) if(OCULUS)
set(OCULUS_SDK_PATH ${CMAKE_SOURCE_DIR}/external/oculus) set(OCULUS_SDK_PATH ${CMAKE_SOURCE_DIR}/external/oculus)
@@ -58,7 +59,9 @@ if(ANDROID)
target_link_options(wivrn PRIVATE -Wl,--undefined=ANativeActivity_onCreate) target_link_options(wivrn PRIVATE -Wl,--undefined=ANativeActivity_onCreate)
file(GLOB PLATFORM_SOURCE CONFIGURE_DEPENDS file(GLOB PLATFORM_SOURCE CONFIGURE_DEPENDS
"decoder/android/*.cpp") "audio/android/*.cpp"
"decoder/android/*.cpp"
)
target_sources(wivrn PRIVATE ${PLATFORM_SOURCE}) target_sources(wivrn PRIVATE ${PLATFORM_SOURCE})
else() else()
add_executable(wivrn) add_executable(wivrn)
+250
View File
@@ -0,0 +1,250 @@
/*
* 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 "audio.h"
#include "spdlog/spdlog.h"
#include <poll.h>
#include <cassert>
#include <aaudio/AAudio.h>
#include <pthread.h>
#include <unistd.h>
#include <netinet/tcp.h>
void wivrn::android::audio::output(AAudioStream * stream, const xrt::drivers::wivrn::to_headset::audio_stream_description::device& format)
{
pthread_setname_np(pthread_self(), "audio_out_thread");
spdlog::info("audio_out_thread started");
try
{
AAudioStream_requestStart(stream);
aaudio_stream_state_t state;
aaudio_result_t result = AAudioStream_waitForStateChange(stream, AAUDIO_STREAM_STATE_STARTING, &state, 1'000'000'000);
if (result != AAUDIO_OK)
throw std::runtime_error(std::string("Cannot start output stream: ") + AAudio_convertResultToText(result));
size_t offset = 0;
char buffer[2000];
const int frame_size = format.num_channels * sizeof(int16_t);
while(!quit)
{
pollfd pfd{};
pfd.fd = fd;
pfd.events = POLLIN;
int r = ::poll(&pfd, 1, 100);
if (r < 0)
throw std::system_error(errno, std::system_category());
if (pfd.revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on audio socket");
if (pfd.revents & POLLIN)
{
ssize_t size = recv(fd, buffer + offset, sizeof(buffer) - offset, 0);
int num_frames = (size + offset) / frame_size;
num_frames = AAudioStream_write(stream, buffer, num_frames, 1'000'000'000);
if (num_frames < 0)
throw std::runtime_error(std::string("Cannot play output stream: ") + AAudio_convertResultToText(result));
size_t consumed_bytes = num_frames * frame_size;
memmove(buffer, buffer + consumed_bytes, size + offset - consumed_bytes);
offset = size + offset - consumed_bytes;
assert(offset >= 0);
assert(offset < sizeof(buffer));
}
}
}
catch(std::exception& e)
{
spdlog::error("Error in audio output thread: {}", e.what());
quit = true;
}
AAudioStream_close(stream);
}
void wivrn::android::audio::input(AAudioStream * stream, const xrt::drivers::wivrn::to_headset::audio_stream_description::device& format)
{
pthread_setname_np(pthread_self(), "audio_in_thread");
try
{
// while(!quit)
// {
//
// }
}
catch(...)
{
quit = true;
}
AAudioStream_close(stream);
}
void wivrn::android::audio::init(const xrt::drivers::wivrn::to_headset::audio_stream_description & desc, sockaddr * address, socklen_t address_size)
{
if (connect(fd, address, address_size) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
int nodelay = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
AAudioStreamBuilder * builder;
aaudio_result_t result = AAudio_createStreamBuilder(&builder);
if (result != AAUDIO_OK)
{
::close(fd);
throw std::runtime_error(std::string("Cannot create stream builder: ") + AAudio_convertResultToText(result));
}
if (desc.speaker)
{
AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_OUTPUT);
AAudioStreamBuilder_setSampleRate(builder, desc.speaker->sample_rate);
AAudioStreamBuilder_setChannelCount(builder, desc.speaker->num_channels);
AAudioStreamBuilder_setPerformanceMode(builder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY);
AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_I16);
AAudioStream * stream;
result = AAudioStreamBuilder_openStream(builder, &stream);
if (result != AAUDIO_OK)
spdlog::error("Cannot create output stream: {}", AAudio_convertResultToText(result));
else
output_thread = std::thread(&audio::output, this, stream, *desc.speaker);
}
if (desc.microphone)
{
AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_INPUT);
AAudioStreamBuilder_setSampleRate(builder, desc.microphone->sample_rate);
AAudioStreamBuilder_setChannelCount(builder, desc.microphone->num_channels);
AAudioStreamBuilder_setPerformanceMode(builder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY);
AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_I16);
AAudioStream * stream;
result = AAudioStreamBuilder_openStream(builder, &stream);
if (result != AAUDIO_OK)
spdlog::error("Cannot create input stream: {}", AAudio_convertResultToText(result));
else
input_thread = std::thread(&audio::input, this, stream, *desc.microphone);
}
AAudioStreamBuilder_delete(builder);
}
wivrn::android::audio::audio(const xrt::drivers::wivrn::to_headset::audio_stream_description & desc, const in_addr & address)
{
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(desc.port);
init(desc, (sockaddr *)&sa, sizeof(sa));
}
wivrn::android::audio::audio(const xrt::drivers::wivrn::to_headset::audio_stream_description & desc, const in6_addr & address)
{
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(desc.port);
init(desc, (sockaddr *)&sa, sizeof(sa));
}
wivrn::android::audio::~audio()
{
quit = true;
if (input_thread.joinable())
input_thread.join();
if (output_thread.joinable())
output_thread.join();
if (fd >= 0)
::close(fd);
}
void wivrn::android::audio::get_audio_description(xrt::drivers::wivrn::from_headset::headset_info_packet & info)
{
AAudioStreamBuilder * builder;
aaudio_result_t result = AAudio_createStreamBuilder(&builder);
if (result != AAUDIO_OK)
return;
AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_OUTPUT);
AAudioStream * stream;
result = AAudioStreamBuilder_openStream(builder, &stream);
if (result == AAUDIO_OK)
{
info.speaker = {
.num_channels = (uint8_t)AAudioStream_getChannelCount(stream),
.sample_rate = (uint32_t)AAudioStream_getSampleRate(stream)
};
AAudioStream_close(stream);
stream = nullptr;
}
AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_INPUT);
result = AAudioStreamBuilder_openStream(builder, &stream);
if (result == AAUDIO_OK)
{
info.microphone = {
.num_channels = (uint8_t)AAudioStream_getChannelCount(stream),
.sample_rate = (uint32_t)AAudioStream_getSampleRate(stream)
};
AAudioStream_close(stream);
stream = nullptr;
}
AAudioStreamBuilder_delete(builder);
}
+53
View File
@@ -0,0 +1,53 @@
/*
* 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_packets.h"
#include <thread>
#include <atomic>
struct AAudioStreamStruct;
namespace wivrn::android
{
class audio
{
void output(AAudioStreamStruct * stream, const xrt::drivers::wivrn::to_headset::audio_stream_description::device& format);
void input(AAudioStreamStruct * stream, const xrt::drivers::wivrn::to_headset::audio_stream_description::device& format);
std::thread output_thread;
std::thread input_thread;
std::atomic<bool> quit = false;
int fd = -1;
void init(const xrt::drivers::wivrn::to_headset::audio_stream_description & desc, sockaddr * address, socklen_t address_size);
public:
audio(const audio&) = delete;
audio& operator=(const audio&) = delete;
audio(const xrt::drivers::wivrn::to_headset::audio_stream_description&, const in_addr& );
audio(const xrt::drivers::wivrn::to_headset::audio_stream_description&, const in6_addr& );
~audio();
static void get_audio_description(xrt::drivers::wivrn::from_headset::headset_info_packet& info);
};
}
+42
View File
@@ -0,0 +1,42 @@
/*
* 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_packets.h"
#ifdef XR_USE_PLATFORM_ANDROID
#include "android/audio.h"
using audio = ::wivrn::android::audio;
#else
class audio
{
public:
audio(const audio&) = delete;
audio& operator=(const audio&) = delete;
audio(const xrt::drivers::wivrn::to_headset::audio_stream_description&, const in_addr& ) {}
audio(const xrt::drivers::wivrn::to_headset::audio_stream_description&, const in6_addr& ) {}
~audio() = default;
static void get_audio_description(xrt::drivers::wivrn::from_headset::headset_info_packet& info) {}
};
#endif
+3
View File
@@ -38,6 +38,7 @@
#include <mutex> #include <mutex>
#include <thread> #include <thread>
#include <vulkan/vulkan_core.h> #include <vulkan/vulkan_core.h>
#include "audio/audio.h"
using namespace xrt::drivers::wivrn; using namespace xrt::drivers::wivrn;
@@ -90,6 +91,8 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
if (info.available_refresh_rates.empty()) if (info.available_refresh_rates.empty())
spdlog::warn("Unable to detect refresh rates"); spdlog::warn("Unable to detect refresh rates");
audio::get_audio_description(info);
self->network_session->send_control(info); self->network_session->send_control(info);
self->network_thread = std::thread(&stream::process_packets, self.get()); self->network_thread = std::thread(&stream::process_packets, self.get());
+4
View File
@@ -33,6 +33,7 @@
#include <mutex> #include <mutex>
#include <thread> #include <thread>
#include <vulkan/vulkan_core.h> #include <vulkan/vulkan_core.h>
#include "audio/audio.h"
namespace scenes namespace scenes
{ {
@@ -88,6 +89,8 @@ class stream : public scene, public std::enable_shared_from_this<stream>
XrTime first_frame_time{}; XrTime first_frame_time{};
const float dbrightness = 2; const float dbrightness = 2;
std::optional<audio> audio_handle;
stream() = default; stream() = default;
public: public:
@@ -101,6 +104,7 @@ public:
void operator()(to_headset::video_stream_parity_shard &&); void operator()(to_headset::video_stream_parity_shard &&);
void operator()(to_headset::haptics &&); void operator()(to_headset::haptics &&);
void operator()(to_headset::timesync_query &&); void operator()(to_headset::timesync_query &&);
void operator()(to_headset::audio_stream_description &&);
void operator()(to_headset::video_stream_description &&); void operator()(to_headset::video_stream_description &&);
VkFormat swapchain_format() VkFormat swapchain_format()
+7
View File
@@ -49,6 +49,13 @@ void scenes::stream::operator()(to_headset::video_stream_parity_shard && shard)
shard_queue.push(std::move(shard)); shard_queue.push(std::move(shard));
} }
void scenes::stream::operator()(to_headset::audio_stream_description && desc)
{
std::visit([&](auto & address){
audio_handle.emplace(desc, address);
}, network_session->address);
}
void scenes::stream::operator()(to_headset::video_stream_description && desc) void scenes::stream::operator()(to_headset::video_stream_description && desc)
{ {
setup(desc); setup(desc);
+2 -2
View File
@@ -37,7 +37,7 @@
using namespace std::chrono_literals; using namespace std::chrono_literals;
wivrn_session::wivrn_session(in6_addr address, int port) : wivrn_session::wivrn_session(in6_addr address, int port) :
control(address, port), stream() control(address, port), stream(), address(address)
{ {
// TODO: negociate UDP port // TODO: negociate UDP port
stream.bind(stream_client_port); stream.bind(stream_client_port);
@@ -49,7 +49,7 @@ wivrn_session::wivrn_session(in6_addr address, int port) :
} }
wivrn_session::wivrn_session(in_addr address, int port) : wivrn_session::wivrn_session(in_addr address, int port) :
control(address, port), stream() control(address, port), stream(), address(address)
{ {
// TODO: negociate UDP port // TODO: negociate UDP port
stream.bind(stream_client_port); stream.bind(stream_client_port);
+2
View File
@@ -32,6 +32,8 @@ class wivrn_session
typed_socket<UDP, to_headset::stream_packets, from_headset::stream_packets> stream; typed_socket<UDP, to_headset::stream_packets, from_headset::stream_packets> stream;
public: public:
std::variant<in_addr, in6_addr> address;
wivrn_session(in6_addr address, int port); wivrn_session(in6_addr address, int port);
wivrn_session(in_addr address, int port); wivrn_session(in_addr address, int port);
wivrn_session(const wivrn_session &) = delete; wivrn_session(const wivrn_session &) = delete;
+24 -4
View File
@@ -41,6 +41,7 @@ struct serialization_traits;
static const int control_port = 9757; static const int control_port = 9757;
static const int stream_client_port = 9757; static const int stream_client_port = 9757;
static const int stream_server_port = 9758; static const int stream_server_port = 9758;
static const int audio_server_port = 9759;
enum class device_id : uint8_t enum class device_id : uint8_t
{ {
@@ -82,19 +83,26 @@ enum class device_id : uint8_t
enum video_codec enum video_codec
{ {
h264, h264,
hevc, h265,
h265 = hevc, hevc = h265,
}; };
namespace from_headset namespace from_headset
{ {
struct headset_info_packet struct headset_info_packet
{ {
uint32_t recommended_eye_width; uint32_t recommended_eye_width;
uint32_t recommended_eye_height; uint32_t recommended_eye_height;
std::vector<float> available_refresh_rates; std::vector<float> available_refresh_rates;
float preferred_refresh_rate; float preferred_refresh_rate;
uint32_t microphone_sample_rate; struct audio_description
{
uint8_t num_channels;
uint32_t sample_rate;
};
std::optional<audio_description> speaker;
std::optional<audio_description> microphone;
}; };
struct tracking struct tracking
@@ -178,6 +186,18 @@ using stream_packets = std::variant<tracking, inputs, timesync_response>;
namespace to_headset namespace to_headset
{ {
struct audio_stream_description
{
uint16_t port;
struct device
{
uint8_t num_channels;
uint32_t sample_rate;
};
std::optional<device> speaker;
std::optional<device> microphone;
};
struct video_stream_description struct video_stream_description
{ {
struct item struct item
@@ -275,7 +295,7 @@ struct timesync_query
}; };
using stream_packets = std::variant<video_stream_data_shard, video_stream_parity_shard, haptics, timesync_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>; using control_packets = std::variant<audio_stream_description, video_stream_description>;
} // namespace to_headset } // namespace to_headset
+2
View File
@@ -54,6 +54,7 @@ add_executable(wivrn-server
hostname.cpp hostname.cpp
avahi_publisher.cpp avahi_publisher.cpp
driver/audio_setup.cpp
driver/configuration.cpp driver/configuration.cpp
driver/encoder_settings.cpp driver/encoder_settings.cpp
driver/wivrn_hmd.cpp driver/wivrn_hmd.cpp
@@ -112,6 +113,7 @@ target_link_libraries(
PkgConfig::systemd PkgConfig::systemd
Boost::pfr Boost::pfr
PkgConfig::AVAHI PkgConfig::AVAHI
PkgConfig::libpulse
Eigen3::Eigen Eigen3::Eigen
wivrn-common wivrn-common
nlohmann_json::nlohmann_json nlohmann_json::nlohmann_json
+327
View File
@@ -0,0 +1,327 @@
#include "audio_setup.h"
#include <pulse/context.h>
#include <pulse/ext-device-manager.h>
#include <pulse/introspect.h>
#include <pulse/proplist.h>
#include <pulse/thread-mainloop.h>
#include <atomic>
#include <future>
#include <iomanip>
#include <iostream>
#include <optional>
#include <vector>
static const char * source_name = "WiVRn-mic";
static const char * sink_name = "WiVRn";
struct module_entry
{
uint32_t module;
uint32_t device;
uint32_t monitor;
};
void wait_connected(std::atomic<pa_context_state> & state)
{
while (true)
{
auto current = state.load();
switch (current)
{
case PA_CONTEXT_READY:
return;
case PA_CONTEXT_FAILED:
throw std::runtime_error("connection failed");
default:
state.wait(current);
}
}
}
template <typename... Args>
struct add_void;
template <typename T, typename... Args>
struct add_void<std::function<T(Args...)>>
{
template <typename L>
static T fn(Args... a, void * userdata)
{
L * f = (L *)userdata;
return (*f)(a...);
}
};
template <typename T>
class wrap_lambda
{
T impl;
public:
wrap_lambda(T && l) :
impl(l) {}
operator auto()
{
using F = decltype(std::function(impl));
return add_void<F>::template fn<T>;
}
operator void *()
{
return this;
}
};
void unload_module(pa_context * ctx, uint32_t id)
{
std::promise<void> p;
wrap_lambda cb = [&p, id](pa_context *, int success) {
if (not success)
std::cout << "failed to unload pulseaudio module " << id
<< std::endl;
else
std::cout << "pulseaudio module " << id << " unloaded"
<< std::endl;
p.set_value();
};
auto op = pa_context_unload_module(ctx, id, cb, cb);
pa_operation_unref(op);
p.get_future().get();
}
std::optional<module_entry> get_sink(pa_context * ctx, const char * name)
{
std::optional<module_entry> result;
std::promise<void> p;
wrap_lambda cb(
[&result, &p](pa_context *, const pa_sink_info * i, int eol) {
if (eol)
{
p.set_value();
return;
}
result = {.module = i->owner_module, .device = i->index, .monitor = i->monitor_source};
});
auto op = pa_context_get_sink_info_by_name(ctx, name, cb, cb);
pa_operation_unref(op);
p.get_future().wait();
return result;
}
module_entry ensure_sink(pa_context * ctx, const char * name, const std::string & description, int channels, int sample_rate)
{
auto sink = get_sink(ctx, name);
if (sink)
unload_module(ctx, sink->module);
std::promise<uint32_t> module_index;
wrap_lambda cb = [&module_index](pa_context *, uint32_t index) {
module_index.set_value(index);
};
std::stringstream params;
params << "sink_name=" << std::quoted(name)
<< " channels=" << channels
<< " rate=" << sample_rate
<< " sink_properties=" << PA_PROP_DEVICE_DESCRIPTION << "=" << std::quoted(description)
<< PA_PROP_DEVICE_ICON_NAME << "=network-wireless";
;
auto op = pa_context_load_module(ctx, "module-null-sink", params.str().c_str(), cb, cb);
pa_operation_unref(op);
module_index.get_future().wait();
sink = get_sink(ctx, name);
if (not sink)
std::runtime_error("failed to create audio sink " +
std::string(name));
return *sink;
}
std::optional<uint32_t> get_simple_tcp(pa_context * ctx,
int port)
{
std::optional<uint32_t> result;
std::promise<void> p;
wrap_lambda cb([&result, &p, port_str = "port=" + std::to_string(port)](
pa_context *, const pa_module_info * i, int eol) {
if (eol)
{
p.set_value();
return;
}
if (i->name == std::string("module-simple-protocol-tcp") and
i->argument and std::string_view(i->argument).find(port_str) != std::string_view::npos)
result = i->index;
});
auto op = pa_context_get_module_info_list(ctx, cb, cb);
pa_operation_unref(op);
p.get_future().wait();
return result;
}
uint32_t load_module_simple(pa_context * ctx, uint16_t port, std::optional<module_entry> microphone, std::optional<module_entry> speaker)
{
std::stringstream params;
params << "port=" << port;
if (microphone)
params << " playback=true sink=" << microphone->device;
else
params << " playback=false";
if (speaker)
params << " record=true source=" << speaker->monitor;
else
params << " record=false";
std::string params_str = params.str();
auto simple_tcp = get_simple_tcp(ctx, port);
if (simple_tcp)
unload_module(ctx, *simple_tcp);
std::promise<uint32_t> module_index;
wrap_lambda cb = [&module_index, &params_str](pa_context *,
uint32_t index) {
if (index == uint32_t(-1))
module_index.set_exception(
std::make_exception_ptr(std::runtime_error(
"failed to load module-simple-protocol-tcp "
"with parameters " +
params_str)));
else
module_index.set_value(index);
};
auto op = pa_context_load_module(ctx, "module-simple-protocol-tcp", params_str.c_str(), cb, cb);
pa_operation_unref(op);
return module_index.get_future().get();
}
struct pa_deleter
{
void operator()(pa_threaded_mainloop * loop)
{
pa_threaded_mainloop_stop(loop);
pa_threaded_mainloop_free(loop);
}
void operator()(pa_context * ctx)
{
pa_context_unref(ctx);
}
};
class pa_connection
{
std::unique_ptr<pa_threaded_mainloop, pa_deleter> main_loop;
std::unique_ptr<pa_context, pa_deleter> ctx;
std::atomic<pa_context_state> context_state{PA_CONTEXT_UNCONNECTED};
public:
pa_connection(const char * app_name)
{
main_loop.reset(pa_threaded_mainloop_new());
auto loop = pa_threaded_mainloop_get_api(main_loop.get());
ctx.reset(pa_context_new(loop, app_name));
wrap_lambda context_state_cb = [this](pa_context * c) {
context_state.store(pa_context_get_state(c));
context_state.notify_all();
};
pa_context_set_state_callback(ctx.get(), context_state_cb, context_state_cb);
int ret = pa_context_connect(ctx.get(), nullptr, PA_CONTEXT_NOAUTOSPAWN, nullptr);
if (ret < 0)
throw std::runtime_error(
"failed to setup pulseaudio connection "
"(pa_context_connect)");
ret = pa_threaded_mainloop_start(main_loop.get());
if (ret < 0)
throw std::runtime_error(
"failed to setup pulseaudio connection "
"(pa_threaded_mainloop_start)");
wait_connected(context_state);
}
operator pa_context *()
{
return ctx.get();
}
};
struct pulse_publish_handle : public audio_publish_handle
{
std::vector<uint32_t> modules;
xrt::drivers::wivrn::to_headset::audio_stream_description desc;
~pulse_publish_handle()
{
if (modules.empty())
return;
try
{
pa_connection cnx("WiVRn");
for (const auto id: modules)
{
unload_module(cnx, id);
}
}
catch (const std::exception & e)
{
std::cout << "failed to depublish pulseaudio modules: "
<< e.what() << std::endl;
}
}
xrt::drivers::wivrn::to_headset::audio_stream_description description() const
{
return desc;
};
static std::shared_ptr<pulse_publish_handle> create(
const std::string & source_name,
const std::string & source_description,
const std::string & sink_name,
const std::string & sink_description,
const uint16_t listen_port,
const xrt::drivers::wivrn::from_headset::headset_info_packet & info)
{
pa_connection cnx("WiVRn");
auto result = std::make_shared<pulse_publish_handle>();
std::optional<module_entry> source, sink;
if (info.microphone)
{
source = ensure_sink(cnx, source_name.c_str(), source_description, info.microphone->num_channels, info.microphone->sample_rate);
result->modules.push_back(source->module);
result->desc.microphone = {.num_channels = info.microphone->num_channels, .sample_rate = info.microphone->sample_rate};
}
if (info.speaker)
{
sink = ensure_sink(cnx, sink_name.c_str(), sink_description, info.speaker->num_channels, info.speaker->sample_rate);
result->modules.push_back(sink->module);
result->desc.speaker = {.num_channels = info.speaker->num_channels, .sample_rate = info.speaker->sample_rate};
}
uint32_t simple_tcp =
load_module_simple(cnx, listen_port, source, sink);
result->modules.push_back(simple_tcp);
result->desc.port = listen_port;
return result;
}
};
std::shared_ptr<audio_publish_handle> audio_publish_handle::create(
const std::string & source_name,
const std::string & source_description,
const std::string & sink_name,
const std::string & sink_description,
const uint16_t listen_port,
const xrt::drivers::wivrn::from_headset::headset_info_packet & info)
{
return pulse_publish_handle::create(source_name, source_description, sink_name, sink_description, listen_port, info);
}
+42
View File
@@ -0,0 +1,42 @@
/*
* 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 <memory>
#include <string>
#include "wivrn_packets.h"
struct audio_publish_handle
{
// unpublishes the device
virtual ~audio_publish_handle() = default;
virtual xrt::drivers::wivrn::to_headset::audio_stream_description description() const = 0;
static std::shared_ptr<audio_publish_handle> create(
const std::string & source_name,
const std::string & source_description,
const std::string & sink_name,
const std::string & sink_description,
const uint16_t listen_port,
const xrt::drivers::wivrn::from_headset::headset_info_packet & info);
};
+17
View File
@@ -18,6 +18,7 @@
*/ */
#include "wivrn_session.h" #include "wivrn_session.h"
#include "audio_setup.h"
#include "os/os_time.h" #include "os/os_time.h"
#include "util/u_logging.h" #include "util/u_logging.h"
@@ -56,6 +57,22 @@ xrt_system_devices * xrt::drivers::wivrn::wivrn_session::create_session(xrt::dri
} }
const auto & info = std::get<from_headset::headset_info_packet>(*control); const auto & info = std::get<from_headset::headset_info_packet>(*control);
try
{
self->audio_handle = audio_publish_handle::create(
"wivrn.source",
"WiVRn microphone",
"wivrn.sink",
"WiVRn",
xrt::drivers::wivrn::audio_server_port,
info);
self->send_control(self->audio_handle->description());
}
catch (const std::exception & e)
{
U_LOG_E("Failed to register audio device: %s", e.what());
}
self->hmd = std::make_unique<wivrn_hmd>(self, info); self->hmd = std::make_unique<wivrn_hmd>(self, info);
self->left_hand = std::make_unique<wivrn_controller>(0, self->hmd.get(), self); self->left_hand = std::make_unique<wivrn_controller>(0, self->hmd.get(), self);
self->right_hand = std::make_unique<wivrn_controller>(1, self->hmd.get(), self); self->right_hand = std::make_unique<wivrn_controller>(1, self->hmd.get(), self);
+3
View File
@@ -30,6 +30,7 @@
class wivrn_hmd; class wivrn_hmd;
class wivrn_controller; class wivrn_controller;
struct audio_publish_handle;
namespace xrt::drivers::wivrn namespace xrt::drivers::wivrn
{ {
@@ -62,6 +63,8 @@ class wivrn_session : public std::enable_shared_from_this<wivrn_session>
std::mutex csv_mutex; std::mutex csv_mutex;
std::ofstream feedback_csv; std::ofstream feedback_csv;
std::shared_ptr<audio_publish_handle> audio_handle;
wivrn_session(TCP && tcp, in6_addr & address); wivrn_session(TCP && tcp, in6_addr & address);
public: public: