From 00fbfafb60ccf632011c07614e7521e2fc15189c Mon Sep 17 00:00:00 2001 From: Patrick Nicolas Date: Thu, 29 Jun 2023 09:08:33 +0200 Subject: [PATCH] use control socket for audio data --- client/audio/android/audio.cpp | 131 +++---- client/audio/android/audio.h | 32 +- client/scenes/stream.h | 1 + client/scenes/stream_network.cpp | 10 +- {client => common}/utils/sync_queue.h | 0 common/wivrn_packets.h | 12 +- server/CMakeLists.txt | 1 + server/driver/audio_pulse.cpp | 482 +++++++++++++++++++++++++ server/driver/audio_pulse.h | 29 ++ server/driver/audio_setup.cpp | 494 +------------------------- server/driver/audio_setup.h | 17 +- server/driver/wivrn_session.cpp | 13 +- server/driver/wivrn_session.h | 5 +- 13 files changed, 623 insertions(+), 604 deletions(-) rename {client => common}/utils/sync_queue.h (100%) create mode 100644 server/driver/audio_pulse.cpp create mode 100644 server/driver/audio_pulse.h diff --git a/client/audio/android/audio.cpp b/client/audio/android/audio.cpp index ed728c82..aade48de 100644 --- a/client/audio/android/audio.cpp +++ b/client/audio/android/audio.cpp @@ -18,6 +18,9 @@ */ #include "audio.h" +#include "wivrn_client.h" +#include "xr/instance.h" + #include "spdlog/spdlog.h" #include #include @@ -29,16 +32,11 @@ #include #include -static unsigned int buffer_size_ms = 10; -static unsigned int buffer_size_mult = 4; - 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"); - char * buffer; - char * sewer; try { @@ -48,46 +46,38 @@ void wivrn::android::audio::output(AAudioStream * stream, const xrt::drivers::wi if (result != AAUDIO_OK) throw std::runtime_error(std::string("Cannot start output stream: ") + AAudio_convertResultToText(result)); - size_t offset = 0; const size_t frame_size = format.num_channels * sizeof(int16_t); - size_t bufsize = frame_size * format.sample_rate / 1000 * buffer_size_ms; - size_t max_bytes_available = bufsize * buffer_size_mult; - buffer = new char[bufsize]; - sewer = new char[bufsize]; + int32_t underruns = 0; + int32_t frames = AAudioStream_getFramesPerBurst(stream); + std::vector silence(frame_size * frames, 0); + + // Tune buffer size to minimize latency + { + auto tuning_end = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); + while (std::chrono::steady_clock::now() < tuning_end) + { + AAudioStream_write(stream, silence.data(), frames, 0); + int32_t underrunCount = AAudioStream_getXRunCount(stream); + if (underrunCount != underruns) + { + AAudioStream_setBufferSizeInFrames(stream, AAudioStream_getBufferSizeInFrames(stream) + frames); + underruns = underrunCount; + } + } + } while (!quit) { - pollfd pfd{}; - pfd.fd = fd; - pfd.events = POLLIN; + auto packet = output_buffer.pop(); + auto &buffer = packet.payload; + int num_frames = buffer.size() / frame_size; - int r = ::poll(&pfd, 1, 100); - if (r < 0) - throw std::system_error(errno, std::system_category()); + num_frames = AAudioStream_write(stream, buffer.data(), num_frames, 0); + if (num_frames < 0) + throw std::runtime_error(std::string("Cannot play output stream: ") + AAudio_convertResultToText(result)); - if (pfd.revents & (POLLHUP | POLLERR)) - throw std::runtime_error("Error on audio socket"); - - if (pfd.revents & POLLIN) - { - ssize_t bytes_available; - while (ioctl(fd, FIONREAD, &bytes_available) == 0 && bytes_available > (ssize_t)max_bytes_available) - recv(fd, sewer, bufsize, 0); - - ssize_t size = recv(fd, buffer + offset, bufsize - 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 < bufsize); - } + // Any remaining data that doesn't fit the buffer is discarded } } catch (std::exception & e) @@ -95,8 +85,6 @@ void wivrn::android::audio::output(AAudioStream * stream, const xrt::drivers::wi spdlog::error("Error in audio output thread: {}", e.what()); quit = true; } - delete buffer; - delete sewer; AAudioStream_close(stream); } @@ -112,15 +100,20 @@ void wivrn::android::audio::input(AAudioStream * stream, const xrt::drivers::wiv if (result != AAUDIO_OK) throw std::runtime_error(std::string("Cannot start input stream: ") + AAudio_convertResultToText(result)); - char buffer[2000]; + xrt::drivers::wivrn::audio_data packet; const int frame_size = format.num_channels * sizeof(int16_t); - const int max_frames = 2000 / frame_size; + const int max_frames = (format.sample_rate * 10) / 1000; // 10ms while (!quit) { - result = AAudioStream_read(stream, buffer, max_frames, 1'000'000'000); + packet.payload.resize(frame_size * max_frames); + result = AAudioStream_read(stream, packet.payload.data(), max_frames, 1'000'000'000); if (result > 0) - send(fd, buffer, frame_size * result, 0); + { + packet.timestamp = instance.now(); + packet.payload.resize(frame_size * result); + session.send_control(packet); + } } } catch (std::exception & e) @@ -132,21 +125,8 @@ void wivrn::android::audio::input(AAudioStream * stream, const xrt::drivers::wiv AAudioStream_close(stream); } -void wivrn::android::audio::init(const xrt::drivers::wivrn::to_headset::audio_stream_description & desc, sockaddr * address, socklen_t address_size) +wivrn::android::audio::audio(const xrt::drivers::wivrn::to_headset::audio_stream_description & desc, wivrn_session& session, xr::instance& instance): session(session), instance(instance) { - 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); @@ -191,36 +171,6 @@ void wivrn::android::audio::init(const xrt::drivers::wivrn::to_headset::audio_st 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; @@ -235,6 +185,11 @@ wivrn::android::audio::~audio() ::close(fd); } +void wivrn::android::audio::operator()(xrt::drivers::wivrn::audio_data && data) +{ + output_buffer.push(std::move(data)); +} + void wivrn::android::audio::get_audio_description(xrt::drivers::wivrn::from_headset::headset_info_packet & info) { AAudioStreamBuilder * builder; diff --git a/client/audio/android/audio.h b/client/audio/android/audio.h index 741747e3..4e4c9047 100644 --- a/client/audio/android/audio.h +++ b/client/audio/android/audio.h @@ -19,35 +19,45 @@ #pragma once +#include "utils/sync_queue.h" #include "wivrn_packets.h" -#include #include +#include struct AAudioStreamStruct; +class wivrn_session; + +namespace xr +{ +class instance; +} 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); + 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; + utils::sync_queue output_buffer; + + wivrn_session & session; + xr::instance & instance; std::atomic 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(const audio &) = delete; + audio & operator=(const audio &) = delete; + audio(const xrt::drivers::wivrn::to_headset::audio_stream_description &, wivrn_session &, xr::instance &); ~audio(); - static void get_audio_description(xrt::drivers::wivrn::from_headset::headset_info_packet& info); + void operator()(xrt::drivers::wivrn::audio_data &&); + + static void get_audio_description(xrt::drivers::wivrn::from_headset::headset_info_packet & info); }; -} +} // namespace wivrn::android diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 4cd7e1b9..65a10204 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -106,6 +106,7 @@ public: void operator()(to_headset::timesync_query &&); void operator()(to_headset::audio_stream_description &&); void operator()(to_headset::video_stream_description &&); + void operator()(audio_data&&); VkFormat swapchain_format() { diff --git a/client/scenes/stream_network.cpp b/client/scenes/stream_network.cpp index b493b629..1307674d 100644 --- a/client/scenes/stream_network.cpp +++ b/client/scenes/stream_network.cpp @@ -51,9 +51,7 @@ void scenes::stream::operator()(to_headset::video_stream_parity_shard && shard) void scenes::stream::operator()(to_headset::audio_stream_description && desc) { - std::visit([&](auto & address){ - audio_handle.emplace(desc, address); - }, network_session->address); + audio_handle.emplace(desc, *network_session, instance); } void scenes::stream::operator()(to_headset::video_stream_description && desc) @@ -75,6 +73,12 @@ void scenes::stream::operator()(to_headset::timesync_query && query) network_session->send_stream(response); } +void scenes::stream::operator()(audio_data&& data) +{ + if (audio_handle) + (*audio_handle)(std::move(data)); +} + void scenes::stream::send_feedback(const xrt::drivers::wivrn::from_headset::feedback & feedback) { try diff --git a/client/utils/sync_queue.h b/common/utils/sync_queue.h similarity index 100% rename from client/utils/sync_queue.h rename to common/utils/sync_queue.h diff --git a/common/wivrn_packets.h b/common/wivrn_packets.h index f90c3b39..ffe9013f 100644 --- a/common/wivrn_packets.h +++ b/common/wivrn_packets.h @@ -41,7 +41,6 @@ struct serialization_traits; static const int control_port = 9757; static const int stream_client_port = 9757; static const int stream_server_port = 9758; -static const int audio_server_port = 9759; enum class device_id : uint8_t { @@ -87,6 +86,12 @@ enum video_codec hevc = h265, }; +struct audio_data +{ + uint64_t timestamp; + std::vector payload; +}; + namespace from_headset { @@ -179,7 +184,7 @@ struct feedback uint8_t received_parity_packets; }; -using control_packets = std::variant; +using control_packets = std::variant; using stream_packets = std::variant; } // namespace from_headset @@ -188,7 +193,6 @@ namespace to_headset struct audio_stream_description { - uint16_t port; struct device { uint8_t num_channels; @@ -299,7 +303,7 @@ struct timesync_query }; using stream_packets = std::variant; -using control_packets = std::variant; +using control_packets = std::variant; } // namespace to_headset diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index d2a71880..a8a36b63 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -54,6 +54,7 @@ add_executable(wivrn-server avahi_publisher.cpp wivrn_ipc.cpp + driver/audio_pulse.cpp driver/audio_setup.cpp driver/configuration.cpp driver/encoder_settings.cpp diff --git a/server/driver/audio_pulse.cpp b/server/driver/audio_pulse.cpp new file mode 100644 index 00000000..64ad4ab8 --- /dev/null +++ b/server/driver/audio_pulse.cpp @@ -0,0 +1,482 @@ +#include "audio_pulse.h" + +#include "../wivrn_ipc.h" +#include "util/u_logging.h" +#include "utils/sync_queue.h" +#include "wivrn_session.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +static const char * source_name = "WiVRn-mic"; +static const char * sink_name = "WiVRn"; +static const char * source_pipe = "wivrn-source"; +static const char * sink_pipe = "wivrn-sink"; + +struct module_entry +{ + uint32_t module; + uint32_t device; + std::filesystem::path socket; +}; + +void wait_connected(std::atomic & 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 +struct add_void; + +template +struct add_void> +{ + template + static T fn(Args... a, void * userdata) + { + L * f = (L *)userdata; + return (*f)(a...); + } +}; + +template +class wrap_lambda +{ + T impl; + +public: + wrap_lambda(T && l) : + impl(l) {} + + operator auto() + { + using F = decltype(std::function(impl)); + return add_void::template fn; + } + + operator void *() + { + return this; + } +}; + +void unload_module(uintptr_t id); + +void unload_module(pa_context * ctx, uint32_t id) +{ + std::promise 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(); + + remove_cleanup_function(unload_module, id); +} + +std::optional get_sink(pa_context * ctx, const char * name) +{ + std::optional result; + std::promise 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}; + }); + auto op = pa_context_get_sink_info_by_name(ctx, name, cb, cb); + pa_operation_unref(op); + p.get_future().wait(); + return result; +} + +std::optional get_source(pa_context * ctx, const char * name) +{ + std::optional result; + std::promise p; + wrap_lambda cb( + [&result, &p](pa_context *, const pa_source_info * i, int eol) { + if (eol) + { + p.set_value(); + return; + } + result = {.module = i->owner_module, .device = i->index}; + }); + auto op = pa_context_get_source_info_by_name(ctx, name, cb, cb); + pa_operation_unref(op); + p.get_future().wait(); + return result; +} + +std::filesystem::path get_socket_path() +{ + const char * path = std::getenv("XDG_RUNTIME_DIR"); + if (path) + return path; + path = "/tmp/wivrn"; + std::filesystem::create_directories(path); + U_LOG_W("XDG_RUNTIME_DIR is not set, using %s instead", path); + return path; +} + +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 module_index; + wrap_lambda cb = [&module_index](pa_context *, uint32_t index) { + module_index.set_value(index); + }; + std::filesystem::path fifo = get_socket_path() / sink_pipe; + std::stringstream params; + params << "sink_name=" << std::quoted(name) + << " file=" << std::quoted(fifo.string()) + << " channels=" << channels + << " rate=" << sample_rate + << " use_system_clock_for_timing=yes" + << " sink_properties=" << PA_PROP_DEVICE_DESCRIPTION << "=" << std::quoted(description) + << PA_PROP_DEVICE_ICON_NAME << "=network-wireless"; + ; + auto op = pa_context_load_module(ctx, "module-pipe-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)); + sink->socket = fifo; + + add_cleanup_function(unload_module, sink->module); + + return *sink; +} + +module_entry ensure_source(pa_context * ctx, const char * name, const std::string & description, int channels, int sample_rate) +{ + auto source = get_source(ctx, name); + if (source) + unload_module(ctx, source->module); + + std::promise module_index; + wrap_lambda cb = [&module_index](pa_context *, uint32_t index) { + module_index.set_value(index); + }; + std::filesystem::path fifo = get_socket_path() / source_pipe; + std::stringstream params; + params << "source_name=" << std::quoted(name) + << " file=" << std::quoted(fifo.string()) + << " channels=" << channels + << " rate=" << sample_rate + << " use_system_clock_for_timing=yes" + << " source_properties=" << PA_PROP_DEVICE_DESCRIPTION << "=" << std::quoted(description) + << PA_PROP_DEVICE_ICON_NAME << "=network-wireless"; + ; + auto op = pa_context_load_module(ctx, "module-pipe-source", params.str().c_str(), cb, cb); + pa_operation_unref(op); + module_index.get_future().wait(); + + source = get_source(ctx, name); + if (not source) + std::runtime_error("failed to create audio source " + std::string(name)); + source->socket = fifo; + return *source; +} + +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 main_loop; + std::unique_ptr ctx; + std::atomic 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_device : public audio_device +{ + xrt::drivers::wivrn::to_headset::audio_stream_description desc; + + std::thread net_thread; + std::atomic quit; + + std::optional speaker; + std::optional microphone; + + utils::sync_queue mic_buffer; + + xrt::drivers::wivrn::fd_base speaker_pipe; + xrt::drivers::wivrn::fd_base mic_pipe; + + xrt::drivers::wivrn::wivrn_session & session; + + ~pulse_device() + { + quit = true; + if (net_thread.joinable()) + net_thread.join(); + if (speaker or microphone) + { + try + { + pa_connection cnx("WiVRn"); + if (speaker) + unload_module(cnx, speaker->module); + if (microphone) + unload_module(cnx, microphone->module); + } + 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 override + { + return desc; + }; + + void run_speaker() + { + assert(desc.speaker); + pthread_setname_np(pthread_self(), "speaker_thread"); + + U_LOG_I("started speaker thread, sample rate %dHz, %d channels", desc.speaker->sample_rate, desc.speaker->num_channels); + + const size_t sample_size = desc.speaker->num_channels * sizeof(int16_t); + // use buffers of up to 2ms + // read buffers must be smaller than buffer size on client or we will discard chunks often + const size_t buffer_size = (desc.speaker->sample_rate * sample_size * 2) / 1000; + xrt::drivers::wivrn::audio_data packet; + // only send complete samples, keep remainder here + std::vector remainder; + + // Flush existing data, but keep alignment + { + int alignment = 0; + char sewer[1024]; + while (true) + { + int size = read(speaker_pipe.get_fd(), sewer, sizeof(sewer)); + if (size <= 0) + break; + alignment = (alignment + size) % sample_size; + } + packet.payload.resize(alignment, 0); + } + + try + { + while (not quit) + { + pollfd pfd{}; + pfd.fd = speaker_pipe.get_fd(); + pfd.events = POLL_IN; + + 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 speaker pipe"); + if (pfd.revents & POLLIN) + { + size_t excess = packet.payload.size(); + packet.payload.resize(buffer_size); + int size = read(pfd.fd, packet.payload.data() + excess, buffer_size - excess); + if (size < 0) + throw std::system_error(errno, std::system_category()); + packet.payload.resize(size + excess); + excess = (excess + size) % sample_size; + remainder.assign(packet.payload.end() - excess, packet.payload.end()); + packet.payload.resize(packet.payload.size() - excess); + packet.timestamp = session.get_offset().to_headset(os_monotonic_get_ns()).count(); + session.send_control(packet); + std::swap(packet.payload, remainder); + } + } + } + catch (const std::exception & e) + { + U_LOG_E("Error in audio thread: %s", e.what()); + } + } + + void run_mic() + { + assert(desc.microphone); + pthread_setname_np(pthread_self(), "mic_thread"); + + const size_t sample_size = desc.speaker->num_channels * sizeof(int16_t); + try + { + while (not quit) + { + pollfd pfd{}; + pfd.fd = mic_pipe.get_fd(); + pfd.events = POLL_OUT; + + 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 mic pipe"); + if (pfd.revents & POLLOUT) + { + auto packet = mic_buffer.pop(); + auto &buffer = packet.payload; + + int written = write(mic_pipe.get_fd(), buffer.data() , buffer.size()); + if (written < 0) + throw std::system_error(errno, std::system_category()); + + // Discard anything that didn't fit the buffer + } + } + } + catch (const std::exception & e) + { + U_LOG_E("Error in audio thread: %s", e.what()); + } + } + + void process_mic_data(const xrt::drivers::wivrn::audio_data & mic_data) override + { + mic_buffer.push(std::move(mic_data)); + } + + pulse_device( + const std::string & source_name, + const std::string & source_description, + const std::string & sink_name, + const std::string & sink_description, + const xrt::drivers::wivrn::from_headset::headset_info_packet & info, + xrt::drivers::wivrn::wivrn_session & session) : + session(session) + { + pa_connection cnx("WiVRn"); + + if (info.microphone) + { + microphone = ensure_source(cnx, source_name.c_str(), source_description, info.microphone->num_channels, info.microphone->sample_rate); + desc.microphone = { + .num_channels = info.microphone->num_channels, + .sample_rate = info.microphone->sample_rate}; + + mic_pipe = open(microphone->socket.c_str(), O_WRONLY | O_NONBLOCK); + if (not mic_pipe) + throw std::system_error(errno, std::system_category(), "failed to open mic pipe " + microphone->socket.string()); + net_thread = std::thread([this]() { run_mic(); }); + } + + if (info.speaker) + { + speaker = ensure_sink(cnx, sink_name.c_str(), sink_description, info.speaker->num_channels, info.speaker->sample_rate); + desc.speaker = { + .num_channels = info.speaker->num_channels, + .sample_rate = info.speaker->sample_rate}; + + speaker_pipe = open(speaker->socket.c_str(), O_RDONLY | O_NONBLOCK); + if (not speaker_pipe) + throw std::system_error(errno, std::system_category(), "failed to open speaker pipe " + speaker->socket.string()); + + net_thread = std::thread([this]() { run_speaker(); }); + } + } +}; + +std::shared_ptr create_pulse_handle( + const std::string & source_name, + const std::string & source_description, + const std::string & sink_name, + const std::string & sink_description, + const xrt::drivers::wivrn::from_headset::headset_info_packet & info, + wivrn_session & session) +{ + return std::make_shared( + source_name, source_description, sink_name, sink_description, info, session); +} + +void unload_module(uintptr_t id) +{ + pa_connection cnx("WiVRn"); + unload_module(cnx, id); +} diff --git a/server/driver/audio_pulse.h b/server/driver/audio_pulse.h new file mode 100644 index 00000000..73bd6a15 --- /dev/null +++ b/server/driver/audio_pulse.h @@ -0,0 +1,29 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2023 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "audio_setup.h" + +std::shared_ptr create_pulse_handle( + const std::string & source_name, + const std::string & source_description, + const std::string & sink_name, + const std::string & sink_description, + const xrt::drivers::wivrn::from_headset::headset_info_packet & info, + xrt::drivers::wivrn::wivrn_session& session); diff --git a/server/driver/audio_setup.cpp b/server/driver/audio_setup.cpp index 807da185..38298a14 100644 --- a/server/driver/audio_setup.cpp +++ b/server/driver/audio_setup.cpp @@ -1,497 +1,15 @@ #include "audio_setup.h" -#include "util/u_logging.h" +#include "audio_pulse.h" -#include "../wivrn_ipc.h" -#include "wivrn_sockets.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static const char * source_name = "WiVRn-mic"; -static const char * sink_name = "WiVRn"; -static const char * source_pipe = "wivrn-source"; -static const char * sink_pipe = "wivrn-sink"; - -static unsigned int buffer_size_ms = 10; - -// max allowed bytes in the output pipe before we start discarding data -// total buffer size = buffer_size_ms + buffer_size_ms * buffer_size_mult -static unsigned int buffer_size_mult = 4; - -struct module_entry -{ - uint32_t module; - uint32_t device; - std::filesystem::path socket; -}; - -void wait_connected(std::atomic & 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 -struct add_void; - -template -struct add_void> -{ - template - static T fn(Args... a, void * userdata) - { - L * f = (L *)userdata; - return (*f)(a...); - } -}; - -template -class wrap_lambda -{ - T impl; - -public: - wrap_lambda(T && l) : - impl(l) {} - - operator auto() - { - using F = decltype(std::function(impl)); - return add_void::template fn; - } - - operator void *() - { - return this; - } -}; - -void unload_module(uintptr_t id); - -void unload_module(pa_context * ctx, uint32_t id) -{ - std::promise 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(); - - remove_cleanup_function(unload_module, id); -} - -std::optional get_sink(pa_context * ctx, const char * name) -{ - std::optional result; - std::promise 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}; - }); - auto op = pa_context_get_sink_info_by_name(ctx, name, cb, cb); - pa_operation_unref(op); - p.get_future().wait(); - return result; -} - -std::optional get_source(pa_context * ctx, const char * name) -{ - std::optional result; - std::promise p; - wrap_lambda cb( - [&result, &p](pa_context *, const pa_source_info * i, int eol) { - if (eol) - { - p.set_value(); - return; - } - result = {.module = i->owner_module, .device = i->index}; - }); - auto op = pa_context_get_source_info_by_name(ctx, name, cb, cb); - pa_operation_unref(op); - p.get_future().wait(); - return result; -} - -std::filesystem::path get_socket_path() -{ - const char * path = std::getenv("XDG_RUNTIME_DIR"); - if (path) - return path; - path = "/tmp/wivrn"; - std::filesystem::create_directories(path); - U_LOG_W("XDG_RUNTIME_DIR is not set, using %s instead", path); - return path; -} - -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 module_index; - wrap_lambda cb = [&module_index](pa_context *, uint32_t index) { - module_index.set_value(index); - }; - std::filesystem::path fifo = get_socket_path() / sink_pipe; - std::stringstream params; - params << "sink_name=" << std::quoted(name) - << " file=" << std::quoted(fifo.string()) - << " channels=" << channels - << " rate=" << sample_rate - << " use_system_clock_for_timing=yes" - << " sink_properties=" << PA_PROP_DEVICE_DESCRIPTION << "=" << std::quoted(description) - << PA_PROP_DEVICE_ICON_NAME << "=network-wireless"; - ; - auto op = pa_context_load_module(ctx, "module-pipe-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)); - sink->socket = fifo; - - add_cleanup_function(unload_module, sink->module); - - return *sink; -} - -module_entry ensure_source(pa_context * ctx, const char * name, const std::string & description, int channels, int sample_rate) -{ - auto source = get_source(ctx, name); - if (source) - unload_module(ctx, source->module); - - std::promise module_index; - wrap_lambda cb = [&module_index](pa_context *, uint32_t index) { - module_index.set_value(index); - }; - std::filesystem::path fifo = get_socket_path() / source_pipe; - std::stringstream params; - params << "source_name=" << std::quoted(name) - << " file=" << std::quoted(fifo.string()) - << " channels=" << channels - << " rate=" << sample_rate - << " use_system_clock_for_timing=yes" - << " source_properties=" << PA_PROP_DEVICE_DESCRIPTION << "=" << std::quoted(description) - << PA_PROP_DEVICE_ICON_NAME << "=network-wireless"; - ; - auto op = pa_context_load_module(ctx, "module-pipe-source", params.str().c_str(), cb, cb); - pa_operation_unref(op); - module_index.get_future().wait(); - - source = get_source(ctx, name); - if (not source) - std::runtime_error("failed to create audio source " + std::string(name)); - source->socket = fifo; - return *source; -} - -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 main_loop; - std::unique_ptr ctx; - std::atomic 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 -{ - xrt::drivers::wivrn::to_headset::audio_stream_description desc; - - std::thread net_thread; - std::atomic quit; - xrt::drivers::wivrn::TCPListener listener; - - std::optional speaker; - std::optional microphone; - - int mic_buf_size; - int spk_buf_size; - - ~pulse_publish_handle() - { - quit = true; - if (net_thread.joinable()) - net_thread.join(); - if (speaker or microphone) - { - try - { - pa_connection cnx("WiVRn"); - if (speaker) - unload_module(cnx, speaker->module); - if (microphone) - unload_module(cnx, microphone->module); - } - 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; - }; - - void serve_client(xrt::drivers::wivrn::fd_base & client) - { - int nodelay = 1; - if (setsockopt(client.get_fd(), IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) - U_LOG_W("failed to set TCP_NODELAY opeion on audio socket: %s", strerror(errno)); - try - { - // file descriptors: - // in pairs (read, write) - // negative if already available - std::vector pfd; - size_t num_pairs; - - xrt::drivers::wivrn::fd_base speaker_pipe; - xrt::drivers::wivrn::fd_base mic_pipe; - - ssize_t bufsize[] = {0, 0}; - ssize_t max_bytes_in_pipe[] = {0, 0}; - char * buf = new char[std::max(spk_buf_size, mic_buf_size)]; - - if (speaker) - { - bufsize[num_pairs] = spk_buf_size; - speaker_pipe = open(speaker->socket.c_str(), O_RDONLY | O_NONBLOCK); - if (speaker_pipe.get_fd() < 0) - throw std::system_error(errno, std::system_category(), "failed to open speaker pipe " + speaker->socket.string()); - pfd.push_back({.fd = speaker_pipe.get_fd(), .events = POLLIN}); - pfd.push_back({.fd = client.get_fd(), .events = POLLOUT}); - - num_pairs++; - - // flush pipe, so we don't have old samples - while (read(speaker_pipe.get_fd(), buf, spk_buf_size) > 0) - {} - } - if (microphone) - { - bufsize[num_pairs] = mic_buf_size; - max_bytes_in_pipe[num_pairs] = mic_buf_size * buffer_size_mult; - - mic_pipe = open(microphone->socket.c_str(), O_WRONLY); - if (mic_pipe.get_fd() < 0) - throw std::system_error(errno, std::system_category(), "failed to open microphone pipe " + microphone->socket.string()); - pfd.push_back({.fd = client.get_fd(), .events = POLLIN}); - pfd.push_back({.fd = mic_pipe.get_fd(), .events = POLLOUT}); - - num_pairs++; - } - while (not quit) - { - int r = ::poll(pfd.data(), pfd.size(), 100); - if (r < 0) - throw std::system_error(errno, std::system_category()); - - for (size_t p = 0; p < num_pairs; p++) - { - int i = p * 2; - int o = i + 1; - if ((pfd[i].revents | pfd[o].revents) & (POLLHUP | POLLERR)) - throw std::runtime_error("Error on audio socket"); - - if ((pfd[i].revents) & POLLIN) - { - ssize_t bytes_read = read(pfd[i].fd, buf, bufsize[p]); - ssize_t bytes_to_write; - - if (max_bytes_in_pipe[p] != 0) - { - ssize_t bytes_in_pipe; - if (ioctl(pfd[o].fd, FIONREAD, &bytes_in_pipe) == 0) - bytes_to_write = std::min((int)max_bytes_in_pipe[p] - (int)bytes_in_pipe, (int)bytes_read); - else - bytes_to_write = bytes_read; - } - else - bytes_to_write = bytes_read; - - ssize_t written = write(pfd[o].fd, buf, bytes_to_write); - if (written < 0) - throw std::system_error(errno, std::system_category(), "failed to transfer audio data"); - } - } - } - } - catch (const std::exception & e) - { - U_LOG_E("Error while serving audio: %s", e.what()); - } - } - - void run() - { - pthread_setname_np(pthread_self(), "audio_thread"); - - try - { - while (not quit) - { - pollfd pfd{}; - pfd.fd = listener.get_fd(); - pfd.events = POLL_IN; - - 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) - { - auto client = listener.accept().first; - serve_client(client); - } - } - } - catch (const std::exception & e) - { - U_LOG_E("Error in audio thread: %s", e.what()); - } - } - - static std::shared_ptr 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(); - - if (info.microphone) - { - result->microphone = ensure_source(cnx, source_name.c_str(), source_description, info.microphone->num_channels, info.microphone->sample_rate); - result->mic_buf_size = 2 * info.microphone->num_channels * (info.microphone->sample_rate / 1000 * buffer_size_ms); - result->desc.microphone = {.num_channels = info.microphone->num_channels, .sample_rate = info.microphone->sample_rate}; - } - if (info.speaker) - { - result->speaker = ensure_sink(cnx, sink_name.c_str(), sink_description, info.speaker->num_channels, info.speaker->sample_rate); - result->spk_buf_size = 2 * info.speaker->num_channels * (info.speaker->sample_rate / 1000 * buffer_size_ms); - result->desc.speaker = {.num_channels = info.speaker->num_channels, .sample_rate = info.speaker->sample_rate}; - } - - result->listener = xrt::drivers::wivrn::TCPListener(listen_port); - result->desc.port = listen_port; - result->net_thread = std::thread(&pulse_publish_handle::run, result.get()); - - return result; - } -}; - -std::shared_ptr audio_publish_handle::create( +std::shared_ptr audio_device::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) + const xrt::drivers::wivrn::from_headset::headset_info_packet & info, + xrt::drivers::wivrn::wivrn_session& session) { - return pulse_publish_handle::create(source_name, source_description, sink_name, sink_description, listen_port, info); -} - -void unload_module(uintptr_t id) -{ - pa_connection cnx("WiVRn"); - unload_module(cnx, id); + // TODO: other backends + return create_pulse_handle(source_name, source_description, sink_name, sink_description, info, session); } diff --git a/server/driver/audio_setup.h b/server/driver/audio_setup.h index 23324a12..51ad7080 100644 --- a/server/driver/audio_setup.h +++ b/server/driver/audio_setup.h @@ -24,19 +24,26 @@ #include "wivrn_packets.h" -struct audio_publish_handle +namespace xrt::drivers::wivrn +{ +class wivrn_session; +} + +struct audio_device { // unpublishes the device - virtual ~audio_publish_handle() = default; + virtual ~audio_device() = default; virtual xrt::drivers::wivrn::to_headset::audio_stream_description description() const = 0; - static std::shared_ptr create( + virtual void process_mic_data(const xrt::drivers::wivrn::audio_data &) = 0; + + static std::shared_ptr 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); + const xrt::drivers::wivrn::from_headset::headset_info_packet & info, + xrt::drivers::wivrn::wivrn_session& session); }; diff --git a/server/driver/wivrn_session.cpp b/server/driver/wivrn_session.cpp index fc49d30e..d0ad1142 100644 --- a/server/driver/wivrn_session.cpp +++ b/server/driver/wivrn_session.cpp @@ -93,13 +93,14 @@ wivrn_system_devices * xrt::drivers::wivrn::wivrn_session::create_session(xrt::d try { - self->audio_handle = audio_publish_handle::create( + self->audio_handle = audio_device::create( "wivrn.source", "WiVRn microphone", "wivrn.sink", "WiVRn", - xrt::drivers::wivrn::audio_server_port, - info); + info, + *self + ); self->send_control(self->audio_handle->description()); } catch (const std::exception & e) @@ -206,6 +207,12 @@ void wivrn_session::operator()(from_headset::feedback && feedback) dump_time("display", feedback.frame_index, o.from_headset(feedback.displayed), feedback.stream_index); } +void wivrn_session::operator()(audio_data&& data) +{ + if (audio_handle) + audio_handle->process_mic_data(data); +} + uint64_t clock_offset::from_headset(uint64_t ts) const { return ts - epoch_offset.count(); diff --git a/server/driver/wivrn_session.h b/server/driver/wivrn_session.h index e01b5e0d..137c2be0 100644 --- a/server/driver/wivrn_session.h +++ b/server/driver/wivrn_session.h @@ -32,7 +32,7 @@ class wivrn_hmd; class wivrn_controller; -struct audio_publish_handle; +struct audio_device; namespace xrt::drivers::wivrn { @@ -60,7 +60,7 @@ class wivrn_session : public std::enable_shared_from_this std::mutex csv_mutex; std::ofstream feedback_csv; - std::shared_ptr audio_handle; + std::shared_ptr audio_handle; wivrn_session(TCP && tcp, in6_addr & address); @@ -76,6 +76,7 @@ public: void operator()(from_headset::inputs &&); void operator()(from_headset::timesync_response &&); void operator()(from_headset::feedback &&); + void operator()(audio_data &&); template void send_stream(const T & packet)