Make sure struct members are initialized
[openal-soft.git] / alc / backends / pulseaudio.cpp
blobd76223d2bd5a274560fe973c7c49f5e7dba6019f
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 2009 by Konstantinos Natsakis <konstantinos.natsakis@gmail.com>
4 * Copyright (C) 2010 by Chris Robinson <chris.kcat@gmail.com>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 * Or go to http://www.gnu.org/copyleft/lgpl.html
22 #include "config.h"
24 #include "pulseaudio.h"
26 #include <algorithm>
27 #include <array>
28 #include <atomic>
29 #include <bitset>
30 #include <chrono>
31 #include <cstdint>
32 #include <cstdlib>
33 #include <cstring>
34 #include <limits>
35 #include <mutex>
36 #include <optional>
37 #include <string>
38 #include <sys/types.h>
39 #include <utility>
40 #include <vector>
42 #include "albit.h"
43 #include "alc/alconfig.h"
44 #include "almalloc.h"
45 #include "alnumeric.h"
46 #include "alspan.h"
47 #include "alstring.h"
48 #include "core/devformat.h"
49 #include "core/device.h"
50 #include "core/logging.h"
51 #include "dynload.h"
52 #include "opthelpers.h"
53 #include "strutils.h"
55 #include <pulse/pulseaudio.h>
58 namespace {
60 using uint = unsigned int;
62 #ifdef HAVE_DYNLOAD
63 #define PULSE_FUNCS(MAGIC) \
64 MAGIC(pa_context_new); \
65 MAGIC(pa_context_unref); \
66 MAGIC(pa_context_get_state); \
67 MAGIC(pa_context_disconnect); \
68 MAGIC(pa_context_set_state_callback); \
69 MAGIC(pa_context_set_subscribe_callback); \
70 MAGIC(pa_context_subscribe); \
71 MAGIC(pa_context_errno); \
72 MAGIC(pa_context_connect); \
73 MAGIC(pa_context_get_server_info); \
74 MAGIC(pa_context_get_sink_info_by_name); \
75 MAGIC(pa_context_get_sink_info_list); \
76 MAGIC(pa_context_get_source_info_by_name); \
77 MAGIC(pa_context_get_source_info_list); \
78 MAGIC(pa_stream_new); \
79 MAGIC(pa_stream_unref); \
80 MAGIC(pa_stream_drop); \
81 MAGIC(pa_stream_get_state); \
82 MAGIC(pa_stream_peek); \
83 MAGIC(pa_stream_write); \
84 MAGIC(pa_stream_connect_record); \
85 MAGIC(pa_stream_connect_playback); \
86 MAGIC(pa_stream_readable_size); \
87 MAGIC(pa_stream_writable_size); \
88 MAGIC(pa_stream_is_corked); \
89 MAGIC(pa_stream_cork); \
90 MAGIC(pa_stream_is_suspended); \
91 MAGIC(pa_stream_get_device_name); \
92 MAGIC(pa_stream_get_latency); \
93 MAGIC(pa_stream_set_write_callback); \
94 MAGIC(pa_stream_set_buffer_attr); \
95 MAGIC(pa_stream_get_buffer_attr); \
96 MAGIC(pa_stream_get_sample_spec); \
97 MAGIC(pa_stream_get_time); \
98 MAGIC(pa_stream_set_read_callback); \
99 MAGIC(pa_stream_set_state_callback); \
100 MAGIC(pa_stream_set_moved_callback); \
101 MAGIC(pa_stream_set_underflow_callback); \
102 MAGIC(pa_stream_new_with_proplist); \
103 MAGIC(pa_stream_disconnect); \
104 MAGIC(pa_stream_set_buffer_attr_callback); \
105 MAGIC(pa_stream_begin_write); \
106 MAGIC(pa_threaded_mainloop_free); \
107 MAGIC(pa_threaded_mainloop_get_api); \
108 MAGIC(pa_threaded_mainloop_lock); \
109 MAGIC(pa_threaded_mainloop_new); \
110 MAGIC(pa_threaded_mainloop_signal); \
111 MAGIC(pa_threaded_mainloop_start); \
112 MAGIC(pa_threaded_mainloop_stop); \
113 MAGIC(pa_threaded_mainloop_unlock); \
114 MAGIC(pa_threaded_mainloop_wait); \
115 MAGIC(pa_channel_map_init_auto); \
116 MAGIC(pa_channel_map_parse); \
117 MAGIC(pa_channel_map_snprint); \
118 MAGIC(pa_channel_map_equal); \
119 MAGIC(pa_channel_map_superset); \
120 MAGIC(pa_channel_position_to_string); \
121 MAGIC(pa_operation_get_state); \
122 MAGIC(pa_operation_unref); \
123 MAGIC(pa_sample_spec_valid); \
124 MAGIC(pa_frame_size); \
125 MAGIC(pa_strerror); \
126 MAGIC(pa_path_get_filename); \
127 MAGIC(pa_get_binary_name); \
128 MAGIC(pa_xmalloc); \
129 MAGIC(pa_xfree);
131 void *pulse_handle;
132 #define MAKE_FUNC(x) decltype(x) * p##x
133 PULSE_FUNCS(MAKE_FUNC)
134 #undef MAKE_FUNC
136 #ifndef IN_IDE_PARSER
137 #define pa_context_new ppa_context_new
138 #define pa_context_unref ppa_context_unref
139 #define pa_context_get_state ppa_context_get_state
140 #define pa_context_disconnect ppa_context_disconnect
141 #define pa_context_set_state_callback ppa_context_set_state_callback
142 #define pa_context_set_subscribe_callback ppa_context_set_subscribe_callback
143 #define pa_context_subscribe ppa_context_subscribe
144 #define pa_context_errno ppa_context_errno
145 #define pa_context_connect ppa_context_connect
146 #define pa_context_get_server_info ppa_context_get_server_info
147 #define pa_context_get_sink_info_by_name ppa_context_get_sink_info_by_name
148 #define pa_context_get_sink_info_list ppa_context_get_sink_info_list
149 #define pa_context_get_source_info_by_name ppa_context_get_source_info_by_name
150 #define pa_context_get_source_info_list ppa_context_get_source_info_list
151 #define pa_stream_new ppa_stream_new
152 #define pa_stream_unref ppa_stream_unref
153 #define pa_stream_disconnect ppa_stream_disconnect
154 #define pa_stream_drop ppa_stream_drop
155 #define pa_stream_set_write_callback ppa_stream_set_write_callback
156 #define pa_stream_set_buffer_attr ppa_stream_set_buffer_attr
157 #define pa_stream_get_buffer_attr ppa_stream_get_buffer_attr
158 #define pa_stream_get_sample_spec ppa_stream_get_sample_spec
159 #define pa_stream_get_time ppa_stream_get_time
160 #define pa_stream_set_read_callback ppa_stream_set_read_callback
161 #define pa_stream_set_state_callback ppa_stream_set_state_callback
162 #define pa_stream_set_moved_callback ppa_stream_set_moved_callback
163 #define pa_stream_set_underflow_callback ppa_stream_set_underflow_callback
164 #define pa_stream_connect_record ppa_stream_connect_record
165 #define pa_stream_connect_playback ppa_stream_connect_playback
166 #define pa_stream_readable_size ppa_stream_readable_size
167 #define pa_stream_writable_size ppa_stream_writable_size
168 #define pa_stream_is_corked ppa_stream_is_corked
169 #define pa_stream_cork ppa_stream_cork
170 #define pa_stream_is_suspended ppa_stream_is_suspended
171 #define pa_stream_get_device_name ppa_stream_get_device_name
172 #define pa_stream_get_latency ppa_stream_get_latency
173 #define pa_stream_set_buffer_attr_callback ppa_stream_set_buffer_attr_callback
174 #define pa_stream_begin_write ppa_stream_begin_write
175 #define pa_threaded_mainloop_free ppa_threaded_mainloop_free
176 #define pa_threaded_mainloop_get_api ppa_threaded_mainloop_get_api
177 #define pa_threaded_mainloop_lock ppa_threaded_mainloop_lock
178 #define pa_threaded_mainloop_new ppa_threaded_mainloop_new
179 #define pa_threaded_mainloop_signal ppa_threaded_mainloop_signal
180 #define pa_threaded_mainloop_start ppa_threaded_mainloop_start
181 #define pa_threaded_mainloop_stop ppa_threaded_mainloop_stop
182 #define pa_threaded_mainloop_unlock ppa_threaded_mainloop_unlock
183 #define pa_threaded_mainloop_wait ppa_threaded_mainloop_wait
184 #define pa_channel_map_init_auto ppa_channel_map_init_auto
185 #define pa_channel_map_parse ppa_channel_map_parse
186 #define pa_channel_map_snprint ppa_channel_map_snprint
187 #define pa_channel_map_equal ppa_channel_map_equal
188 #define pa_channel_map_superset ppa_channel_map_superset
189 #define pa_channel_position_to_string ppa_channel_position_to_string
190 #define pa_operation_get_state ppa_operation_get_state
191 #define pa_operation_unref ppa_operation_unref
192 #define pa_sample_spec_valid ppa_sample_spec_valid
193 #define pa_frame_size ppa_frame_size
194 #define pa_strerror ppa_strerror
195 #define pa_stream_get_state ppa_stream_get_state
196 #define pa_stream_peek ppa_stream_peek
197 #define pa_stream_write ppa_stream_write
198 #define pa_xfree ppa_xfree
199 #define pa_path_get_filename ppa_path_get_filename
200 #define pa_get_binary_name ppa_get_binary_name
201 #define pa_xmalloc ppa_xmalloc
202 #endif /* IN_IDE_PARSER */
204 #endif
207 constexpr pa_channel_map MonoChanMap{
208 1, {PA_CHANNEL_POSITION_MONO}
209 }, StereoChanMap{
210 2, {PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT}
211 }, QuadChanMap{
212 4, {
213 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
214 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
216 }, X51ChanMap{
217 6, {
218 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
219 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
220 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
222 }, X51RearChanMap{
223 6, {
224 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
225 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
226 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
228 }, X61ChanMap{
229 7, {
230 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
231 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
232 PA_CHANNEL_POSITION_REAR_CENTER,
233 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
235 }, X71ChanMap{
236 8, {
237 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
238 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
239 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
240 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
242 }, X714ChanMap{
243 12, {
244 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
245 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
246 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
247 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT,
248 PA_CHANNEL_POSITION_TOP_FRONT_LEFT, PA_CHANNEL_POSITION_TOP_FRONT_RIGHT,
249 PA_CHANNEL_POSITION_TOP_REAR_LEFT, PA_CHANNEL_POSITION_TOP_REAR_RIGHT
254 /* *grumble* Don't use enums for bitflags. */
255 constexpr pa_stream_flags_t operator|(pa_stream_flags_t lhs, pa_stream_flags_t rhs)
256 { return pa_stream_flags_t(lhs | al::to_underlying(rhs)); }
257 constexpr pa_stream_flags_t& operator|=(pa_stream_flags_t &lhs, pa_stream_flags_t rhs)
259 lhs = lhs | rhs;
260 return lhs;
262 constexpr pa_stream_flags_t operator~(pa_stream_flags_t flag)
263 { return pa_stream_flags_t(~al::to_underlying(flag)); }
264 constexpr pa_stream_flags_t& operator&=(pa_stream_flags_t &lhs, pa_stream_flags_t rhs)
266 lhs = pa_stream_flags_t(al::to_underlying(lhs) & rhs);
267 return lhs;
270 constexpr pa_context_flags_t operator|(pa_context_flags_t lhs, pa_context_flags_t rhs)
271 { return pa_context_flags_t(lhs | al::to_underlying(rhs)); }
272 constexpr pa_context_flags_t& operator|=(pa_context_flags_t &lhs, pa_context_flags_t rhs)
274 lhs = lhs | rhs;
275 return lhs;
278 constexpr pa_subscription_mask_t operator|(pa_subscription_mask_t lhs, pa_subscription_mask_t rhs)
279 { return pa_subscription_mask_t(lhs | al::to_underlying(rhs)); }
282 struct DevMap {
283 std::string name;
284 std::string device_name;
287 bool checkName(const al::span<const DevMap> list, const std::string &name)
289 auto match_name = [&name](const DevMap &entry) -> bool { return entry.name == name; };
290 return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
293 std::vector<DevMap> PlaybackDevices;
294 std::vector<DevMap> CaptureDevices;
297 /* Global flags and properties */
298 pa_context_flags_t pulse_ctx_flags;
300 class PulseMainloop {
301 pa_threaded_mainloop *mLoop{};
302 pa_context *mContext{};
304 public:
305 PulseMainloop() = default;
306 PulseMainloop(const PulseMainloop&) = delete;
307 PulseMainloop(PulseMainloop&& rhs) noexcept : mLoop{rhs.mLoop} { rhs.mLoop = nullptr; }
308 explicit PulseMainloop(pa_threaded_mainloop *loop) noexcept : mLoop{loop} { }
309 ~PulseMainloop();
311 PulseMainloop& operator=(const PulseMainloop&) = delete;
312 PulseMainloop& operator=(PulseMainloop&& rhs) noexcept
313 { std::swap(mLoop, rhs.mLoop); return *this; }
314 PulseMainloop& operator=(std::nullptr_t) noexcept
316 if(mLoop)
317 pa_threaded_mainloop_free(mLoop);
318 mLoop = nullptr;
319 return *this;
322 explicit operator bool() const noexcept { return mLoop != nullptr; }
324 [[nodiscard]]
325 auto start() const { return pa_threaded_mainloop_start(mLoop); }
326 auto stop() const { return pa_threaded_mainloop_stop(mLoop); }
328 [[nodiscard]] auto getApi() const { return pa_threaded_mainloop_get_api(mLoop); }
329 [[nodiscard]] auto getContext() const noexcept { return mContext; }
331 auto lock() const { return pa_threaded_mainloop_lock(mLoop); }
332 auto unlock() const { return pa_threaded_mainloop_unlock(mLoop); }
334 auto signal(bool wait=false) const { return pa_threaded_mainloop_signal(mLoop, wait); }
336 static auto Create() { return PulseMainloop{pa_threaded_mainloop_new()}; }
339 void streamSuccessCallback(pa_stream*, int) const noexcept { signal(); }
340 static void streamSuccessCallbackC(pa_stream *stream, int success, void *pdata) noexcept
341 { static_cast<PulseMainloop*>(pdata)->streamSuccessCallback(stream, success); }
343 void close(pa_stream *stream=nullptr);
346 void deviceSinkCallback(pa_context*, const pa_sink_info *info, int eol) const noexcept
348 if(eol)
350 signal();
351 return;
354 /* Skip this device is if it's already in the list. */
355 auto match_devname = [info](const DevMap &entry) -> bool
356 { return entry.device_name == info->name; };
357 if(std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), match_devname) != PlaybackDevices.cend())
358 return;
360 /* Make sure the display name (description) is unique. Append a number
361 * counter as needed.
363 int count{1};
364 std::string newname{info->description};
365 while(checkName(PlaybackDevices, newname))
367 newname = info->description;
368 newname += " #";
369 newname += std::to_string(++count);
371 PlaybackDevices.emplace_back(DevMap{std::move(newname), info->name});
372 DevMap &newentry = PlaybackDevices.back();
374 TRACE("Got device \"%s\", \"%s\"\n", newentry.name.c_str(), newentry.device_name.c_str());
377 void deviceSourceCallback(pa_context*, const pa_source_info *info, int eol) const noexcept
379 if(eol)
381 signal();
382 return;
385 /* Skip this device is if it's already in the list. */
386 auto match_devname = [info](const DevMap &entry) -> bool
387 { return entry.device_name == info->name; };
388 if(std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), match_devname) != CaptureDevices.cend())
389 return;
391 /* Make sure the display name (description) is unique. Append a number
392 * counter as needed.
394 int count{1};
395 std::string newname{info->description};
396 while(checkName(CaptureDevices, newname))
398 newname = info->description;
399 newname += " #";
400 newname += std::to_string(++count);
402 CaptureDevices.emplace_back(DevMap{std::move(newname), info->name});
403 DevMap &newentry = CaptureDevices.back();
405 TRACE("Got device \"%s\", \"%s\"\n", newentry.name.c_str(), newentry.device_name.c_str());
408 void probePlaybackDevices();
409 void probeCaptureDevices();
411 friend struct MainloopUniqueLock;
413 struct MainloopUniqueLock : public std::unique_lock<PulseMainloop> {
414 using std::unique_lock<PulseMainloop>::unique_lock;
415 MainloopUniqueLock& operator=(MainloopUniqueLock&&) = default;
417 auto wait() const -> void
418 { pa_threaded_mainloop_wait(mutex()->mLoop); }
420 template<typename Predicate>
421 auto wait(Predicate done_waiting) const -> void
422 { while(!done_waiting()) wait(); }
424 void waitForOperation(pa_operation *op) const
426 if(op)
428 wait([op]{ return pa_operation_get_state(op) != PA_OPERATION_RUNNING; });
429 pa_operation_unref(op);
434 void setEventHandler()
436 pa_operation *op{pa_context_subscribe(mutex()->mContext,
437 PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SOURCE,
438 [](pa_context*, int, void *pdata) noexcept
439 { static_cast<PulseMainloop*>(pdata)->signal(); },
440 mutex())};
441 waitForOperation(op);
443 /* Watch for device added/removed events.
445 * TODO: Also track the "default" device, in as much as PulseAudio has
446 * the concept of a default device (whatever device is opened when not
447 * specifying a specific sink or source name). There doesn't seem to be
448 * an event for this.
450 auto handler = [](pa_context*, pa_subscription_event_type_t t, uint32_t, void*) noexcept
452 const auto eventFacility = (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK);
453 if(eventFacility == PA_SUBSCRIPTION_EVENT_SINK
454 || eventFacility == PA_SUBSCRIPTION_EVENT_SOURCE)
456 const auto deviceType = (eventFacility == PA_SUBSCRIPTION_EVENT_SINK)
457 ? alc::DeviceType::Playback : alc::DeviceType::Capture;
458 const auto eventType = (t & PA_SUBSCRIPTION_EVENT_TYPE_MASK);
459 if(eventType == PA_SUBSCRIPTION_EVENT_NEW)
460 alc::Event(alc::EventType::DeviceAdded, deviceType, "Device added");
461 else if(eventType == PA_SUBSCRIPTION_EVENT_REMOVE)
462 alc::Event(alc::EventType::DeviceRemoved, deviceType, "Device removed");
465 pa_context_set_subscribe_callback(mutex()->mContext, handler, nullptr);
469 void contextStateCallback(pa_context *context) noexcept
471 pa_context_state_t state{pa_context_get_state(context)};
472 if(state == PA_CONTEXT_READY || !PA_CONTEXT_IS_GOOD(state))
473 mutex()->signal();
476 void streamStateCallback(pa_stream *stream) noexcept
478 pa_stream_state_t state{pa_stream_get_state(stream)};
479 if(state == PA_STREAM_READY || !PA_STREAM_IS_GOOD(state))
480 mutex()->signal();
483 void connectContext();
484 pa_stream *connectStream(const char *device_name, pa_stream_flags_t flags,
485 pa_buffer_attr *attr, pa_sample_spec *spec, pa_channel_map *chanmap, BackendType type);
487 using MainloopLockGuard = std::lock_guard<PulseMainloop>;
489 PulseMainloop::~PulseMainloop()
491 if(mContext)
493 MainloopUniqueLock looplock{*this};
494 pa_context_disconnect(mContext);
495 pa_context_unref(mContext);
497 if(mLoop)
498 pa_threaded_mainloop_free(mLoop);
502 void MainloopUniqueLock::connectContext()
504 if(mutex()->mContext)
505 return;
507 mutex()->mContext = pa_context_new(mutex()->getApi(), nullptr);
508 if(!mutex()->mContext) throw al::backend_exception{al::backend_error::OutOfMemory,
509 "pa_context_new() failed"};
511 pa_context_set_state_callback(mutex()->mContext, [](pa_context *ctx, void *pdata) noexcept
512 { return static_cast<MainloopUniqueLock*>(pdata)->contextStateCallback(ctx); }, this);
514 int err{pa_context_connect(mutex()->mContext, nullptr, pulse_ctx_flags, nullptr)};
515 if(err >= 0)
517 wait([&err,this]()
519 pa_context_state_t state{pa_context_get_state(mutex()->mContext)};
520 if(!PA_CONTEXT_IS_GOOD(state))
522 err = pa_context_errno(mutex()->mContext);
523 if(err > 0) err = -err;
524 return true;
526 return state == PA_CONTEXT_READY;
529 pa_context_set_state_callback(mutex()->mContext, nullptr, nullptr);
531 if(err < 0)
533 pa_context_unref(mutex()->mContext);
534 mutex()->mContext = nullptr;
535 throw al::backend_exception{al::backend_error::DeviceError, "Context did not connect (%s)",
536 pa_strerror(err)};
540 pa_stream *MainloopUniqueLock::connectStream(const char *device_name, pa_stream_flags_t flags,
541 pa_buffer_attr *attr, pa_sample_spec *spec, pa_channel_map *chanmap, BackendType type)
543 const char *stream_id{(type==BackendType::Playback) ? "Playback Stream" : "Capture Stream"};
544 pa_stream *stream{pa_stream_new(mutex()->mContext, stream_id, spec, chanmap)};
545 if(!stream)
546 throw al::backend_exception{al::backend_error::OutOfMemory, "pa_stream_new() failed (%s)",
547 pa_strerror(pa_context_errno(mutex()->mContext))};
549 pa_stream_set_state_callback(stream, [](pa_stream *strm, void *pdata) noexcept
550 { return static_cast<MainloopUniqueLock*>(pdata)->streamStateCallback(strm); }, this);
552 int err{(type==BackendType::Playback) ?
553 pa_stream_connect_playback(stream, device_name, attr, flags, nullptr, nullptr) :
554 pa_stream_connect_record(stream, device_name, attr, flags)};
555 if(err < 0)
557 pa_stream_unref(stream);
558 throw al::backend_exception{al::backend_error::DeviceError, "%s did not connect (%s)",
559 stream_id, pa_strerror(err)};
562 wait([&err,stream,stream_id,this]()
564 pa_stream_state_t state{pa_stream_get_state(stream)};
565 if(!PA_STREAM_IS_GOOD(state))
567 err = pa_context_errno(mutex()->mContext);
568 pa_stream_unref(stream);
569 throw al::backend_exception{al::backend_error::DeviceError,
570 "%s did not get ready (%s)", stream_id, pa_strerror(err)};
572 return state == PA_STREAM_READY;
575 pa_stream_set_state_callback(stream, nullptr, nullptr);
577 return stream;
580 void PulseMainloop::close(pa_stream *stream)
582 if(!stream)
583 return;
585 MainloopUniqueLock looplock{*this};
586 pa_stream_set_state_callback(stream, nullptr, nullptr);
587 pa_stream_set_moved_callback(stream, nullptr, nullptr);
588 pa_stream_set_write_callback(stream, nullptr, nullptr);
589 pa_stream_set_buffer_attr_callback(stream, nullptr, nullptr);
590 pa_stream_disconnect(stream);
591 pa_stream_unref(stream);
595 void PulseMainloop::probePlaybackDevices()
597 PlaybackDevices.clear();
598 try {
599 MainloopUniqueLock plock{*this};
600 plock.connectContext();
602 auto sink_callback = [](pa_context *ctx, const pa_sink_info *info, int eol, void *pdata) noexcept
603 { return static_cast<PulseMainloop*>(pdata)->deviceSinkCallback(ctx, info, eol); };
605 pa_operation *op{pa_context_get_sink_info_by_name(mContext, nullptr, sink_callback, this)};
606 plock.waitForOperation(op);
608 op = pa_context_get_sink_info_list(mContext, sink_callback, this);
609 plock.waitForOperation(op);
611 catch(std::exception &e) {
612 ERR("Error enumerating devices: %s\n", e.what());
616 void PulseMainloop::probeCaptureDevices()
618 CaptureDevices.clear();
619 try {
620 MainloopUniqueLock plock{*this};
621 plock.connectContext();
623 auto src_callback = [](pa_context *ctx, const pa_source_info *info, int eol, void *pdata) noexcept
624 { return static_cast<PulseMainloop*>(pdata)->deviceSourceCallback(ctx, info, eol); };
626 pa_operation *op{pa_context_get_source_info_by_name(mContext, nullptr, src_callback,
627 this)};
628 plock.waitForOperation(op);
630 op = pa_context_get_source_info_list(mContext, src_callback, this);
631 plock.waitForOperation(op);
633 catch(std::exception &e) {
634 ERR("Error enumerating devices: %s\n", e.what());
639 /* Used for initial connection test and enumeration. */
640 PulseMainloop gGlobalMainloop;
643 struct PulsePlayback final : public BackendBase {
644 PulsePlayback(DeviceBase *device) noexcept : BackendBase{device} { }
645 ~PulsePlayback() override;
647 void bufferAttrCallback(pa_stream *stream) noexcept;
648 void streamStateCallback(pa_stream *stream) noexcept;
649 void streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept;
650 void sinkInfoCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept;
651 void sinkNameCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept;
652 void streamMovedCallback(pa_stream *stream) noexcept;
654 void open(std::string_view name) override;
655 bool reset() override;
656 void start() override;
657 void stop() override;
658 ClockLatency getClockLatency() override;
660 PulseMainloop mMainloop;
662 std::optional<std::string> mDeviceName{std::nullopt};
664 bool mIs51Rear{false};
665 pa_buffer_attr mAttr{};
666 pa_sample_spec mSpec{};
668 pa_stream *mStream{nullptr};
670 uint mFrameSize{0u};
673 PulsePlayback::~PulsePlayback()
674 { if(mStream) mMainloop.close(mStream); }
677 void PulsePlayback::bufferAttrCallback(pa_stream *stream) noexcept
679 /* FIXME: Update the device's UpdateSize (and/or BufferSize) using the new
680 * buffer attributes? Changing UpdateSize will change the ALC_REFRESH
681 * property, which probably shouldn't change between device resets. But
682 * leaving it alone means ALC_REFRESH will be off.
684 mAttr = *(pa_stream_get_buffer_attr(stream));
685 TRACE("minreq=%d, tlength=%d, prebuf=%d\n", mAttr.minreq, mAttr.tlength, mAttr.prebuf);
688 void PulsePlayback::streamStateCallback(pa_stream *stream) noexcept
690 if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
692 ERR("Received stream failure!\n");
693 mDevice->handleDisconnect("Playback stream failure");
695 mMainloop.signal();
698 void PulsePlayback::streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept
700 do {
701 pa_free_cb_t free_func{nullptr};
702 auto buflen = static_cast<size_t>(-1);
703 void *buf{};
704 if(pa_stream_begin_write(stream, &buf, &buflen) || !buf) UNLIKELY
706 buflen = nbytes;
707 buf = pa_xmalloc(buflen);
708 free_func = pa_xfree;
710 else
711 buflen = std::min(buflen, nbytes);
712 nbytes -= buflen;
714 mDevice->renderSamples(buf, static_cast<uint>(buflen/mFrameSize), mSpec.channels);
716 int ret{pa_stream_write(stream, buf, buflen, free_func, 0, PA_SEEK_RELATIVE)};
717 if(ret != PA_OK) UNLIKELY
718 ERR("Failed to write to stream: %d, %s\n", ret, pa_strerror(ret));
719 } while(nbytes > 0);
722 void PulsePlayback::sinkInfoCallback(pa_context*, const pa_sink_info *info, int eol) noexcept
724 struct ChannelMap {
725 DevFmtChannels fmt;
726 pa_channel_map map;
727 bool is_51rear;
729 static constexpr std::array<ChannelMap,8> chanmaps{{
730 { DevFmtX714, X714ChanMap, false },
731 { DevFmtX71, X71ChanMap, false },
732 { DevFmtX61, X61ChanMap, false },
733 { DevFmtX51, X51ChanMap, false },
734 { DevFmtX51, X51RearChanMap, true },
735 { DevFmtQuad, QuadChanMap, false },
736 { DevFmtStereo, StereoChanMap, false },
737 { DevFmtMono, MonoChanMap, false }
740 if(eol)
742 mMainloop.signal();
743 return;
746 auto chaniter = std::find_if(chanmaps.cbegin(), chanmaps.cend(),
747 [info](const ChannelMap &chanmap) -> bool
748 { return pa_channel_map_superset(&info->channel_map, &chanmap.map); }
750 if(chaniter != chanmaps.cend())
752 if(!mDevice->Flags.test(ChannelsRequest))
753 mDevice->FmtChans = chaniter->fmt;
754 mIs51Rear = chaniter->is_51rear;
756 else
758 mIs51Rear = false;
759 std::array<char,PA_CHANNEL_MAP_SNPRINT_MAX> chanmap_str{};
760 pa_channel_map_snprint(chanmap_str.data(), chanmap_str.size(), &info->channel_map);
761 WARN("Failed to find format for channel map:\n %s\n", chanmap_str.data());
764 if(info->active_port)
765 TRACE("Active port: %s (%s)\n", info->active_port->name, info->active_port->description);
766 mDevice->Flags.set(DirectEar, (info->active_port
767 && strcmp(info->active_port->name, "analog-output-headphones") == 0));
770 void PulsePlayback::sinkNameCallback(pa_context*, const pa_sink_info *info, int eol) noexcept
772 if(eol)
774 mMainloop.signal();
775 return;
777 mDevice->DeviceName = info->description;
780 void PulsePlayback::streamMovedCallback(pa_stream *stream) noexcept
782 mDeviceName = pa_stream_get_device_name(stream);
783 TRACE("Stream moved to %s\n", mDeviceName->c_str());
787 void PulsePlayback::open(std::string_view name)
789 mMainloop = PulseMainloop::Create();
790 if(mMainloop.start() != 0)
791 throw al::backend_exception{al::backend_error::DeviceError,
792 "Failed to start device mainloop"};
794 const char *pulse_name{nullptr};
795 std::string_view display_name;
796 if(!name.empty())
798 if(PlaybackDevices.empty())
799 mMainloop.probePlaybackDevices();
801 auto match_name = [name](const DevMap &entry) -> bool
802 { return entry.name == name || entry.device_name == name; };
803 auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), match_name);
804 if(iter == PlaybackDevices.cend())
805 throw al::backend_exception{al::backend_error::NoDevice,
806 "Device name \"%.*s\" not found", al::sizei(name), name.data()};
807 pulse_name = iter->device_name.c_str();
808 display_name = iter->name;
811 MainloopUniqueLock plock{mMainloop};
812 plock.connectContext();
814 pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_FIX_FORMAT | PA_STREAM_FIX_RATE |
815 PA_STREAM_FIX_CHANNELS};
816 if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
817 flags |= PA_STREAM_DONT_MOVE;
819 pa_sample_spec spec{};
820 spec.format = PA_SAMPLE_S16NE;
821 spec.rate = 44100;
822 spec.channels = 2;
824 if(!pulse_name)
826 static const auto defname = al::getenv("ALSOFT_PULSE_DEFAULT");
827 if(defname) pulse_name = defname->c_str();
829 TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)");
830 mStream = plock.connectStream(pulse_name, flags, nullptr, &spec, nullptr,
831 BackendType::Playback);
833 pa_stream_set_moved_callback(mStream, [](pa_stream *stream, void *pdata) noexcept
834 { return static_cast<PulsePlayback*>(pdata)->streamMovedCallback(stream); }, this);
835 mFrameSize = static_cast<uint>(pa_frame_size(pa_stream_get_sample_spec(mStream)));
837 if(pulse_name) mDeviceName.emplace(pulse_name);
838 else mDeviceName.reset();
839 if(display_name.empty())
841 auto name_callback = [](pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept
842 { return static_cast<PulsePlayback*>(pdata)->sinkNameCallback(context, info, eol); };
843 pa_operation *op{pa_context_get_sink_info_by_name(mMainloop.getContext(),
844 pa_stream_get_device_name(mStream), name_callback, this)};
845 plock.waitForOperation(op);
847 else
848 mDevice->DeviceName = display_name;
851 bool PulsePlayback::reset()
853 MainloopUniqueLock plock{mMainloop};
854 const auto deviceName = mDeviceName ? mDeviceName->c_str() : nullptr;
856 if(mStream)
858 pa_stream_set_state_callback(mStream, nullptr, nullptr);
859 pa_stream_set_moved_callback(mStream, nullptr, nullptr);
860 pa_stream_set_write_callback(mStream, nullptr, nullptr);
861 pa_stream_set_buffer_attr_callback(mStream, nullptr, nullptr);
862 pa_stream_disconnect(mStream);
863 pa_stream_unref(mStream);
864 mStream = nullptr;
867 auto info_callback = [](pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept
868 { return static_cast<PulsePlayback*>(pdata)->sinkInfoCallback(context, info, eol); };
869 pa_operation *op{pa_context_get_sink_info_by_name(mMainloop.getContext(), deviceName,
870 info_callback, this)};
871 plock.waitForOperation(op);
873 pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_INTERPOLATE_TIMING |
874 PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_EARLY_REQUESTS};
875 if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
876 flags |= PA_STREAM_DONT_MOVE;
877 if(GetConfigValueBool(mDevice->DeviceName, "pulse", "adjust-latency", false))
879 /* ADJUST_LATENCY can't be specified with EARLY_REQUESTS, for some
880 * reason. So if the user wants to adjust the overall device latency,
881 * we can't ask to get write signals as soon as minreq is reached.
883 flags &= ~PA_STREAM_EARLY_REQUESTS;
884 flags |= PA_STREAM_ADJUST_LATENCY;
886 if(GetConfigValueBool(mDevice->DeviceName, "pulse", "fix-rate", false)
887 || !mDevice->Flags.test(FrequencyRequest))
888 flags |= PA_STREAM_FIX_RATE;
890 pa_channel_map chanmap{};
891 switch(mDevice->FmtChans)
893 case DevFmtMono:
894 chanmap = MonoChanMap;
895 break;
896 case DevFmtAmbi3D:
897 mDevice->FmtChans = DevFmtStereo;
898 /*fall-through*/
899 case DevFmtStereo:
900 chanmap = StereoChanMap;
901 break;
902 case DevFmtQuad:
903 chanmap = QuadChanMap;
904 break;
905 case DevFmtX51:
906 chanmap = (mIs51Rear ? X51RearChanMap : X51ChanMap);
907 break;
908 case DevFmtX61:
909 chanmap = X61ChanMap;
910 break;
911 case DevFmtX71:
912 case DevFmtX3D71:
913 chanmap = X71ChanMap;
914 break;
915 case DevFmtX714:
916 chanmap = X714ChanMap;
917 break;
919 setDefaultWFXChannelOrder();
921 switch(mDevice->FmtType)
923 case DevFmtByte:
924 mDevice->FmtType = DevFmtUByte;
925 /* fall-through */
926 case DevFmtUByte:
927 mSpec.format = PA_SAMPLE_U8;
928 break;
929 case DevFmtUShort:
930 mDevice->FmtType = DevFmtShort;
931 /* fall-through */
932 case DevFmtShort:
933 mSpec.format = PA_SAMPLE_S16NE;
934 break;
935 case DevFmtUInt:
936 mDevice->FmtType = DevFmtInt;
937 /* fall-through */
938 case DevFmtInt:
939 mSpec.format = PA_SAMPLE_S32NE;
940 break;
941 case DevFmtFloat:
942 mSpec.format = PA_SAMPLE_FLOAT32NE;
943 break;
945 mSpec.rate = mDevice->Frequency;
946 mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
947 if(pa_sample_spec_valid(&mSpec) == 0)
948 throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample spec"};
950 const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
951 mAttr.maxlength = ~0u;
952 mAttr.tlength = mDevice->BufferSize * frame_size;
953 mAttr.prebuf = 0u;
954 mAttr.minreq = mDevice->UpdateSize * frame_size;
955 mAttr.fragsize = ~0u;
957 mStream = plock.connectStream(deviceName, flags, &mAttr, &mSpec, &chanmap,
958 BackendType::Playback);
960 pa_stream_set_state_callback(mStream, [](pa_stream *stream, void *pdata) noexcept
961 { return static_cast<PulsePlayback*>(pdata)->streamStateCallback(stream); }, this);
962 pa_stream_set_moved_callback(mStream, [](pa_stream *stream, void *pdata) noexcept
963 { return static_cast<PulsePlayback*>(pdata)->streamMovedCallback(stream); }, this);
965 mSpec = *(pa_stream_get_sample_spec(mStream));
966 mFrameSize = static_cast<uint>(pa_frame_size(&mSpec));
968 if(mDevice->Frequency != mSpec.rate)
970 /* Server updated our playback rate, so modify the buffer attribs
971 * accordingly.
973 const auto scale = static_cast<double>(mSpec.rate) / mDevice->Frequency;
974 const auto perlen = std::clamp(std::round(scale*mDevice->UpdateSize), 64.0, 8192.0);
975 const auto bufmax = uint{std::numeric_limits<int>::max()} / mFrameSize;
976 const auto buflen = std::clamp(std::round(scale*mDevice->BufferSize), perlen*2.0,
977 static_cast<double>(bufmax));
979 mAttr.maxlength = ~0u;
980 mAttr.tlength = static_cast<uint>(buflen) * mFrameSize;
981 mAttr.prebuf = 0u;
982 mAttr.minreq = static_cast<uint>(perlen) * mFrameSize;
984 op = pa_stream_set_buffer_attr(mStream, &mAttr, &PulseMainloop::streamSuccessCallbackC,
985 &mMainloop);
986 plock.waitForOperation(op);
988 mDevice->Frequency = mSpec.rate;
991 auto attr_callback = [](pa_stream *stream, void *pdata) noexcept
992 { return static_cast<PulsePlayback*>(pdata)->bufferAttrCallback(stream); };
993 pa_stream_set_buffer_attr_callback(mStream, attr_callback, this);
994 bufferAttrCallback(mStream);
996 mDevice->BufferSize = mAttr.tlength / mFrameSize;
997 mDevice->UpdateSize = mAttr.minreq / mFrameSize;
999 return true;
1002 void PulsePlayback::start()
1004 MainloopUniqueLock plock{mMainloop};
1006 /* Write some samples to fill the buffer before we start feeding it newly
1007 * mixed samples.
1009 if(size_t todo{pa_stream_writable_size(mStream)})
1011 void *buf{pa_xmalloc(todo)};
1012 mDevice->renderSamples(buf, static_cast<uint>(todo/mFrameSize), mSpec.channels);
1013 pa_stream_write(mStream, buf, todo, pa_xfree, 0, PA_SEEK_RELATIVE);
1016 pa_stream_set_write_callback(mStream, [](pa_stream *stream, size_t nbytes, void *pdata)noexcept
1017 { return static_cast<PulsePlayback*>(pdata)->streamWriteCallback(stream, nbytes); }, this);
1018 pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
1019 &mMainloop)};
1021 plock.waitForOperation(op);
1024 void PulsePlayback::stop()
1026 MainloopUniqueLock plock{mMainloop};
1028 pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
1029 &mMainloop)};
1030 plock.waitForOperation(op);
1031 pa_stream_set_write_callback(mStream, nullptr, nullptr);
1035 ClockLatency PulsePlayback::getClockLatency()
1037 ClockLatency ret{};
1038 pa_usec_t latency{};
1039 int neg{}, err{};
1042 MainloopUniqueLock plock{mMainloop};
1043 ret.ClockTime = mDevice->getClockTime();
1044 err = pa_stream_get_latency(mStream, &latency, &neg);
1047 if(err != 0) UNLIKELY
1049 /* If err = -PA_ERR_NODATA, it means we were called too soon after
1050 * starting the stream and no timing info has been received from the
1051 * server yet. Give a generic value since nothing better is available.
1053 if(err != -PA_ERR_NODATA)
1054 ERR("Failed to get stream latency: 0x%x\n", err);
1055 latency = mDevice->BufferSize - mDevice->UpdateSize;
1056 neg = 0;
1058 else if(neg) UNLIKELY
1059 latency = 0;
1060 ret.Latency = std::chrono::microseconds{latency};
1062 return ret;
1066 struct PulseCapture final : public BackendBase {
1067 PulseCapture(DeviceBase *device) noexcept : BackendBase{device} { }
1068 ~PulseCapture() override;
1070 void streamStateCallback(pa_stream *stream) noexcept;
1071 void sourceNameCallback(pa_context *context, const pa_source_info *info, int eol) noexcept;
1072 void streamMovedCallback(pa_stream *stream) noexcept;
1074 void open(std::string_view name) override;
1075 void start() override;
1076 void stop() override;
1077 void captureSamples(std::byte *buffer, uint samples) override;
1078 uint availableSamples() override;
1079 ClockLatency getClockLatency() override;
1081 PulseMainloop mMainloop;
1083 std::optional<std::string> mDeviceName{std::nullopt};
1085 al::span<const std::byte> mCapBuffer;
1086 size_t mHoleLength{0};
1087 size_t mPacketLength{0};
1089 uint mLastReadable{0u};
1090 std::byte mSilentVal{};
1092 pa_buffer_attr mAttr{};
1093 pa_sample_spec mSpec{};
1095 pa_stream *mStream{nullptr};
1098 PulseCapture::~PulseCapture()
1099 { if(mStream) mMainloop.close(mStream); }
1102 void PulseCapture::streamStateCallback(pa_stream *stream) noexcept
1104 if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
1106 ERR("Received stream failure!\n");
1107 mDevice->handleDisconnect("Capture stream failure");
1109 mMainloop.signal();
1112 void PulseCapture::sourceNameCallback(pa_context*, const pa_source_info *info, int eol) noexcept
1114 if(eol)
1116 mMainloop.signal();
1117 return;
1119 mDevice->DeviceName = info->description;
1122 void PulseCapture::streamMovedCallback(pa_stream *stream) noexcept
1124 mDeviceName = pa_stream_get_device_name(stream);
1125 TRACE("Stream moved to %s\n", mDeviceName->c_str());
1129 void PulseCapture::open(std::string_view name)
1131 if(!mMainloop)
1133 mMainloop = PulseMainloop::Create();
1134 if(mMainloop.start() != 0)
1135 throw al::backend_exception{al::backend_error::DeviceError,
1136 "Failed to start device mainloop"};
1139 const char *pulse_name{nullptr};
1140 if(!name.empty())
1142 if(CaptureDevices.empty())
1143 mMainloop.probeCaptureDevices();
1145 auto match_name = [name](const DevMap &entry) -> bool
1146 { return entry.name == name || entry.device_name == name; };
1147 auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), match_name);
1148 if(iter == CaptureDevices.cend())
1149 throw al::backend_exception{al::backend_error::NoDevice,
1150 "Device name \"%.*s\" not found", al::sizei(name), name.data()};
1151 pulse_name = iter->device_name.c_str();
1152 mDevice->DeviceName = iter->name;
1155 MainloopUniqueLock plock{mMainloop};
1156 plock.connectContext();
1158 pa_channel_map chanmap{};
1159 switch(mDevice->FmtChans)
1161 case DevFmtMono:
1162 chanmap = MonoChanMap;
1163 break;
1164 case DevFmtStereo:
1165 chanmap = StereoChanMap;
1166 break;
1167 case DevFmtQuad:
1168 chanmap = QuadChanMap;
1169 break;
1170 case DevFmtX51:
1171 chanmap = X51ChanMap;
1172 break;
1173 case DevFmtX61:
1174 chanmap = X61ChanMap;
1175 break;
1176 case DevFmtX71:
1177 chanmap = X71ChanMap;
1178 break;
1179 case DevFmtX714:
1180 chanmap = X714ChanMap;
1181 break;
1182 case DevFmtX3D71:
1183 case DevFmtAmbi3D:
1184 throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported",
1185 DevFmtChannelsString(mDevice->FmtChans)};
1187 setDefaultWFXChannelOrder();
1189 switch(mDevice->FmtType)
1191 case DevFmtUByte:
1192 mSilentVal = std::byte(0x80);
1193 mSpec.format = PA_SAMPLE_U8;
1194 break;
1195 case DevFmtShort:
1196 mSpec.format = PA_SAMPLE_S16NE;
1197 break;
1198 case DevFmtInt:
1199 mSpec.format = PA_SAMPLE_S32NE;
1200 break;
1201 case DevFmtFloat:
1202 mSpec.format = PA_SAMPLE_FLOAT32NE;
1203 break;
1204 case DevFmtByte:
1205 case DevFmtUShort:
1206 case DevFmtUInt:
1207 throw al::backend_exception{al::backend_error::DeviceError,
1208 "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)};
1210 mSpec.rate = mDevice->Frequency;
1211 mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
1212 if(pa_sample_spec_valid(&mSpec) == 0)
1213 throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample format"};
1215 const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
1216 const uint samples{std::max(mDevice->BufferSize, mDevice->Frequency*100u/1000u)};
1217 mAttr.minreq = ~0u;
1218 mAttr.prebuf = ~0u;
1219 mAttr.maxlength = samples * frame_size;
1220 mAttr.tlength = ~0u;
1221 mAttr.fragsize = std::min(samples, mDevice->Frequency*50u/1000u) * frame_size;
1223 pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_ADJUST_LATENCY};
1224 if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
1225 flags |= PA_STREAM_DONT_MOVE;
1227 TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)");
1228 mStream = plock.connectStream(pulse_name, flags, &mAttr, &mSpec, &chanmap,
1229 BackendType::Capture);
1231 pa_stream_set_moved_callback(mStream, [](pa_stream *stream, void *pdata) noexcept
1232 { return static_cast<PulseCapture*>(pdata)->streamMovedCallback(stream); }, this);
1233 pa_stream_set_state_callback(mStream, [](pa_stream *stream, void *pdata) noexcept
1234 { return static_cast<PulseCapture*>(pdata)->streamStateCallback(stream); }, this);
1236 if(pulse_name) mDeviceName.emplace(pulse_name);
1237 else mDeviceName.reset();
1238 if(mDevice->DeviceName.empty())
1240 auto name_callback = [](pa_context *context, const pa_source_info *info, int eol, void *pdata) noexcept
1241 { return static_cast<PulseCapture*>(pdata)->sourceNameCallback(context, info, eol); };
1242 pa_operation *op{pa_context_get_source_info_by_name(mMainloop.getContext(),
1243 pa_stream_get_device_name(mStream), name_callback, this)};
1244 plock.waitForOperation(op);
1248 void PulseCapture::start()
1250 MainloopUniqueLock plock{mMainloop};
1251 pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
1252 &mMainloop)};
1253 plock.waitForOperation(op);
1256 void PulseCapture::stop()
1258 MainloopUniqueLock plock{mMainloop};
1259 pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
1260 &mMainloop)};
1261 plock.waitForOperation(op);
1264 void PulseCapture::captureSamples(std::byte *buffer, uint samples)
1266 al::span<std::byte> dstbuf{buffer, samples * pa_frame_size(&mSpec)};
1268 /* Capture is done in fragment-sized chunks, so we loop until we get all
1269 * that's available.
1271 mLastReadable -= static_cast<uint>(dstbuf.size());
1272 while(!dstbuf.empty())
1274 if(mHoleLength > 0) UNLIKELY
1276 const size_t rem{std::min(dstbuf.size(), mHoleLength)};
1277 std::fill_n(dstbuf.begin(), rem, mSilentVal);
1278 dstbuf = dstbuf.subspan(rem);
1279 mHoleLength -= rem;
1281 continue;
1283 if(!mCapBuffer.empty())
1285 const size_t rem{std::min(dstbuf.size(), mCapBuffer.size())};
1286 std::copy_n(mCapBuffer.begin(), rem, dstbuf.begin());
1287 dstbuf = dstbuf.subspan(rem);
1288 mCapBuffer = mCapBuffer.subspan(rem);
1290 continue;
1293 if(!mDevice->Connected.load(std::memory_order_acquire)) UNLIKELY
1294 break;
1296 MainloopUniqueLock plock{mMainloop};
1297 if(mPacketLength > 0)
1299 pa_stream_drop(mStream);
1300 mPacketLength = 0;
1303 const pa_stream_state_t state{pa_stream_get_state(mStream)};
1304 if(!PA_STREAM_IS_GOOD(state)) UNLIKELY
1306 mDevice->handleDisconnect("Bad capture state: %u", state);
1307 break;
1310 const void *capbuf{};
1311 size_t caplen{};
1312 if(pa_stream_peek(mStream, &capbuf, &caplen) < 0) UNLIKELY
1314 mDevice->handleDisconnect("Failed retrieving capture samples: %s",
1315 pa_strerror(pa_context_errno(mMainloop.getContext())));
1316 break;
1318 plock.unlock();
1320 if(caplen == 0) break;
1321 if(!capbuf) UNLIKELY
1322 mHoleLength = caplen;
1323 else
1324 mCapBuffer = {static_cast<const std::byte*>(capbuf), caplen};
1325 mPacketLength = caplen;
1327 if(!dstbuf.empty())
1328 std::fill(dstbuf.begin(), dstbuf.end(), mSilentVal);
1331 uint PulseCapture::availableSamples()
1333 size_t readable{std::max(mCapBuffer.size(), mHoleLength)};
1335 if(mDevice->Connected.load(std::memory_order_acquire))
1337 MainloopUniqueLock plock{mMainloop};
1338 size_t got{pa_stream_readable_size(mStream)};
1339 if(static_cast<ssize_t>(got) < 0) UNLIKELY
1341 const char *err{pa_strerror(static_cast<int>(got))};
1342 ERR("pa_stream_readable_size() failed: %s\n", err);
1343 mDevice->handleDisconnect("Failed getting readable size: %s", err);
1345 else
1347 /* "readable" is the number of bytes from the last packet that have
1348 * not yet been read by the caller. So add the stream's readable
1349 * size excluding the last packet (the stream size includes the
1350 * last packet until it's dropped).
1352 if(got > mPacketLength)
1353 readable += got - mPacketLength;
1357 /* Avoid uint overflow, and avoid decreasing the readable count. */
1358 readable = std::min<size_t>(readable, std::numeric_limits<uint>::max());
1359 mLastReadable = std::max(mLastReadable, static_cast<uint>(readable));
1360 return mLastReadable / static_cast<uint>(pa_frame_size(&mSpec));
1364 ClockLatency PulseCapture::getClockLatency()
1366 ClockLatency ret{};
1367 pa_usec_t latency{};
1368 int neg{}, err{};
1371 MainloopUniqueLock plock{mMainloop};
1372 ret.ClockTime = mDevice->getClockTime();
1373 err = pa_stream_get_latency(mStream, &latency, &neg);
1376 if(err != 0) UNLIKELY
1378 ERR("Failed to get stream latency: 0x%x\n", err);
1379 latency = 0;
1380 neg = 0;
1382 else if(neg) UNLIKELY
1383 latency = 0;
1384 ret.Latency = std::chrono::microseconds{latency};
1386 return ret;
1389 } // namespace
1392 bool PulseBackendFactory::init()
1394 #ifdef HAVE_DYNLOAD
1395 if(!pulse_handle)
1397 #ifdef _WIN32
1398 #define PALIB "libpulse-0.dll"
1399 #elif defined(__APPLE__) && defined(__MACH__)
1400 #define PALIB "libpulse.0.dylib"
1401 #else
1402 #define PALIB "libpulse.so.0"
1403 #endif
1404 pulse_handle = LoadLib(PALIB);
1405 if(!pulse_handle)
1407 WARN("Failed to load %s\n", PALIB);
1408 return false;
1411 std::string missing_funcs;
1412 #define LOAD_FUNC(x) do { \
1413 p##x = reinterpret_cast<decltype(p##x)>(GetSymbol(pulse_handle, #x)); \
1414 if(!(p##x)) missing_funcs += "\n" #x; \
1415 } while(0)
1416 PULSE_FUNCS(LOAD_FUNC)
1417 #undef LOAD_FUNC
1419 if(!missing_funcs.empty())
1421 WARN("Missing expected functions:%s\n", missing_funcs.c_str());
1422 CloseLib(pulse_handle);
1423 pulse_handle = nullptr;
1424 return false;
1427 #endif /* HAVE_DYNLOAD */
1429 pulse_ctx_flags = PA_CONTEXT_NOFLAGS;
1430 if(!GetConfigValueBool({}, "pulse", "spawn-server", false))
1431 pulse_ctx_flags |= PA_CONTEXT_NOAUTOSPAWN;
1433 try {
1434 if(!gGlobalMainloop)
1436 gGlobalMainloop = PulseMainloop::Create();
1437 if(gGlobalMainloop.start() != 0)
1439 gGlobalMainloop = nullptr;
1440 return false;
1444 MainloopUniqueLock plock{gGlobalMainloop};
1445 plock.connectContext();
1446 plock.setEventHandler();
1447 return true;
1449 catch(...) {
1450 return false;
1454 bool PulseBackendFactory::querySupport(BackendType type)
1455 { return type == BackendType::Playback || type == BackendType::Capture; }
1457 auto PulseBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
1459 std::vector<std::string> outnames;
1461 auto add_device = [&outnames](const DevMap &entry) -> void
1462 { outnames.push_back(entry.name); };
1464 switch(type)
1466 case BackendType::Playback:
1467 gGlobalMainloop.probePlaybackDevices();
1468 outnames.reserve(PlaybackDevices.size());
1469 std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
1470 break;
1472 case BackendType::Capture:
1473 gGlobalMainloop.probeCaptureDevices();
1474 outnames.reserve(CaptureDevices.size());
1475 std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
1476 break;
1479 return outnames;
1482 BackendPtr PulseBackendFactory::createBackend(DeviceBase *device, BackendType type)
1484 if(type == BackendType::Playback)
1485 return BackendPtr{new PulsePlayback{device}};
1486 if(type == BackendType::Capture)
1487 return BackendPtr{new PulseCapture{device}};
1488 return nullptr;
1491 BackendFactory &PulseBackendFactory::getFactory()
1493 static PulseBackendFactory factory{};
1494 return factory;
1497 alc::EventSupport PulseBackendFactory::queryEventSupport(alc::EventType eventType, BackendType)
1499 switch(eventType)
1501 case alc::EventType::DeviceAdded:
1502 case alc::EventType::DeviceRemoved:
1503 return alc::EventSupport::FullSupport;
1505 case alc::EventType::DefaultDeviceChanged:
1506 case alc::EventType::Count:
1507 break;
1509 return alc::EventSupport::NoSupport;