8#include <condition_variable>
15#include <opus/opus_multistream.h>
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>>>;
36 int map_stream(
int channels,
bool quality);
38 constexpr auto SAMPLE_RATE = 48000;
48 platf::speaker::map_stereo,
56 platf::speaker::map_stereo,
64 platf::speaker::map_surround51,
72 platf::speaker::map_surround51,
80 platf::speaker::map_surround71,
88 platf::speaker::map_surround71,
93 void encodeThread(sample_queue_t samples,
config_t config,
void *channel_data) {
94 auto packets =
mail::man->queue<packet_t>(mail::audio_packets);
97 apply_surround_params(stream, config.customStreamParams);
101 platf::adjust_thread_priority(platf::thread_priority_e::high);
103 opus_t opus {opus_multistream_encoder_create(
107 stream.coupledStreams,
109 OPUS_APPLICATION_RESTRICTED_LOWDELAY,
113 opus_multistream_encoder_ctl(opus.get(), OPUS_SET_BITRATE(stream.bitrate));
114 opus_multistream_encoder_ctl(opus.get(), OPUS_SET_VBR(0));
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;
120 auto frame_size = config.packetDuration * stream.sampleRate / 1000;
121 while (
auto sample = samples->pop()) {
122 buffer_t packet {1400};
124 int bytes = opus_multistream_encode_float(opus.get(), sample->data(), frame_size, std::begin(packet), packet.size());
126 BOOST_LOG(error) <<
"Couldn't encode audio: "sv << opus_strerror(bytes);
132 packet.fake_resize(bytes);
133 packets->raise(channel_data, std::move(packet));
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();
145 apply_surround_params(stream, config.customStreamParams);
148 auto frame_size = config.packetDuration * stream.sampleRate / 1000;
149 std::function<std::unique_ptr<platf::mic_t>()> open_microphone;
152 std::string recorded_sink;
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;
159 shutdown_event->view();
165 if (!config.session_server.empty()) {
166 open_microphone = [&]() {
171 if (!open_microphone) {
173 if (!ref || !ref->control) {
176 auto &control = ref->control;
181 std::string session_sink = config.session_sink;
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;
195 if (session_sink.empty() && ref->sink.null &&
197 auto &null = *ref->sink.null;
198 switch (stream.channelCount) {
203 sink = &null.surround51;
206 sink = &null.surround71;
211 BOOST_LOG(info) <<
"Selected audio sink: "sv << *sink;
212 if (session_sink.empty()) {
213 recorded_sink = *sink;
222 if (session_sink.empty() && !ref->sink_flag->exchange(
true, std::memory_order_acquire)) {
224 ref->restore_sink = ref->sink.host != *sink;
225 if (ref->restore_sink) {
226 if (control->set_sink(*sink)) {
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);
239 auto mic = open_microphone();
245 init_failure_fg.disable();
248 platf::adjust_thread_priority(platf::thread_priority_e::critical);
250 auto samples = std::make_shared<sample_queue_t::element_type>(30);
251 std::thread thread {encodeThread, samples, config, channel_data};
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;
272 auto fg = util::fail_guard([&]() {
276 shutdown_event->view();
277 if (elsewhere_watch.joinable()) {
278 elsewhere_watch.join();
282 int samples_per_frame = frame_size * stream.channelCount;
284 while (!shutdown_event->peek()) {
285 std::vector<float> sample_buffer;
286 sample_buffer.resize(samples_per_frame);
288 auto status = mic->sample(sample_buffer);
290 case platf::capture_e::ok:
292 case platf::capture_e::timeout:
294 case platf::capture_e::reinit:
295 if (config::audio.auto_capture) {
296 BOOST_LOG(info) <<
"Reinitializing audio capture"sv;
299 mic = open_microphone();
301 BOOST_LOG(warning) <<
"Couldn't re-initialize audio input"sv;
303 }
while (!mic && !shutdown_event->view(5s));
311 samples->raise(std::move(sample_buffer));
316 static auto control_shared {safe::make_shared<audio_ctx_t>(start_audio_control, stop_audio_control)};
317 return control_shared.ref();
321 if (ctx.sink.host.empty() && config::audio.sink.empty()) {
344 constexpr auto HOST_SINK_WAIT_INTERVAL = 500ms;
345 constexpr int HOST_SINK_WAIT_ATTEMPTS = 20;
350 struct host_sink_hold_t {
354 std::condition_variable cancelled;
363 bool releasing {
false};
365 ~host_sink_hold_t() {
367 std::lock_guard lock {mutex};
370 cancelled.notify_all();
371 if (waiter.joinable()) {
383 host_sink_hold_t &host_sink_hold() {
384 static host_sink_hold_t hold;
391 void wait_for_host_sink() {
392 auto &hold = host_sink_hold();
393 std::unique_lock lock {hold.mutex};
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;
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;
409 if (waited_out && hold.releasing) {
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;
419 if (!hold.releasing) {
424 hold.releasing =
false;
425 auto ref = std::move(hold.ref);
440 auto &hold = host_sink_hold();
442 std::unique_lock lock {hold.mutex};
443 if (hold.releasing) {
448 hold.releasing =
false;
450 hold.cancelled.notify_all();
455 hold.ref = std::move(ref);
457 BOOST_LOG(debug) <<
"Holding the host audio sink across the display change"sv;
462 auto &hold = host_sink_hold();
464 std::thread finished;
466 std::lock_guard lock {hold.mutex};
467 if (!hold.ref || hold.releasing) {
471 hold.releasing =
true;
474 finished = std::move(hold.waiter);
475 hold.waiter = std::thread {wait_for_host_sink};
478 if (finished.joinable()) {
485 if (!ref || !ref->control) {
492 const auto &stream = stream_configs[map_stream(channels,
false)];
493 return ref->control->create_session_sink(name, stream.mapping, stream.channelCount);
498 if (!ref || !ref->control) {
501 ref->control->remove_session_sink(name);
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) {
510 BOOST_LOG(error) <<
"Couldn't create the client microphone decoder: "sv << opus_strerror(status);
515 const int frame = opus_packet_get_nb_samples(data, size, SAMPLE_RATE);
516 if (!decoder || frame <= 0) {
522 const auto gap =
static_cast<std::int16_t
>(sequence - *last_sequence);
526 lost = std::min(gap - 1, 5);
528 last_sequence = sequence;
531 std::array<opus_int16, 5760> pcm;
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);
537 writer->write(pcm.data(), samples);
541 const int samples = opus_decode(decoder.get(), data, size, pcm.data(), pcm.size(), 0);
543 writer->write(pcm.data(), samples);
549 return std::make_unique<client_mic_t>(std::move(writer));
559 const std::string &sink = ctx.sink.host.empty() ? config::audio.sink : ctx.sink.host;
564 return ctx.control->is_sink_available(sink);
567 int map_stream(
int channels,
bool quality) {
568 int shift = quality ? 1 : 0;
571 return STEREO + shift;
573 return SURROUND51 + shift;
575 return SURROUND71 + shift;
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;
585 ctx.sink_flag = std::make_unique<std::atomic_bool>(
false);
588 ctx.restore_sink =
false;
590 if (!(ctx.control = platf::audio_control())) {
594 auto sink = ctx.control->sink_info();
601 ctx.sink = std::move(*sink);
607 void stop_audio_control(audio_ctx_t &ctx) {
609 if (!ctx.restore_sink) {
614 const std::string &sink = ctx.sink.host.empty() ? config::audio.sink : ctx.sink.host;
617 ctx.control->set_sink(sink);
621 void apply_surround_params(opus_stream_config_t &stream,
const stream_params_t ¶ms) {
622 stream.channelCount = params.channelCount;
623 stream.streams = params.streams;
624 stream.coupledStreams = params.coupledStreams;
625 stream.mapping = params.mapping;
bool is_audio_ctx_sink_available(const audio_ctx_t &ctx)
Check if the audio sink held by audio context is available.
bool host_sink_restore_pending(const audio_ctx_t &ctx)
Whether releasing the host sink still has something to wait for.
void release_host_sink()
Let go of a hold_host_sink() hold and restore the sink it recorded.
std::unique_ptr< client_mic_t > open_client_mic(const std::string &source)
nullptr if the session mic cannot be opened.
void hold_host_sink()
Record the host's default sink before a display change can move it.
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.
audio_ctx_ref_t get_audio_ctx_ref()
Get the reference to the audio context.
bool create_session_sink(const std::string &name, int channels)
Create the sink an isolated session records, and its own alone.
Declarations for audio capture and encoding.
@ MAX_STREAM_CONFIG
Maximum audio stream configuration.
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.
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.
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.
@ HIGH_QUALITY
High quality audio.
@ CUSTOM_SURROUND_PARAMS
Custom surround parameters.
Declarations for thread-safe data structures.
Declarations for utility functions.