Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
audio.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <algorithm>
7#include <array>
8#include <condition_variable>
9#include <functional>
10#include <mutex>
11#include <set>
12#include <thread>
13
14// lib includes
15#include <opus/opus_multistream.h>
16
17// local includes
18#include "audio.h"
19#include "config.h"
20#include "globals.h"
21#include "logging.h"
22#include "platform/common.h"
24#include "thread_safe.h"
25#include "utility.h"
26
27namespace audio {
28 using namespace std::literals;
29 using opus_t = util::safe_ptr<OpusMSEncoder, opus_multistream_encoder_destroy>;
30 using sample_queue_t = std::shared_ptr<safe::queue_t<std::vector<float>>>;
31
32 static int start_audio_control(audio_ctx_t &ctx);
33 static void stop_audio_control(audio_ctx_t &);
34 static void apply_surround_params(opus_stream_config_t &stream, const stream_params_t &params);
35
36 int map_stream(int channels, bool quality);
37
38 constexpr auto SAMPLE_RATE = 48000;
39
40 // NOTE: If you adjust the bitrates listed here, make sure to update the
41 // corresponding bitrate adjustment logic in rtsp_stream::cmd_announce()
43 {
44 SAMPLE_RATE,
45 2,
46 1,
47 1,
48 platf::speaker::map_stereo,
49 96000,
50 },
51 {
52 SAMPLE_RATE,
53 2,
54 1,
55 1,
56 platf::speaker::map_stereo,
57 512000,
58 },
59 {
60 SAMPLE_RATE,
61 6,
62 4,
63 2,
64 platf::speaker::map_surround51,
65 256000,
66 },
67 {
68 SAMPLE_RATE,
69 6,
70 6,
71 0,
72 platf::speaker::map_surround51,
73 1536000,
74 },
75 {
76 SAMPLE_RATE,
77 8,
78 5,
79 3,
80 platf::speaker::map_surround71,
81 450000,
82 },
83 {
84 SAMPLE_RATE,
85 8,
86 8,
87 0,
88 platf::speaker::map_surround71,
89 2048000,
90 },
91 };
92
93 void encodeThread(sample_queue_t samples, config_t config, void *channel_data) {
94 auto packets = mail::man->queue<packet_t>(mail::audio_packets);
95 auto stream = stream_configs[map_stream(config.channels, config.flags[config_t::HIGH_QUALITY])];
96 if (config.flags[config_t::CUSTOM_SURROUND_PARAMS]) {
97 apply_surround_params(stream, config.customStreamParams);
98 }
99
100 // Encoding takes place on this thread
101 platf::adjust_thread_priority(platf::thread_priority_e::high);
102
103 opus_t opus {opus_multistream_encoder_create(
104 stream.sampleRate,
105 stream.channelCount,
106 stream.streams,
107 stream.coupledStreams,
108 stream.mapping,
109 OPUS_APPLICATION_RESTRICTED_LOWDELAY,
110 nullptr
111 )};
112
113 opus_multistream_encoder_ctl(opus.get(), OPUS_SET_BITRATE(stream.bitrate));
114 opus_multistream_encoder_ctl(opus.get(), OPUS_SET_VBR(0));
115
116 BOOST_LOG(info) << "Opus initialized: "sv << stream.sampleRate / 1000 << " kHz, "sv
117 << stream.channelCount << " channels, "sv
118 << stream.bitrate / 1000 << " kbps (total), LOWDELAY"sv;
119
120 auto frame_size = config.packetDuration * stream.sampleRate / 1000;
121 while (auto sample = samples->pop()) {
122 buffer_t packet {1400};
123
124 int bytes = opus_multistream_encode_float(opus.get(), sample->data(), frame_size, std::begin(packet), packet.size());
125 if (bytes < 0) {
126 BOOST_LOG(error) << "Couldn't encode audio: "sv << opus_strerror(bytes);
127 packets->stop();
128
129 return;
130 }
131
132 packet.fake_resize(bytes);
133 packets->raise(channel_data, std::move(packet));
134 }
135 }
136
137 void capture(safe::mail_t mail, config_t config, void *channel_data) {
138 auto shutdown_event = mail->event<bool>(mail::shutdown);
139 if (!config::audio.stream || config.input_only) {
140 shutdown_event->view();
141 return;
142 }
143 auto stream = stream_configs[map_stream(config.channels, config.flags[config_t::HIGH_QUALITY])];
144 if (config.flags[config_t::CUSTOM_SURROUND_PARAMS]) {
145 apply_surround_params(stream, config.customStreamParams);
146 }
147
148 auto frame_size = config.packetDuration * stream.sampleRate / 1000;
149 std::function<std::unique_ptr<platf::mic_t>()> open_microphone;
150 audio_ctx_ref_t ref;
151 // The host sink this stream records, when it shares the host's sound server.
152 std::string recorded_sink;
153
154 auto init_failure_fg = util::fail_guard([&shutdown_event]() {
155 BOOST_LOG(error) << "Unable to initialize audio capture. The stream will not have audio."sv;
156
157 // Wait for shutdown to be signalled if we fail init.
158 // This allows streaming to continue without audio.
159 shutdown_event->view();
160 return;
161 });
162
163 // A session with an audio server of its own is recorded there, without the
164 // host's audio control and the virtual sinks it adds to the host's server.
165 if (!config.session_server.empty()) {
166 open_microphone = [&]() {
167 return platf::session_audio::microphone(config.session_server, config.session_sink, stream.mapping, stream.channelCount, stream.sampleRate, frame_size);
168 };
169 }
170
171 if (!open_microphone) {
172 ref = get_audio_ctx_ref();
173 if (!ref || !ref->control) {
174 return;
175 }
176 auto &control = ref->control;
177
178 // A session that owns a sink takes it and considers nothing else. Every
179 // priority below is a sink the whole machine shares, which is the one thing
180 // an isolated session must not record.
181 std::string session_sink = config.session_sink;
182
183 // Order of priority:
184 // 1. Virtual sink
185 // 2. Audio sink
186 // 3. Host
187 std::string *sink = &ref->sink.host;
188 if (!session_sink.empty()) {
189 sink = &session_sink;
190 } else if (!config::audio.sink.empty()) {
191 sink = &config::audio.sink;
192 }
193
194 // Prefer the virtual sink if host playback is disabled or there's no other sink
195 if (session_sink.empty() && ref->sink.null &&
196 (!config.flags[config_t::HOST_AUDIO] || sink->empty())) {
197 auto &null = *ref->sink.null;
198 switch (stream.channelCount) {
199 case 2:
200 sink = &null.stereo;
201 break;
202 case 6:
203 sink = &null.surround51;
204 break;
205 case 8:
206 sink = &null.surround71;
207 break;
208 }
209 }
210
211 BOOST_LOG(info) << "Selected audio sink: "sv << *sink;
212 if (session_sink.empty()) {
213 recorded_sink = *sink;
214 }
215
216 // Only the first to start a session may change the default sink, and an
217 // isolated session is never that one. Moving the host's default is how the
218 // host's own audio is made to reach a stream; doing it for a session that
219 // is somebody else's would put the host - and every other session - into
220 // that client's ears, and take the audio away from whoever was streaming
221 // before.
222 if (session_sink.empty() && !ref->sink_flag->exchange(true, std::memory_order_acquire)) {
223 // If the selected sink is different than the current one, change sinks.
224 ref->restore_sink = ref->sink.host != *sink;
225 if (ref->restore_sink) {
226 if (control->set_sink(*sink)) {
227 return;
228 }
229 }
230 }
231
232 open_microphone = [&]() {
233 return config.session_sink.empty() ?
234 ref->control->microphone(stream.mapping, stream.channelCount, stream.sampleRate, frame_size) :
235 ref->control->microphone_from(config.session_sink, stream.mapping, stream.channelCount, stream.sampleRate, frame_size);
236 };
237 }
238
239 auto mic = open_microphone();
240 if (!mic) {
241 return;
242 }
243
244 // Audio is initialized, so we don't want to print the failure message
245 init_failure_fg.disable();
246
247 // Capture takes place on this thread
248 platf::adjust_thread_priority(platf::thread_priority_e::critical);
249
250 auto samples = std::make_shared<sample_queue_t::element_type>(30);
251 std::thread thread {encodeThread, samples, config, channel_data};
252
253 // An application whose output was chosen for it keeps playing there when
254 // Hermes makes its sink the default, so the client hears nothing from it
255 // and nothing says why. Name each one once per stream.
256 std::thread elsewhere_watch;
257 if (!recorded_sink.empty() && ref && ref->control) {
258 elsewhere_watch = std::thread {[&control = ref->control, recorded_sink, shutdown_event]() {
259 std::set<std::string> reported;
260 while (!shutdown_event->view(5s)) {
261 for (const auto &stream : control->streams_playing_elsewhere(recorded_sink)) {
262 if (reported.insert(stream).second) {
263 BOOST_LOG(warning) << "Audio from "sv << stream << " does not reach the client, which hears "sv << recorded_sink
264 << ". That output was chosen for the application, in the desktop's sound settings or "sv
265 << "remembered by the sound server; set it back to the default output to stream it."sv;
266 }
267 }
268 }
269 }};
270 }
271
272 auto fg = util::fail_guard([&]() {
273 samples->stop();
274 thread.join();
275
276 shutdown_event->view();
277 if (elsewhere_watch.joinable()) {
278 elsewhere_watch.join();
279 }
280 });
281
282 int samples_per_frame = frame_size * stream.channelCount;
283
284 while (!shutdown_event->peek()) {
285 std::vector<float> sample_buffer;
286 sample_buffer.resize(samples_per_frame);
287
288 auto status = mic->sample(sample_buffer);
289 switch (status) {
290 case platf::capture_e::ok:
291 break;
292 case platf::capture_e::timeout:
293 continue;
294 case platf::capture_e::reinit:
295 if (config::audio.auto_capture) {
296 BOOST_LOG(info) << "Reinitializing audio capture"sv;
297 mic.reset();
298 do {
299 mic = open_microphone();
300 if (!mic) {
301 BOOST_LOG(warning) << "Couldn't re-initialize audio input"sv;
302 }
303 } while (!mic && !shutdown_event->view(5s));
304 }
305
306 continue;
307 default:
308 return;
309 }
310
311 samples->raise(std::move(sample_buffer));
312 }
313 }
314
315 audio_ctx_ref_t get_audio_ctx_ref() {
316 static auto control_shared {safe::make_shared<audio_ctx_t>(start_audio_control, stop_audio_control)};
317 return control_shared.ref();
318 }
319
321 if (ctx.sink.host.empty() && config::audio.sink.empty()) {
322 return false;
323 }
324
325 return !is_audio_ctx_sink_available(ctx);
326 }
327
328 namespace {
344 constexpr auto HOST_SINK_WAIT_INTERVAL = 500ms;
345 constexpr int HOST_SINK_WAIT_ATTEMPTS = 20;
346
350 struct host_sink_hold_t {
351 std::mutex mutex;
352
354 std::condition_variable cancelled;
355
357 audio_ctx_ref_t ref;
358
360 std::thread waiter;
361
363 bool releasing {false};
364
365 ~host_sink_hold_t() {
366 {
367 std::lock_guard lock {mutex};
368 releasing = false;
369 }
370 cancelled.notify_all();
371 if (waiter.joinable()) {
372 waiter.join();
373 }
374 }
375 };
376
383 host_sink_hold_t &host_sink_hold() {
384 static host_sink_hold_t hold;
385 return hold;
386 }
387
391 void wait_for_host_sink() {
392 auto &hold = host_sink_hold();
393 std::unique_lock lock {hold.mutex};
394
395 bool waited_out = false;
396 std::string waited_for;
397 for (int attempt = 0; attempt < HOST_SINK_WAIT_ATTEMPTS && hold.releasing; ++attempt) {
398 const auto *ctx = hold.ref ? hold.ref.get() : nullptr;
399 if (!ctx || !host_sink_restore_pending(*ctx)) {
400 break;
401 }
402 waited_out = attempt + 1 == HOST_SINK_WAIT_ATTEMPTS;
403 waited_for = ctx->sink.host.empty() ? config::audio.sink : ctx->sink.host;
404 hold.cancelled.wait_for(lock, HOST_SINK_WAIT_INTERVAL, [&hold]() {
405 return !hold.releasing;
406 });
407 }
408
409 if (waited_out && hold.releasing) {
410 // Unplugged for good, most likely, rather than slow to come back. The
411 // restore below will fail on the name, and dropping the context takes
412 // the virtual sinks with it - at which point the sound server picks a
413 // default of its own, which is the right answer once the device the
414 // user chose is gone.
415 BOOST_LOG(warning) << "Gave up waiting for audio sink ["sv << waited_for
416 << "] to come back; leaving the default where the sound server puts it"sv;
417 }
418
419 if (!hold.releasing) {
420 // A new session took the hold back while we were waiting.
421 return;
422 }
423
424 hold.releasing = false;
425 auto ref = std::move(hold.ref);
426 hold.ref = {};
427 lock.unlock();
428
429 // Dropped outside the lock: the last reference is the one that talks to
430 // the sound server to put the default sink back.
431 ref = {};
432 }
433 } // namespace
434
436 // Take the context first. That constructs its static before the hold's, so
437 // the hold is destroyed first at exit and joins its waiter while the
438 // context is still there to be dropped.
439 auto ref = get_audio_ctx_ref();
440 auto &hold = host_sink_hold();
441
442 std::unique_lock lock {hold.mutex};
443 if (hold.releasing) {
444 // The previous session's release is still waiting for its sink. That
445 // context holds the default recorded before any display went dark, which
446 // is the one this session wants as well - keep it rather than let it go
447 // and read a default that is about to be moved again.
448 hold.releasing = false;
449 lock.unlock();
450 hold.cancelled.notify_all();
451 return;
452 }
453
454 if (!hold.ref) {
455 hold.ref = std::move(ref);
456 lock.unlock();
457 BOOST_LOG(debug) << "Holding the host audio sink across the display change"sv;
458 }
459 }
460
462 auto &hold = host_sink_hold();
463
464 std::thread finished;
465 {
466 std::lock_guard lock {hold.mutex};
467 if (!hold.ref || hold.releasing) {
468 return;
469 }
470
471 hold.releasing = true;
472 // Either never started, or already past its own `releasing = false`, so
473 // joining it below costs nothing.
474 finished = std::move(hold.waiter);
475 hold.waiter = std::thread {wait_for_host_sink};
476 }
477
478 if (finished.joinable()) {
479 finished.join();
480 }
481 }
482
483 bool create_session_sink(const std::string &name, int channels) {
484 auto ref = get_audio_ctx_ref();
485 if (!ref || !ref->control) {
486 return false;
487 }
488
489 // The layout comes from the same table capture uses, so the sink is made
490 // with the channel map that will later be recorded from it. Quality picks
491 // the bitrate and nothing about the layout, so either row will do.
492 const auto &stream = stream_configs[map_stream(channels, false)];
493 return ref->control->create_session_sink(name, stream.mapping, stream.channelCount);
494 }
495
496 void remove_session_sink(const std::string &name) {
497 auto ref = get_audio_ctx_ref();
498 if (!ref || !ref->control) {
499 return;
500 }
501 ref->control->remove_session_sink(name);
502 }
503
504 client_mic_t::client_mic_t(std::unique_ptr<platf::mic_writer_t> writer):
505 writer {std::move(writer)} {
506 int status = OPUS_OK;
507 decoder.reset(opus_decoder_create(SAMPLE_RATE, 1, &status));
508 if (status != OPUS_OK) {
509 decoder.reset();
510 BOOST_LOG(error) << "Couldn't create the client microphone decoder: "sv << opus_strerror(status);
511 }
512 }
513
514 void client_mic_t::write(std::uint16_t sequence, const std::uint8_t *data, std::size_t size) {
515 const int frame = opus_packet_get_nb_samples(data, size, SAMPLE_RATE);
516 if (!decoder || frame <= 0) {
517 return;
518 }
519
520 int lost = 0;
521 if (last_sequence) {
522 const auto gap = static_cast<std::int16_t>(sequence - *last_sequence);
523 if (gap <= 0) {
524 return;
525 }
526 lost = std::min(gap - 1, 5);
527 }
528 last_sequence = sequence;
529
530 // 120 ms, Opus' longest frame.
531 std::array<opus_int16, 5760> pcm;
532 // Conceal all but the last lost frame, which this packet's FEC carries.
533 for (; lost > 0; --lost) {
534 const bool fec = lost == 1;
535 const int samples = opus_decode(decoder.get(), fec ? data : nullptr, fec ? size : 0, pcm.data(), frame, fec);
536 if (samples > 0) {
537 writer->write(pcm.data(), samples);
538 }
539 }
540
541 const int samples = opus_decode(decoder.get(), data, size, pcm.data(), pcm.size(), 0);
542 if (samples > 0) {
543 writer->write(pcm.data(), samples);
544 }
545 }
546
547 std::unique_ptr<client_mic_t> open_client_mic(const std::string &source) {
548 if (auto writer = platf::session_audio::open_mic(source)) {
549 return std::make_unique<client_mic_t>(std::move(writer));
550 }
551 return nullptr;
552 }
553
555 if (!ctx.control) {
556 return false;
557 }
558
559 const std::string &sink = ctx.sink.host.empty() ? config::audio.sink : ctx.sink.host;
560 if (sink.empty()) {
561 return false;
562 }
563
564 return ctx.control->is_sink_available(sink);
565 }
566
567 int map_stream(int channels, bool quality) {
568 int shift = quality ? 1 : 0;
569 switch (channels) {
570 case 2:
571 return STEREO + shift;
572 case 6:
573 return SURROUND51 + shift;
574 case 8:
575 return SURROUND71 + shift;
576 }
577 return STEREO;
578 }
579
580 int start_audio_control(audio_ctx_t &ctx) {
581 auto fg = util::fail_guard([]() {
582 BOOST_LOG(warning) << "There will be no audio"sv;
583 });
584
585 ctx.sink_flag = std::make_unique<std::atomic_bool>(false);
586
587 // The default sink has not been replaced yet.
588 ctx.restore_sink = false;
589
590 if (!(ctx.control = platf::audio_control())) {
591 return 0;
592 }
593
594 auto sink = ctx.control->sink_info();
595 if (!sink) {
596 // Let the calling code know it failed
597 ctx.control.reset();
598 return 0;
599 }
600
601 ctx.sink = std::move(*sink);
602
603 fg.disable();
604 return 0;
605 }
606
607 void stop_audio_control(audio_ctx_t &ctx) {
608 // restore audio-sink if applicable
609 if (!ctx.restore_sink) {
610 return;
611 }
612
613 // Change back to the host sink, unless there was none
614 const std::string &sink = ctx.sink.host.empty() ? config::audio.sink : ctx.sink.host;
615 if (!sink.empty()) {
616 // Best effort, it's allowed to fail
617 ctx.control->set_sink(sink);
618 }
619 }
620
621 void apply_surround_params(opus_stream_config_t &stream, const stream_params_t &params) {
622 stream.channelCount = params.channelCount;
623 stream.streams = params.streams;
624 stream.coupledStreams = params.coupledStreams;
625 stream.mapping = params.mapping;
626 }
627} // namespace audio
bool is_audio_ctx_sink_available(const audio_ctx_t &ctx)
Check if the audio sink held by audio context is available.
Definition audio.cpp:554
bool host_sink_restore_pending(const audio_ctx_t &ctx)
Whether releasing the host sink still has something to wait for.
Definition audio.cpp:320
void release_host_sink()
Let go of a hold_host_sink() hold and restore the sink it recorded.
Definition audio.cpp:461
std::unique_ptr< client_mic_t > open_client_mic(const std::string &source)
nullptr if the session mic cannot be opened.
Definition audio.cpp:547
void hold_host_sink()
Record the host's default sink before a display change can move it.
Definition audio.cpp:435
void remove_session_sink(const std::string &name)
Remove a sink made by create_session_sink(). Removing one that is already gone is not an error.
Definition audio.cpp:496
audio_ctx_ref_t get_audio_ctx_ref()
Get the reference to the audio context.
Definition audio.cpp:315
bool create_session_sink(const std::string &name, int channels)
Create the sink an isolated session records, and its own alone.
Definition audio.cpp:483
Declarations for audio capture and encoding.
@ STEREO
Stereo.
Definition audio.h:21
@ MAX_STREAM_CONFIG
Maximum audio stream configuration.
Definition audio.h:27
void write(std::uint16_t sequence, const std::uint8_t *data, std::size_t size)
Packets older than the last one are dropped; lost ones are concealed.
Definition audio.cpp:514
Declarations for common platform specific utilities.
Declarations for the configuration of Sunshine.
Declarations for globally accessible variables and functions.
Declarations for logging related functions.
safe::mail_t man
A process-wide communication mechanism.
Definition globals.cpp:8
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.
std::unique_ptr< mic_t > microphone(const std::string &pulse_server, const std::string &sink, const std::uint8_t *mapping, int channels, std::uint32_t sample_rate, std::uint32_t frame_size)
Record sink's monitor on the server at pulse_server.
Definition audio.cpp:117
@ HIGH_QUALITY
High quality audio.
Definition audio.h:50
@ CUSTOM_SURROUND_PARAMS
Custom surround parameters.
Definition audio.h:52
@ HOST_AUDIO
Host audio.
Definition audio.h:51
Declarations for thread-safe data structures.
Declarations for utility functions.