Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
session_audio.cpp
Go to the documentation of this file.
1
5#ifndef BOOST_PROCESS_VERSION
6 #define BOOST_PROCESS_VERSION 1
7#endif
8
9// standard includes
10#include <algorithm>
11#include <array>
12#include <chrono>
13#include <csignal>
14#include <filesystem>
15#include <fstream>
16#include <map>
17#include <mutex>
18#include <thread>
19
20// platform includes
21#include <sys/socket.h>
22#include <sys/un.h>
23#include <unistd.h>
24
25// lib includes
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>
35
36// local includes
37#include "session_audio.h"
38#include "src/logging.h"
39
40namespace bp = boost::process::v1;
41namespace fs = std::filesystem;
42using namespace std::literals;
43
44namespace platf::session_audio {
45 namespace {
46 std::string positions(int channels) {
47 switch (channels) {
48 case 6:
49 return "FL FR FC LFE RL RR";
50 case 8:
51 return "FL FR FC LFE RL RR SL SR";
52 default:
53 return "FL FR";
54 }
55 }
56
57 // No ALSA, Bluetooth or camera monitors: the sink below and Hermes' mic
58 // stream are the only devices. The pulse server takes no D-Bus name, which the
59 // host's already owns.
60 std::string pipewire_conf(const std::string &sink, int channels) {
61 std::string conf = R"(context.properties = {
62 core.daemon = true
63 core.name = pipewire-0
64 link.max-buffers = 16
65 default.clock.rate = 48000
66}
67context.spa-libs = {
68 audio.convert.* = audioconvert/libspa-audioconvert
69 video.convert.* = videoconvert/libspa-videoconvert
70 support.* = support/libspa-support
71}
72context.modules = [
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 }
82)";
83 conf += R"(]
84pulse.properties = {
85 server.address = [ "unix:native" ]
86 server.dbus-name = ""
87}
88context.objects = [
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
98 object.linger = true
99 } }
100]
101)";
102 return conf;
103 }
104
105 // Linking and default nodes only; nothing is remembered, and nothing
106 // talks to the host's session bus (MPRIS pausing would reach its players).
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 }
111]
112wireplumber.profiles = {
113 hermes-session = {
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
122 }
123}
124)";
125
126 bool write_file(const fs::path &path, const std::string &contents) {
127 std::error_code ec;
128 fs::create_directories(path.parent_path(), ec);
129 std::ofstream file {path};
130 file << contents;
131 return file.good();
132 }
133
134 void stop(bp::child &child) {
135 if (!child.valid()) {
136 return;
137 }
138 if (child.running()) {
139 ::kill(child.id(), SIGTERM);
140 }
141 for (int i = 0; i < 100 && child.running(); ++i) {
142 std::this_thread::sleep_for(20ms);
143 }
144 if (child.running()) {
145 child.terminate();
146 }
147 child.wait();
148 }
149
150 // The client's microphone between Hermes and the session: a jitter buffer
151 // just deep enough for Wi-Fi. (PipeWire's pipe-tunnel holds 8192 frames,
152 // 171 ms, to match clocks; dropping a few samples does that here.)
153 class mic_buffer_t {
154 public:
155 void write(const std::int16_t *samples, int count) {
156 std::lock_guard lock {mutex};
157 for (int i = 0; i < count; ++i) {
158 // Full: the oldest go, so a fast client clock or a burst after a
159 // stall never turns into delay.
160 if (fill == ring.size()) {
161 head = (head + 1) % ring.size();
162 --fill;
163 }
164 ring[(head + fill++) % ring.size()] = samples[i];
165 }
166 }
167
168 // Real-time side: never waits for the writer.
169 void read(std::int16_t *out, std::size_t count) {
170 std::size_t n = 0;
171 if (std::unique_lock lock {mutex, std::try_to_lock}; lock.owns_lock()) {
172 playing = playing || fill >= start_fill;
173 if (playing) {
174 n = std::min(count, fill);
175 for (std::size_t i = 0; i < n; ++i) {
176 out[i] = ring[(head + i) % ring.size()];
177 }
178 head = (head + n) % ring.size();
179 fill -= n;
180 // Underrun: silence until start_fill is buffered again.
181 playing = n == count;
182 }
183 }
184 std::fill(out + n, out + count, 0);
185 }
186
187 private:
188 static constexpr std::size_t start_fill = 48 * 30;
189 std::array<std::int16_t, 48 * 80> ring {};
190 std::size_t head {};
191 std::size_t fill {};
192 bool playing {};
193 std::mutex mutex;
194 };
195
196 std::mutex mics_mutex;
197 std::map<std::string, std::weak_ptr<mic_buffer_t>> mics;
198
199 int connect_socket(const std::string &path) {
200 sockaddr_un address {.sun_family = AF_UNIX};
201 if (path.size() >= sizeof address.sun_path) {
202 return -1;
203 }
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) {
207 ::close(fd);
208 return -1;
209 }
210 return fd;
211 }
212
213 // The session's mic: an Audio/Source stream on its server, fed from buffer.
214 class mic_stream_t {
215 public:
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);
221 });
222
223 loop = pw_thread_loop_new("hermes-mic", nullptr);
224 context = pw_context_new(pw_thread_loop_get_loop(loop), nullptr, 0);
225 // PIPEWIRE_REMOTE overrides a remote name, so connect the socket ourselves.
226 const int fd = connect_socket(remote);
227 core = fd < 0 ? nullptr : pw_context_connect_fd(context, fd, nullptr, 0);
228 if (!core) {
229 return;
230 }
231
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);
235
236 spa_audio_info_raw info {};
237 info.format = SPA_AUDIO_FORMAT_S16;
238 info.rate = 48000;
239 info.channels = 1;
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) {
246 connected = true;
247 }
248 }
249
250 ~mic_stream_t() {
251 pw_thread_loop_stop(loop);
252 if (stream) {
253 pw_stream_destroy(stream);
254 }
255 if (core) {
256 pw_core_disconnect(core);
257 }
258 pw_context_destroy(context);
259 pw_thread_loop_destroy(loop);
260 }
261
262 bool connected {};
263
264 private:
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);
268 if (!buffer) {
269 return;
270 }
271 spa_data &out = buffer->buffer->datas[0];
272 if (out.data) {
273 auto frames = out.maxsize / sizeof(std::int16_t);
274 if (buffer->requested) {
275 frames = std::min<std::size_t>(frames, buffer->requested);
276 }
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);
281 }
282 pw_stream_queue_buffer(self->stream, buffer);
283 }
284
285 std::shared_ptr<mic_buffer_t> buffer;
286 pw_thread_loop *loop {};
287 pw_context *context {};
288 pw_core *core {};
289 pw_stream *stream {};
290 spa_hook listener {};
291 };
292
293 class pipewire_t: public server_t {
294 public:
295 pipewire_t(std::string runtime_dir, std::string mic):
296 runtime_dir {std::move(runtime_dir)},
297 mic {std::move(mic)} {
298 }
299
300 ~pipewire_t() override {
301 if (!mic.empty()) {
302 std::lock_guard lock {mics_mutex};
303 mics.erase(mic);
304 }
305 mic_stream.reset();
306 stop(wireplumber);
307 stop(pipewire);
308 }
309
310 std::string pulse_server() const override {
311 return "unix:" + runtime_dir + "/pulse/native";
312 }
313
314 std::string pipewire_remote() const override {
315 return runtime_dir + "/pipewire-0";
316 }
317
318 std::string runtime_dir;
319 std::string mic;
320 std::unique_ptr<mic_stream_t> mic_stream;
321 bp::child pipewire;
322 bp::child wireplumber;
323 };
324
325 // A socket on disk is not a ready audio graph. In particular WirePlumber
326 // can exit after exec, or the session's default node may not exist yet.
327 // Ask the explicitly named private server; never autospawn or probe the
328 // host's default server while bringing an isolated session up.
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()};
331 if (!loop) {
332 return false;
333 }
334 util::safe_ptr<pa_context, pa_context_unref> context {
335 pa_context_new(pa_mainloop_get_api(loop.get()), "Hermes session readiness")
336 };
337 if (!context || pa_context_connect(context.get(), server.pulse_server().c_str(), PA_CONTEXT_NOAUTOSPAWN, nullptr) < 0) {
338 return false;
339 }
340 auto disconnect = util::fail_guard([&]() {
341 pa_context_disconnect(context.get());
342 });
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()))) {
346 return false;
347 }
348 if (pa_mainloop_iterate(loop.get(), 0, nullptr) < 0) {
349 return false;
350 }
351 if (pa_context_get_state(context.get()) != PA_CONTEXT_READY) {
352 std::this_thread::sleep_for(10ms);
353 continue;
354 }
355
356 struct graph_t {
357 const std::string &sink;
358 const std::string &mic;
359 bool output = false;
360 bool input = false;
361 bool defaults = false;
362 } graph {sink, mic, false, mic.empty(), false};
363
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;
369 }
370 },
371 &graph)
372 };
373 util::safe_ptr<pa_operation, pa_operation_unref> input;
374 if (!mic.empty()) {
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;
379 }
380 },
381 &graph));
382 }
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));
388 },
389 &graph)
390 };
391 auto cancel_operations = util::fail_guard([&]() {
392 for (auto *operation : {output.get(), input.get(), defaults.get()}) {
393 if (operation) {
394 pa_operation_cancel(operation);
395 }
396 }
397 });
398 if (!output || !defaults || (!mic.empty() && !input)) {
399 return false;
400 }
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);
405 };
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) {
408 return false;
409 }
410 std::this_thread::sleep_for(10ms);
411 }
412 if (pending()) {
413 return false;
414 }
415 if (graph.output && graph.input && graph.defaults) {
416 return true;
417 }
418 std::this_thread::sleep_for(20ms);
419 }
420 return false;
421 }
422 } // namespace
423
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;
429 return nullptr;
430 }
431
432 const fs::path dir = fs::path {runtime_dir} / "audio";
433 // Not named pipewire.conf, so no system or user fragments apply.
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();
438 return nullptr;
439 }
440 std::error_code ec;
441
442 // The user's own PipeWire config and WirePlumber state stay out of it.
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"}) {
445 env.erase(name);
446 }
447 env["XDG_RUNTIME_DIR"] = runtime_dir;
448 env["XDG_CONFIG_HOME"] = (dir / "config").string();
449 env["XDG_STATE_HOME"] = (dir / "state").string();
450
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);
453 if (ec) {
454 BOOST_LOG(warning) << "Couldn't start PipeWire: "sv << ec.message();
455 return nullptr;
456 }
457
458 // Applications start once the pulse socket exists; it is created last.
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;
463 return nullptr;
464 }
465 std::this_thread::sleep_for(20ms);
466 }
467
468 server->wireplumber = bp::child(wireplumber, "-p", "hermes-session", env, bp::std_in < bp::null, bp::limit_handles, ec);
469 if (ec) {
470 BOOST_LOG(warning) << "Couldn't start WirePlumber: "sv << ec.message();
471 return nullptr;
472 }
473 // The mic is Hermes' own stream, so the graph is only complete once it exists.
474 if (!mic.empty()) {
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 << ']';
479 return nullptr;
480 }
481 std::lock_guard lock {mics_mutex};
482 mics[mic] = buffer;
483 }
484
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 << ']';
488 return nullptr;
489 }
490
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 + ']');
493 return server;
494 }
495
496 namespace {
497 class buffer_mic_writer_t: public mic_writer_t {
498 public:
499 explicit buffer_mic_writer_t(std::shared_ptr<mic_buffer_t> buffer):
500 buffer {std::move(buffer)} {
501 }
502
503 void write(const std::int16_t *samples, int count) override {
504 buffer->write(samples, count);
505 }
506
507 private:
508 std::shared_ptr<mic_buffer_t> buffer;
509 };
510 } // namespace
511
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();
516 if (!buffer) {
517 BOOST_LOG(warning) << "No session mic ["sv << mic << ']';
518 return nullptr;
519 }
520 return std::make_unique<buffer_mic_writer_t>(std::move(buffer));
521 }
522} // namespace platf::session_audio
Feeds a client's microphone into a session mic.
Definition common.h:557
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...