5#ifndef BOOST_PROCESS_VERSION
6 #define BOOST_PROCESS_VERSION 1
21#include <sys/socket.h>
26#include <boost/process/v1/child.hpp>
27#include <boost/process/v1/env.hpp>
28#include <boost/process/v1/environment.hpp>
29#include <boost/process/v1/handles.hpp>
30#include <boost/process/v1/io.hpp>
31#include <boost/process/v1/search_path.hpp>
32#include <pipewire/pipewire.h>
33#include <spa/param/audio/format-utils.h>
34#include <pulse/pulseaudio.h>
40namespace bp = boost::process::v1;
41namespace fs = std::filesystem;
42using namespace std::literals;
44namespace platf::session_audio {
46 std::string positions(
int channels) {
49 return "FL FR FC LFE RL RR";
51 return "FL FR FC LFE RL RR SL SR";
60 std::string pipewire_conf(
const std::string &sink,
int channels) {
61 std::string conf = R
"(context.properties = {
63 core.name = pipewire-0
65 default.clock.rate = 48000
68 audio.convert.* = audioconvert/libspa-audioconvert
69 video.convert.* = videoconvert/libspa-videoconvert
70 support.* = support/libspa-support
73 { name = libpipewire-module-rt args = { nice.level = -11 rt.prio = 88 rtportal.enabled = false } flags = [ ifexists nofail ] }
74 { name = libpipewire-module-protocol-native args = { sockets = [ { name = pipewire-0 } { name = pipewire-0-manager } ] } }
75 { name = libpipewire-module-metadata }
76 { name = libpipewire-module-spa-node-factory }
77 { name = libpipewire-module-client-node }
78 { name = libpipewire-module-access }
79 { name = libpipewire-module-adapter }
80 { name = libpipewire-module-link-factory }
81 { name = libpipewire-module-protocol-pulse }
85 server.address = [ "unix:native" ]
89 { factory = spa-node-factory args = { factory.name = support.node.driver node.name = Dummy-Driver node.group = pipewire.dummy priority.driver = 20000 } }
90 { factory = spa-node-factory args = { factory.name = support.node.driver node.name = Freewheel-Driver node.group = pipewire.freewheel priority.driver = 19000 node.freewheel = true } }
91 { factory = adapter args = {
92 factory.name = support.null-audio-sink
93 node.name = )" + sink + R"(
94 node.description = "Hermes session"
95 media.class = Audio/Sink
96 audio.position = [ )" + positions(channels) + R"( ]
97 monitor.channel-volumes = true
107 constexpr auto wireplumber_conf = R
"(override.context.modules = [
108 { name = libpipewire-module-rt args = { nice.level = -11 rtportal.enabled = false } flags = [ ifexists nofail ] }
109 { name = libpipewire-module-protocol-native }
110 { name = libpipewire-module-metadata }
112wireplumber.profiles = {
114 inherits = [ policy, mixin.systemwide-session, mixin.stateless ]
115 hardware.audio = disabled
116 hardware.bluetooth = disabled
117 hardware.video-capture = disabled
118 support.dbus = disabled
119 api.notifications = disabled
120 support.mpris = disabled
121 hooks.linking.pause-playback = disabled
126 bool write_file(
const fs::path &path,
const std::string &contents) {
128 fs::create_directories(path.parent_path(), ec);
129 std::ofstream file {path};
134 void stop(bp::child &child) {
135 if (!child.valid()) {
138 if (child.running()) {
139 ::kill(child.id(), SIGTERM);
141 for (
int i = 0; i < 100 && child.running(); ++i) {
142 std::this_thread::sleep_for(20ms);
144 if (child.running()) {
155 void write(
const std::int16_t *samples,
int count) {
156 std::lock_guard lock {mutex};
157 for (
int i = 0; i < count; ++i) {
160 if (fill == ring.size()) {
161 head = (head + 1) % ring.size();
164 ring[(head + fill++) % ring.size()] = samples[i];
169 void read(std::int16_t *out, std::size_t count) {
171 if (std::unique_lock lock {mutex, std::try_to_lock}; lock.owns_lock()) {
172 playing = playing || fill >= start_fill;
174 n = std::min(count, fill);
175 for (std::size_t i = 0; i < n; ++i) {
176 out[i] = ring[(head + i) % ring.size()];
178 head = (head + n) % ring.size();
181 playing = n == count;
184 std::fill(out + n, out + count, 0);
188 static constexpr std::size_t start_fill = 48 * 30;
189 std::array<std::int16_t, 48 * 80> ring {};
196 std::mutex mics_mutex;
197 std::map<std::string, std::weak_ptr<mic_buffer_t>> mics;
199 int connect_socket(
const std::string &path) {
200 sockaddr_un address {.sun_family = AF_UNIX};
201 if (path.size() >=
sizeof address.sun_path) {
204 path.copy(address.sun_path, path.size());
205 const int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
206 if (fd >= 0 && ::connect(fd,
reinterpret_cast<const sockaddr *
>(&address),
sizeof address) < 0) {
216 mic_stream_t(
const std::string &remote,
const std::string &name, std::shared_ptr<mic_buffer_t> buffer):
217 buffer {std::move(buffer)} {
218 static std::once_flag initialized;
219 std::call_once(initialized, [] {
220 pw_init(
nullptr,
nullptr);
223 loop = pw_thread_loop_new(
"hermes-mic",
nullptr);
224 context = pw_context_new(pw_thread_loop_get_loop(loop),
nullptr, 0);
226 const int fd = connect_socket(remote);
227 core = fd < 0 ? nullptr : pw_context_connect_fd(context, fd,
nullptr, 0);
232 stream = pw_stream_new(core,
"Client microphone", pw_properties_new(PW_KEY_MEDIA_TYPE,
"Audio", PW_KEY_MEDIA_CLASS,
"Audio/Source", PW_KEY_NODE_NAME, name.c_str(), PW_KEY_NODE_DESCRIPTION,
"Client microphone", PW_KEY_NODE_LATENCY,
"480/48000",
nullptr));
233 static const pw_stream_events events {.version = PW_VERSION_STREAM_EVENTS, .process = process};
234 pw_stream_add_listener(stream, &listener, &events,
this);
236 spa_audio_info_raw info {};
237 info.format = SPA_AUDIO_FORMAT_S16;
240 info.position[0] = SPA_AUDIO_CHANNEL_MONO;
241 std::uint8_t pod[1024];
242 auto builder = SPA_POD_BUILDER_INIT(pod,
sizeof pod);
243 const spa_pod *params[] {spa_format_audio_raw_build(&builder, SPA_PARAM_EnumFormat, &info)};
244 if (pw_stream_connect(stream, PW_DIRECTION_OUTPUT, PW_ID_ANY,
static_cast<pw_stream_flags
>(PW_STREAM_FLAG_MAP_BUFFERS | PW_STREAM_FLAG_RT_PROCESS), params, 1) == 0 &&
245 pw_thread_loop_start(loop) == 0) {
251 pw_thread_loop_stop(loop);
253 pw_stream_destroy(stream);
256 pw_core_disconnect(core);
258 pw_context_destroy(context);
259 pw_thread_loop_destroy(loop);
265 static void process(
void *data) {
266 auto *self =
static_cast<mic_stream_t *
>(data);
267 pw_buffer *buffer = pw_stream_dequeue_buffer(self->stream);
271 spa_data &out = buffer->buffer->datas[0];
273 auto frames = out.maxsize /
sizeof(std::int16_t);
274 if (buffer->requested) {
275 frames = std::min<std::size_t>(frames, buffer->requested);
277 self->buffer->read(
static_cast<std::int16_t *
>(out.data), frames);
278 out.chunk->offset = 0;
279 out.chunk->stride =
sizeof(std::int16_t);
280 out.chunk->size = frames *
sizeof(std::int16_t);
282 pw_stream_queue_buffer(self->stream, buffer);
285 std::shared_ptr<mic_buffer_t> buffer;
286 pw_thread_loop *loop {};
287 pw_context *context {};
289 pw_stream *stream {};
290 spa_hook listener {};
295 pipewire_t(std::string runtime_dir, std::string mic):
296 runtime_dir {std::move(runtime_dir)},
297 mic {std::move(mic)} {
300 ~pipewire_t()
override {
302 std::lock_guard lock {mics_mutex};
310 std::string pulse_server()
const override {
311 return "unix:" + runtime_dir +
"/pulse/native";
314 std::string pipewire_remote()
const override {
315 return runtime_dir +
"/pipewire-0";
318 std::string runtime_dir;
320 std::unique_ptr<mic_stream_t> mic_stream;
322 bp::child wireplumber;
329 bool wait_for_audio_graph(pipewire_t &server,
const std::string &sink,
const std::string &mic) {
330 util::safe_ptr<pa_mainloop, pa_mainloop_free> loop {pa_mainloop_new()};
334 util::safe_ptr<pa_context, pa_context_unref> context {
335 pa_context_new(pa_mainloop_get_api(loop.get()),
"Hermes session readiness")
337 if (!context || pa_context_connect(context.get(), server.pulse_server().c_str(), PA_CONTEXT_NOAUTOSPAWN,
nullptr) < 0) {
341 pa_context_disconnect(context.get());
343 const auto deadline = std::chrono::steady_clock::now() + 5s;
344 while (std::chrono::steady_clock::now() < deadline) {
345 if (!server.pipewire.running() || !server.wireplumber.running() || !PA_CONTEXT_IS_GOOD(pa_context_get_state(context.get()))) {
348 if (pa_mainloop_iterate(loop.get(), 0,
nullptr) < 0) {
351 if (pa_context_get_state(context.get()) != PA_CONTEXT_READY) {
352 std::this_thread::sleep_for(10ms);
357 const std::string &sink;
358 const std::string &mic;
361 bool defaults =
false;
362 } graph {sink, mic,
false, mic.empty(),
false};
364 util::safe_ptr<pa_operation, pa_operation_unref> output {
365 pa_context_get_sink_info_by_name(context.get(), sink.c_str(), [](pa_context *,
const pa_sink_info *info,
int,
void *data) {
366 auto &graph = *static_cast<graph_t *>(data);
367 if (info && info->name) {
368 graph.output = graph.sink == info->name;
373 util::safe_ptr<pa_operation, pa_operation_unref> input;
375 input.reset(pa_context_get_source_info_by_name(context.get(), mic.c_str(), [](pa_context *,
const pa_source_info *info,
int,
void *data) {
376 auto &graph = *static_cast<graph_t *>(data);
377 if (info && info->name) {
378 graph.input = graph.mic == info->name;
383 util::safe_ptr<pa_operation, pa_operation_unref> defaults {
384 pa_context_get_server_info(context.get(), [](pa_context *,
const pa_server_info *info,
void *data) {
385 auto &graph = *static_cast<graph_t *>(data);
386 graph.defaults = info && info->default_sink_name && graph.sink == info->default_sink_name &&
387 (graph.mic.empty() || (info->default_source_name && graph.mic == info->default_source_name));
391 auto cancel_operations = util::fail_guard([&]() {
392 for (
auto *operation : {output.get(), input.get(), defaults.get()}) {
394 pa_operation_cancel(operation);
398 if (!output || !defaults || (!mic.empty() && !input)) {
401 const auto pending = [&]() {
402 return pa_operation_get_state(output.get()) == PA_OPERATION_RUNNING ||
403 pa_operation_get_state(defaults.get()) == PA_OPERATION_RUNNING ||
404 (input && pa_operation_get_state(input.get()) == PA_OPERATION_RUNNING);
406 while (pending() && std::chrono::steady_clock::now() < deadline) {
407 if (!server.pipewire.running() || !server.wireplumber.running() || !PA_CONTEXT_IS_GOOD(pa_context_get_state(context.get())) || pa_mainloop_iterate(loop.get(), 0,
nullptr) < 0) {
410 std::this_thread::sleep_for(10ms);
415 if (graph.output && graph.input && graph.defaults) {
418 std::this_thread::sleep_for(20ms);
424 std::unique_ptr<server_t>
start(
const std::string &runtime_dir,
const std::string &sink,
int channels,
const std::string &mic) {
425 const auto pipewire = bp::search_path(
"pipewire");
426 const auto wireplumber = bp::search_path(
"wireplumber");
427 if (pipewire.empty() || wireplumber.empty()) {
428 BOOST_LOG(warning) <<
"PipeWire or WirePlumber is not installed; no private audio server"sv;
432 const fs::path dir = fs::path {runtime_dir} /
"audio";
434 const auto conf = dir /
"hermes-session.conf";
435 if (!write_file(conf, pipewire_conf(sink, channels)) ||
436 !write_file(dir /
"config/wireplumber/wireplumber.conf.d/hermes-session.conf", wireplumber_conf)) {
437 BOOST_LOG(warning) <<
"Couldn't write the private audio server's config to "sv << dir.string();
443 auto env = bp::environment {boost::this_process::environment()};
444 for (
const auto *name : {
"PIPEWIRE_REMOTE",
"PIPEWIRE_RUNTIME_DIR",
"PIPEWIRE_CONFIG_DIR",
"PIPEWIRE_CONFIG_NAME",
"PIPEWIRE_CORE",
"PIPEWIRE_NODE",
"PIPEWIRE_PROPS",
"PULSE_SERVER",
"PULSE_RUNTIME_PATH",
"PULSE_SINK",
"PULSE_SOURCE",
"WIREPLUMBER_CONFIG_DIR",
"DBUS_SESSION_BUS_ADDRESS",
"DISPLAY",
"WAYLAND_DISPLAY"}) {
447 env[
"XDG_RUNTIME_DIR"] = runtime_dir;
448 env[
"XDG_CONFIG_HOME"] = (dir /
"config").
string();
449 env[
"XDG_STATE_HOME"] = (dir /
"state").
string();
451 auto server = std::make_unique<pipewire_t>(runtime_dir, mic);
452 server->pipewire = bp::child(pipewire,
"-c", conf.string(), env, bp::std_in < bp::null, bp::limit_handles, ec);
454 BOOST_LOG(warning) <<
"Couldn't start PipeWire: "sv << ec.message();
459 const auto socket = fs::path {runtime_dir} /
"pulse" /
"native";
460 for (
auto deadline = std::chrono::steady_clock::now() + 5s; !fs::exists(socket, ec);) {
461 if (!server->pipewire.running() || std::chrono::steady_clock::now() > deadline) {
462 BOOST_LOG(warning) <<
"The private PipeWire server didn't come up in "sv << runtime_dir;
465 std::this_thread::sleep_for(20ms);
468 server->wireplumber = bp::child(wireplumber,
"-p",
"hermes-session", env, bp::std_in < bp::null, bp::limit_handles, ec);
470 BOOST_LOG(warning) <<
"Couldn't start WirePlumber: "sv << ec.message();
475 auto buffer = std::make_shared<mic_buffer_t>();
476 server->mic_stream = std::make_unique<mic_stream_t>(server->pipewire_remote(), mic, buffer);
477 if (!server->mic_stream->connected) {
478 BOOST_LOG(warning) <<
"Couldn't create the session mic ["sv << mic <<
']';
481 std::lock_guard lock {mics_mutex};
485 if (!wait_for_audio_graph(*server, sink, mic)) {
486 BOOST_LOG(warning) <<
"The private audio graph was not ready in "sv << runtime_dir
487 <<
"; expected sink [" << sink <<
"] and source [" << mic <<
']';
491 BOOST_LOG(info) <<
"Started a private PipeWire server in "sv << runtime_dir <<
" with sink ["sv << sink <<
']'
492 << (mic.empty() ?
""s :
" and mic ["s + mic +
']');
499 explicit buffer_mic_writer_t(std::shared_ptr<mic_buffer_t> buffer):
500 buffer {std::move(buffer)} {
503 void write(
const std::int16_t *samples,
int count)
override {
504 buffer->write(samples, count);
508 std::shared_ptr<mic_buffer_t> buffer;
512 std::unique_ptr<mic_writer_t>
open_mic(
const std::string &mic) {
513 std::lock_guard lock {mics_mutex};
514 const auto it = mics.find(mic);
515 auto buffer = it == mics.end() ? nullptr : it->second.lock();
517 BOOST_LOG(warning) <<
"No session mic ["sv << mic <<
']';
520 return std::make_unique<buffer_mic_writer_t>(std::move(buffer));
Feeds a client's microphone into a session mic.
PipeWire and WirePlumber running in a session's runtime directory.
void disconnect(resp_https_t response, req_https_t request)
Disconnect a client.
Declarations for logging related functions.
int write_file(const char *path, const std::string_view &contents)
Writes a file.
std::unique_ptr< server_t > start(const std::string &runtime_dir, const std::string &sink, int channels, const std::string &mic)
Start a server in runtime_dir with sink as its only output and, if mic is not empty,...
std::unique_ptr< mic_writer_t > open_mic(const std::string &mic)
Open a session mic for writing 48 kHz mono samples, or nullptr.
An isolated session's own PipeWire server.
bool stop(const std::string &client_uuid)
Stop the client's session unit. Stopping one that is already gone succeeds, so this is safe to call o...