Don't lock the device state when preparing a new effect state
[openal-soft.git] / alc / backends / pulseaudio.cpp
blob91fa4b6c1567c83c414d1ef05546c8122867e79e
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 <cmath>
32 #include <cstddef>
33 #include <cstdint>
34 #include <cstring>
35 #include <exception>
36 #include <limits>
37 #include <mutex>
38 #include <optional>
39 #include <string>
40 #include <string_view>
41 #include <sys/types.h>
42 #include <utility>
43 #include <vector>
45 #include "alc/alconfig.h"
46 #include "alspan.h"
47 #include "alstring.h"
48 #include "base.h"
49 #include "core/devformat.h"
50 #include "core/device.h"
51 #include "core/logging.h"
52 #include "dynload.h"
53 #include "opthelpers.h"
54 #include "strutils.h"
56 #include <pulse/pulseaudio.h>
59 namespace {
61 using uint = unsigned int;
63 #ifdef HAVE_DYNLOAD
64 #define PULSE_FUNCS(MAGIC) \
65 MAGIC(pa_context_new); \
66 MAGIC(pa_context_unref); \
67 MAGIC(pa_context_get_state); \
68 MAGIC(pa_context_disconnect); \
69 MAGIC(pa_context_set_state_callback); \
70 MAGIC(pa_context_set_subscribe_callback); \
71 MAGIC(pa_context_subscribe); \
72 MAGIC(pa_context_errno); \
73 MAGIC(pa_context_connect); \
74 MAGIC(pa_context_get_server_info); \
75 MAGIC(pa_context_get_sink_info_by_name); \
76 MAGIC(pa_context_get_sink_info_list); \
77 MAGIC(pa_context_get_source_info_by_name); \
78 MAGIC(pa_context_get_source_info_list); \
79 MAGIC(pa_stream_new); \
80 MAGIC(pa_stream_unref); \
81 MAGIC(pa_stream_drop); \
82 MAGIC(pa_stream_get_state); \
83 MAGIC(pa_stream_peek); \
84 MAGIC(pa_stream_write); \
85 MAGIC(pa_stream_connect_record); \
86 MAGIC(pa_stream_connect_playback); \
87 MAGIC(pa_stream_readable_size); \
88 MAGIC(pa_stream_writable_size); \
89 MAGIC(pa_stream_is_corked); \
90 MAGIC(pa_stream_cork); \
91 MAGIC(pa_stream_is_suspended); \
92 MAGIC(pa_stream_get_device_name); \
93 MAGIC(pa_stream_get_latency); \
94 MAGIC(pa_stream_set_write_callback); \
95 MAGIC(pa_stream_set_buffer_attr); \
96 MAGIC(pa_stream_get_buffer_attr); \
97 MAGIC(pa_stream_get_sample_spec); \
98 MAGIC(pa_stream_get_time); \
99 MAGIC(pa_stream_set_read_callback); \
100 MAGIC(pa_stream_set_state_callback); \
101 MAGIC(pa_stream_set_moved_callback); \
102 MAGIC(pa_stream_set_underflow_callback); \
103 MAGIC(pa_stream_new_with_proplist); \
104 MAGIC(pa_stream_disconnect); \
105 MAGIC(pa_stream_set_buffer_attr_callback); \
106 MAGIC(pa_stream_begin_write); \
107 MAGIC(pa_threaded_mainloop_free); \
108 MAGIC(pa_threaded_mainloop_get_api); \
109 MAGIC(pa_threaded_mainloop_lock); \
110 MAGIC(pa_threaded_mainloop_new); \
111 MAGIC(pa_threaded_mainloop_signal); \
112 MAGIC(pa_threaded_mainloop_start); \
113 MAGIC(pa_threaded_mainloop_stop); \
114 MAGIC(pa_threaded_mainloop_unlock); \
115 MAGIC(pa_threaded_mainloop_wait); \
116 MAGIC(pa_channel_map_init_auto); \
117 MAGIC(pa_channel_map_parse); \
118 MAGIC(pa_channel_map_snprint); \
119 MAGIC(pa_channel_map_equal); \
120 MAGIC(pa_channel_map_superset); \
121 MAGIC(pa_channel_position_to_string); \
122 MAGIC(pa_operation_get_state); \
123 MAGIC(pa_operation_unref); \
124 MAGIC(pa_sample_spec_valid); \
125 MAGIC(pa_frame_size); \
126 MAGIC(pa_strerror); \
127 MAGIC(pa_path_get_filename); \
128 MAGIC(pa_get_binary_name); \
129 MAGIC(pa_xmalloc); \
130 MAGIC(pa_xfree);
132 void *pulse_handle;
133 #define MAKE_FUNC(x) decltype(x) * p##x
134 PULSE_FUNCS(MAKE_FUNC)
135 #undef MAKE_FUNC
137 #ifndef IN_IDE_PARSER
138 #define pa_context_new ppa_context_new
139 #define pa_context_unref ppa_context_unref
140 #define pa_context_get_state ppa_context_get_state
141 #define pa_context_disconnect ppa_context_disconnect
142 #define pa_context_set_state_callback ppa_context_set_state_callback
143 #define pa_context_set_subscribe_callback ppa_context_set_subscribe_callback
144 #define pa_context_subscribe ppa_context_subscribe
145 #define pa_context_errno ppa_context_errno
146 #define pa_context_connect ppa_context_connect
147 #define pa_context_get_server_info ppa_context_get_server_info
148 #define pa_context_get_sink_info_by_name ppa_context_get_sink_info_by_name
149 #define pa_context_get_sink_info_list ppa_context_get_sink_info_list
150 #define pa_context_get_source_info_by_name ppa_context_get_source_info_by_name
151 #define pa_context_get_source_info_list ppa_context_get_source_info_list
152 #define pa_stream_new ppa_stream_new
153 #define pa_stream_unref ppa_stream_unref
154 #define pa_stream_disconnect ppa_stream_disconnect
155 #define pa_stream_drop ppa_stream_drop
156 #define pa_stream_set_write_callback ppa_stream_set_write_callback
157 #define pa_stream_set_buffer_attr ppa_stream_set_buffer_attr
158 #define pa_stream_get_buffer_attr ppa_stream_get_buffer_attr
159 #define pa_stream_get_sample_spec ppa_stream_get_sample_spec
160 #define pa_stream_get_time ppa_stream_get_time
161 #define pa_stream_set_read_callback ppa_stream_set_read_callback
162 #define pa_stream_set_state_callback ppa_stream_set_state_callback
163 #define pa_stream_set_moved_callback ppa_stream_set_moved_callback
164 #define pa_stream_set_underflow_callback ppa_stream_set_underflow_callback
165 #define pa_stream_connect_record ppa_stream_connect_record
166 #define pa_stream_connect_playback ppa_stream_connect_playback
167 #define pa_stream_readable_size ppa_stream_readable_size
168 #define pa_stream_writable_size ppa_stream_writable_size
169 #define pa_stream_is_corked ppa_stream_is_corked
170 #define pa_stream_cork ppa_stream_cork
171 #define pa_stream_is_suspended ppa_stream_is_suspended
172 #define pa_stream_get_device_name ppa_stream_get_device_name
173 #define pa_stream_get_latency ppa_stream_get_latency
174 #define pa_stream_set_buffer_attr_callback ppa_stream_set_buffer_attr_callback
175 #define pa_stream_begin_write ppa_stream_begin_write
176 #define pa_threaded_mainloop_free ppa_threaded_mainloop_free
177 #define pa_threaded_mainloop_get_api ppa_threaded_mainloop_get_api
178 #define pa_threaded_mainloop_lock ppa_threaded_mainloop_lock
179 #define pa_threaded_mainloop_new ppa_threaded_mainloop_new
180 #define pa_threaded_mainloop_signal ppa_threaded_mainloop_signal
181 #define pa_threaded_mainloop_start ppa_threaded_mainloop_start
182 #define pa_threaded_mainloop_stop ppa_threaded_mainloop_stop
183 #define pa_threaded_mainloop_unlock ppa_threaded_mainloop_unlock
184 #define pa_threaded_mainloop_wait ppa_threaded_mainloop_wait
185 #define pa_channel_map_init_auto ppa_channel_map_init_auto
186 #define pa_channel_map_parse ppa_channel_map_parse
187 #define pa_channel_map_snprint ppa_channel_map_snprint
188 #define pa_channel_map_equal ppa_channel_map_equal
189 #define pa_channel_map_superset ppa_channel_map_superset
190 #define pa_channel_position_to_string ppa_channel_position_to_string
191 #define pa_operation_get_state ppa_operation_get_state
192 #define pa_operation_unref ppa_operation_unref
193 #define pa_sample_spec_valid ppa_sample_spec_valid
194 #define pa_frame_size ppa_frame_size
195 #define pa_strerror ppa_strerror
196 #define pa_stream_get_state ppa_stream_get_state
197 #define pa_stream_peek ppa_stream_peek
198 #define pa_stream_write ppa_stream_write
199 #define pa_xfree ppa_xfree
200 #define pa_path_get_filename ppa_path_get_filename
201 #define pa_get_binary_name ppa_get_binary_name
202 #define pa_xmalloc ppa_xmalloc
203 #endif /* IN_IDE_PARSER */
205 #endif
208 constexpr pa_channel_map MonoChanMap{
209 1, {PA_CHANNEL_POSITION_MONO}
210 }, StereoChanMap{
211 2, {PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT}
212 }, QuadChanMap{
213 4, {
214 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
215 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
217 }, X51ChanMap{
218 6, {
219 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
220 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
221 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
223 }, X51RearChanMap{
224 6, {
225 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
226 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
227 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
229 }, X61ChanMap{
230 7, {
231 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
232 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
233 PA_CHANNEL_POSITION_REAR_CENTER,
234 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
236 }, X71ChanMap{
237 8, {
238 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
239 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
240 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
241 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
243 }, X714ChanMap{
244 12, {
245 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
246 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
247 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
248 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT,
249 PA_CHANNEL_POSITION_TOP_FRONT_LEFT, PA_CHANNEL_POSITION_TOP_FRONT_RIGHT,
250 PA_CHANNEL_POSITION_TOP_REAR_LEFT, PA_CHANNEL_POSITION_TOP_REAR_RIGHT
255 /* *grumble* Don't use enums for bitflags. */
256 constexpr pa_stream_flags_t operator|(pa_stream_flags_t lhs, pa_stream_flags_t rhs)
257 { return pa_stream_flags_t(lhs | al::to_underlying(rhs)); }
258 constexpr pa_stream_flags_t& operator|=(pa_stream_flags_t &lhs, pa_stream_flags_t rhs)
260 lhs = lhs | rhs;
261 return lhs;
263 constexpr pa_stream_flags_t operator~(pa_stream_flags_t flag)
264 { return pa_stream_flags_t(~al::to_underlying(flag)); }
265 constexpr pa_stream_flags_t& operator&=(pa_stream_flags_t &lhs, pa_stream_flags_t rhs)
267 lhs = pa_stream_flags_t(al::to_underlying(lhs) & rhs);
268 return lhs;
271 constexpr pa_context_flags_t operator|(pa_context_flags_t lhs, pa_context_flags_t rhs)
272 { return pa_context_flags_t(lhs | al::to_underlying(rhs)); }
273 constexpr pa_context_flags_t& operator|=(pa_context_flags_t &lhs, pa_context_flags_t rhs)
275 lhs = lhs | rhs;
276 return lhs;
279 constexpr pa_subscription_mask_t operator|(pa_subscription_mask_t lhs, pa_subscription_mask_t rhs)
280 { return pa_subscription_mask_t(lhs | al::to_underlying(rhs)); }
283 struct DevMap {
284 std::string name;
285 std::string device_name;
288 bool checkName(const al::span<const DevMap> list, const std::string &name)
290 auto match_name = [&name](const DevMap &entry) -> bool { return entry.name == name; };
291 return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
294 std::vector<DevMap> PlaybackDevices;
295 std::vector<DevMap> CaptureDevices;
298 /* Global flags and properties */
299 pa_context_flags_t pulse_ctx_flags;
301 class PulseMainloop {
302 pa_threaded_mainloop *mLoop{};
303 pa_context *mContext{};
305 public:
306 PulseMainloop() = default;
307 PulseMainloop(const PulseMainloop&) = delete;
308 PulseMainloop(PulseMainloop&& rhs) noexcept : mLoop{rhs.mLoop} { rhs.mLoop = nullptr; }
309 explicit PulseMainloop(pa_threaded_mainloop *loop) noexcept : mLoop{loop} { }
310 ~PulseMainloop();
312 PulseMainloop& operator=(const PulseMainloop&) = delete;
313 PulseMainloop& operator=(PulseMainloop&& rhs) noexcept
314 { std::swap(mLoop, rhs.mLoop); return *this; }
315 PulseMainloop& operator=(std::nullptr_t) noexcept
317 if(mLoop)
318 pa_threaded_mainloop_free(mLoop);
319 mLoop = nullptr;
320 return *this;
323 explicit operator bool() const noexcept { return mLoop != nullptr; }
325 [[nodiscard]]
326 auto start() const { return pa_threaded_mainloop_start(mLoop); }
327 auto stop() const { return pa_threaded_mainloop_stop(mLoop); }
329 [[nodiscard]] auto getApi() const { return pa_threaded_mainloop_get_api(mLoop); }
330 [[nodiscard]] auto getContext() const noexcept { return mContext; }
332 auto lock() const { return pa_threaded_mainloop_lock(mLoop); }
333 auto unlock() const { return pa_threaded_mainloop_unlock(mLoop); }
335 auto signal(bool wait=false) const { return pa_threaded_mainloop_signal(mLoop, wait); }
337 static auto Create() { return PulseMainloop{pa_threaded_mainloop_new()}; }
340 void streamSuccessCallback(pa_stream*, int) const noexcept { signal(); }
341 static void streamSuccessCallbackC(pa_stream *stream, int success, void *pdata) noexcept
342 { static_cast<PulseMainloop*>(pdata)->streamSuccessCallback(stream, success); }
344 void close(pa_stream *stream=nullptr);
347 void deviceSinkCallback(pa_context*, const pa_sink_info *info, int eol) const noexcept
349 if(eol)
351 signal();
352 return;
355 /* Skip this device is if it's already in the list. */
356 auto match_devname = [info](const DevMap &entry) -> bool
357 { return entry.device_name == info->name; };
358 if(std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), match_devname) != PlaybackDevices.cend())
359 return;
361 /* Make sure the display name (description) is unique. Append a number
362 * counter as needed.
364 int count{1};
365 std::string newname{info->description};
366 while(checkName(PlaybackDevices, newname))
368 newname = info->description;
369 newname += " #";
370 newname += std::to_string(++count);
372 PlaybackDevices.emplace_back(DevMap{std::move(newname), info->name});
373 DevMap &newentry = PlaybackDevices.back();
375 TRACE("Got device \"%s\", \"%s\"\n", newentry.name.c_str(), newentry.device_name.c_str());
378 void deviceSourceCallback(pa_context*, const pa_source_info *info, int eol) const noexcept
380 if(eol)
382 signal();
383 return;
386 /* Skip this device is if it's already in the list. */
387 auto match_devname = [info](const DevMap &entry) -> bool
388 { return entry.device_name == info->name; };
389 if(std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), match_devname) != CaptureDevices.cend())
390 return;
392 /* Make sure the display name (description) is unique. Append a number
393 * counter as needed.
395 int count{1};
396 std::string newname{info->description};
397 while(checkName(CaptureDevices, newname))
399 newname = info->description;
400 newname += " #";
401 newname += std::to_string(++count);
403 CaptureDevices.emplace_back(DevMap{std::move(newname), info->name});
404 DevMap &newentry = CaptureDevices.back();
406 TRACE("Got device \"%s\", \"%s\"\n", newentry.name.c_str(), newentry.device_name.c_str());
409 void probePlaybackDevices();
410 void probeCaptureDevices();
412 friend struct MainloopUniqueLock;
414 struct MainloopUniqueLock : public std::unique_lock<PulseMainloop> {
415 using std::unique_lock<PulseMainloop>::unique_lock;
416 MainloopUniqueLock& operator=(MainloopUniqueLock&&) = default;
418 auto wait() const -> void
419 { pa_threaded_mainloop_wait(mutex()->mLoop); }
421 template<typename Predicate>
422 auto wait(Predicate done_waiting) const -> void
423 { while(!done_waiting()) wait(); }
425 void waitForOperation(pa_operation *op) const
427 if(op)
429 wait([op]{ return pa_operation_get_state(op) != PA_OPERATION_RUNNING; });
430 pa_operation_unref(op);
435 void setEventHandler()
437 pa_operation *op{pa_context_subscribe(mutex()->mContext,
438 PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SOURCE,
439 [](pa_context*, int, void *pdata) noexcept
440 { static_cast<PulseMainloop*>(pdata)->signal(); },
441 mutex())};
442 waitForOperation(op);
444 /* Watch for device added/removed events.
446 * TODO: Also track the "default" device, in as much as PulseAudio has
447 * the concept of a default device (whatever device is opened when not
448 * specifying a specific sink or source name). There doesn't seem to be
449 * an event for this.
451 auto handler = [](pa_context*, pa_subscription_event_type_t t, uint32_t, void*) noexcept
453 const auto eventFacility = (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK);
454 if(eventFacility == PA_SUBSCRIPTION_EVENT_SINK
455 || eventFacility == PA_SUBSCRIPTION_EVENT_SOURCE)
457 const auto deviceType = (eventFacility == PA_SUBSCRIPTION_EVENT_SINK)
458 ? alc::DeviceType::Playback : alc::DeviceType::Capture;
459 const auto eventType = (t & PA_SUBSCRIPTION_EVENT_TYPE_MASK);
460 if(eventType == PA_SUBSCRIPTION_EVENT_NEW)
461 alc::Event(alc::EventType::DeviceAdded, deviceType, "Device added");
462 else if(eventType == PA_SUBSCRIPTION_EVENT_REMOVE)
463 alc::Event(alc::EventType::DeviceRemoved, deviceType, "Device removed");
466 pa_context_set_subscribe_callback(mutex()->mContext, handler, nullptr);
470 void contextStateCallback(pa_context *context) noexcept
472 pa_context_state_t state{pa_context_get_state(context)};
473 if(state == PA_CONTEXT_READY || !PA_CONTEXT_IS_GOOD(state))
474 mutex()->signal();
477 void streamStateCallback(pa_stream *stream) noexcept
479 pa_stream_state_t state{pa_stream_get_state(stream)};
480 if(state == PA_STREAM_READY || !PA_STREAM_IS_GOOD(state))
481 mutex()->signal();
484 void connectContext();
485 pa_stream *connectStream(const char *device_name, pa_stream_flags_t flags,
486 pa_buffer_attr *attr, pa_sample_spec *spec, pa_channel_map *chanmap, BackendType type);
488 using MainloopLockGuard = std::lock_guard<PulseMainloop>;
490 PulseMainloop::~PulseMainloop()
492 if(mContext)
494 MainloopUniqueLock looplock{*this};
495 pa_context_disconnect(mContext);
496 pa_context_unref(mContext);
498 if(mLoop)
499 pa_threaded_mainloop_free(mLoop);
503 void MainloopUniqueLock::connectContext()
505 if(mutex()->mContext)
506 return;
508 mutex()->mContext = pa_context_new(mutex()->getApi(), nullptr);
509 if(!mutex()->mContext) throw al::backend_exception{al::backend_error::OutOfMemory,
510 "pa_context_new() failed"};
512 pa_context_set_state_callback(mutex()->mContext, [](pa_context *ctx, void *pdata) noexcept
513 { return static_cast<MainloopUniqueLock*>(pdata)->contextStateCallback(ctx); }, this);
515 int err{pa_context_connect(mutex()->mContext, nullptr, pulse_ctx_flags, nullptr)};
516 if(err >= 0)
518 wait([&err,this]()
520 pa_context_state_t state{pa_context_get_state(mutex()->mContext)};
521 if(!PA_CONTEXT_IS_GOOD(state))
523 err = pa_context_errno(mutex()->mContext);
524 if(err > 0) err = -err;
525 return true;
527 return state == PA_CONTEXT_READY;
530 pa_context_set_state_callback(mutex()->mContext, nullptr, nullptr);
532 if(err < 0)
534 pa_context_unref(mutex()->mContext);
535 mutex()->mContext = nullptr;
536 throw al::backend_exception{al::backend_error::DeviceError, "Context did not connect (%s)",
537 pa_strerror(err)};
541 pa_stream *MainloopUniqueLock::connectStream(const char *device_name, pa_stream_flags_t flags,
542 pa_buffer_attr *attr, pa_sample_spec *spec, pa_channel_map *chanmap, BackendType type)
544 const char *stream_id{(type==BackendType::Playback) ? "Playback Stream" : "Capture Stream"};
545 pa_stream *stream{pa_stream_new(mutex()->mContext, stream_id, spec, chanmap)};
546 if(!stream)
547 throw al::backend_exception{al::backend_error::OutOfMemory, "pa_stream_new() failed (%s)",
548 pa_strerror(pa_context_errno(mutex()->mContext))};
550 pa_stream_set_state_callback(stream, [](pa_stream *strm, void *pdata) noexcept
551 { return static_cast<MainloopUniqueLock*>(pdata)->streamStateCallback(strm); }, this);
553 int err{(type==BackendType::Playback) ?
554 pa_stream_connect_playback(stream, device_name, attr, flags, nullptr, nullptr) :
555 pa_stream_connect_record(stream, device_name, attr, flags)};
556 if(err < 0)
558 pa_stream_unref(stream);
559 throw al::backend_exception{al::backend_error::DeviceError, "%s did not connect (%s)",
560 stream_id, pa_strerror(err)};
563 wait([&err,stream,stream_id,this]()
565 pa_stream_state_t state{pa_stream_get_state(stream)};
566 if(!PA_STREAM_IS_GOOD(state))
568 err = pa_context_errno(mutex()->mContext);
569 pa_stream_unref(stream);
570 throw al::backend_exception{al::backend_error::DeviceError,
571 "%s did not get ready (%s)", stream_id, pa_strerror(err)};
573 return state == PA_STREAM_READY;
576 pa_stream_set_state_callback(stream, nullptr, nullptr);
578 return stream;
581 void PulseMainloop::close(pa_stream *stream)
583 if(!stream)
584 return;
586 MainloopUniqueLock looplock{*this};
587 pa_stream_set_state_callback(stream, nullptr, nullptr);
588 pa_stream_set_moved_callback(stream, nullptr, nullptr);
589 pa_stream_set_write_callback(stream, nullptr, nullptr);
590 pa_stream_set_buffer_attr_callback(stream, nullptr, nullptr);
591 pa_stream_disconnect(stream);
592 pa_stream_unref(stream);
596 void PulseMainloop::probePlaybackDevices()
598 PlaybackDevices.clear();
599 try {
600 MainloopUniqueLock plock{*this};
601 plock.connectContext();
603 auto sink_callback = [](pa_context *ctx, const pa_sink_info *info, int eol, void *pdata) noexcept
604 { return static_cast<PulseMainloop*>(pdata)->deviceSinkCallback(ctx, info, eol); };
606 pa_operation *op{pa_context_get_sink_info_by_name(mContext, nullptr, sink_callback, this)};
607 plock.waitForOperation(op);
609 op = pa_context_get_sink_info_list(mContext, sink_callback, this);
610 plock.waitForOperation(op);
612 catch(std::exception &e) {
613 ERR("Error enumerating devices: %s\n", e.what());
617 void PulseMainloop::probeCaptureDevices()
619 CaptureDevices.clear();
620 try {
621 MainloopUniqueLock plock{*this};
622 plock.connectContext();
624 auto src_callback = [](pa_context *ctx, const pa_source_info *info, int eol, void *pdata) noexcept
625 { return static_cast<PulseMainloop*>(pdata)->deviceSourceCallback(ctx, info, eol); };
627 pa_operation *op{pa_context_get_source_info_by_name(mContext, nullptr, src_callback,
628 this)};
629 plock.waitForOperation(op);
631 op = pa_context_get_source_info_list(mContext, src_callback, this);
632 plock.waitForOperation(op);
634 catch(std::exception &e) {
635 ERR("Error enumerating devices: %s\n", e.what());
640 /* Used for initial connection test and enumeration. */
641 PulseMainloop gGlobalMainloop;
644 struct PulsePlayback final : public BackendBase {
645 PulsePlayback(DeviceBase *device) noexcept : BackendBase{device} { }
646 ~PulsePlayback() override;
648 void bufferAttrCallback(pa_stream *stream) noexcept;
649 void streamStateCallback(pa_stream *stream) noexcept;
650 void streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept;
651 void sinkInfoCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept;
652 void sinkNameCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept;
653 void streamMovedCallback(pa_stream *stream) noexcept;
655 void open(std::string_view name) override;
656 bool reset() override;
657 void start() override;
658 void stop() override;
659 ClockLatency getClockLatency() override;
661 PulseMainloop mMainloop;
663 std::optional<std::string> mDeviceName{std::nullopt};
665 bool mIs51Rear{false};
666 pa_buffer_attr mAttr{};
667 pa_sample_spec mSpec{};
669 pa_stream *mStream{nullptr};
671 uint mFrameSize{0u};
674 PulsePlayback::~PulsePlayback()
675 { if(mStream) mMainloop.close(mStream); }
678 void PulsePlayback::bufferAttrCallback(pa_stream *stream) noexcept
680 /* FIXME: Update the device's UpdateSize (and/or BufferSize) using the new
681 * buffer attributes? Changing UpdateSize will change the ALC_REFRESH
682 * property, which probably shouldn't change between device resets. But
683 * leaving it alone means ALC_REFRESH will be off.
685 mAttr = *(pa_stream_get_buffer_attr(stream));
686 TRACE("minreq=%d, tlength=%d, prebuf=%d\n", mAttr.minreq, mAttr.tlength, mAttr.prebuf);
689 void PulsePlayback::streamStateCallback(pa_stream *stream) noexcept
691 if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
693 ERR("Received stream failure!\n");
694 mDevice->handleDisconnect("Playback stream failure");
696 mMainloop.signal();
699 void PulsePlayback::streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept
701 do {
702 pa_free_cb_t free_func{nullptr};
703 auto buflen = static_cast<size_t>(-1);
704 void *buf{};
705 if(pa_stream_begin_write(stream, &buf, &buflen) || !buf) UNLIKELY
707 buflen = nbytes;
708 buf = pa_xmalloc(buflen);
709 free_func = pa_xfree;
711 else
712 buflen = std::min(buflen, nbytes);
713 nbytes -= buflen;
715 mDevice->renderSamples(buf, static_cast<uint>(buflen/mFrameSize), mSpec.channels);
717 int ret{pa_stream_write(stream, buf, buflen, free_func, 0, PA_SEEK_RELATIVE)};
718 if(ret != PA_OK) UNLIKELY
719 ERR("Failed to write to stream: %d, %s\n", ret, pa_strerror(ret));
720 } while(nbytes > 0);
723 void PulsePlayback::sinkInfoCallback(pa_context*, const pa_sink_info *info, int eol) noexcept
725 struct ChannelMap {
726 DevFmtChannels fmt;
727 pa_channel_map map;
728 bool is_51rear;
730 static constexpr std::array<ChannelMap,8> chanmaps{{
731 { DevFmtX714, X714ChanMap, false },
732 { DevFmtX71, X71ChanMap, false },
733 { DevFmtX61, X61ChanMap, false },
734 { DevFmtX51, X51ChanMap, false },
735 { DevFmtX51, X51RearChanMap, true },
736 { DevFmtQuad, QuadChanMap, false },
737 { DevFmtStereo, StereoChanMap, false },
738 { DevFmtMono, MonoChanMap, false }
741 if(eol)
743 mMainloop.signal();
744 return;
747 auto chaniter = std::find_if(chanmaps.cbegin(), chanmaps.cend(),
748 [info](const ChannelMap &chanmap) -> bool
749 { return pa_channel_map_superset(&info->channel_map, &chanmap.map); }
751 if(chaniter != chanmaps.cend())
753 if(!mDevice->Flags.test(ChannelsRequest))
754 mDevice->FmtChans = chaniter->fmt;
755 mIs51Rear = chaniter->is_51rear;
757 else
759 mIs51Rear = false;
760 std::array<char,PA_CHANNEL_MAP_SNPRINT_MAX> chanmap_str{};
761 pa_channel_map_snprint(chanmap_str.data(), chanmap_str.size(), &info->channel_map);
762 WARN("Failed to find format for channel map:\n %s\n", chanmap_str.data());
765 if(info->active_port)
766 TRACE("Active port: %s (%s)\n", info->active_port->name, info->active_port->description);
767 mDevice->Flags.set(DirectEar, (info->active_port
768 && strcmp(info->active_port->name, "analog-output-headphones") == 0));
771 void PulsePlayback::sinkNameCallback(pa_context*, const pa_sink_info *info, int eol) noexcept
773 if(eol)
775 mMainloop.signal();
776 return;
778 mDevice->DeviceName = info->description;
781 void PulsePlayback::streamMovedCallback(pa_stream *stream) noexcept
783 mDeviceName = pa_stream_get_device_name(stream);
784 TRACE("Stream moved to %s\n", mDeviceName->c_str());
788 void PulsePlayback::open(std::string_view name)
790 mMainloop = PulseMainloop::Create();
791 if(mMainloop.start() != 0)
792 throw al::backend_exception{al::backend_error::DeviceError,
793 "Failed to start device mainloop"};
795 const char *pulse_name{nullptr};
796 std::string_view display_name;
797 if(!name.empty())
799 if(PlaybackDevices.empty())
800 mMainloop.probePlaybackDevices();
802 auto match_name = [name](const DevMap &entry) -> bool
803 { return entry.name == name || entry.device_name == name; };
804 auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), match_name);
805 if(iter == PlaybackDevices.cend())
806 throw al::backend_exception{al::backend_error::NoDevice,
807 "Device name \"%.*s\" not found", al::sizei(name), name.data()};
809 pulse_name = iter->device_name.c_str();
810 display_name = iter->name;
813 MainloopUniqueLock plock{mMainloop};
814 plock.connectContext();
816 pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_FIX_FORMAT | PA_STREAM_FIX_RATE |
817 PA_STREAM_FIX_CHANNELS};
818 if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
819 flags |= PA_STREAM_DONT_MOVE;
821 pa_sample_spec spec{};
822 spec.format = PA_SAMPLE_S16NE;
823 spec.rate = 44100;
824 spec.channels = 2;
826 if(!pulse_name)
828 static const auto defname = al::getenv("ALSOFT_PULSE_DEFAULT");
829 if(defname) pulse_name = defname->c_str();
831 TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)");
832 mStream = plock.connectStream(pulse_name, flags, nullptr, &spec, nullptr,
833 BackendType::Playback);
835 constexpr auto move_callback = [](pa_stream *stream, void *pdata) noexcept
836 { return static_cast<PulsePlayback*>(pdata)->streamMovedCallback(stream); };
837 pa_stream_set_moved_callback(mStream, move_callback, this);
838 mFrameSize = static_cast<uint>(pa_frame_size(pa_stream_get_sample_spec(mStream)));
840 if(pulse_name) mDeviceName.emplace(pulse_name);
841 else mDeviceName.reset();
842 if(display_name.empty())
844 auto name_callback = [](pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept
845 { return static_cast<PulsePlayback*>(pdata)->sinkNameCallback(context, info, eol); };
846 pa_operation *op{pa_context_get_sink_info_by_name(mMainloop.getContext(),
847 pa_stream_get_device_name(mStream), name_callback, this)};
848 plock.waitForOperation(op);
850 else
851 mDevice->DeviceName = display_name;
854 bool PulsePlayback::reset()
856 MainloopUniqueLock plock{mMainloop};
857 const auto deviceName = mDeviceName ? mDeviceName->c_str() : nullptr;
859 if(mStream)
861 pa_stream_set_state_callback(mStream, nullptr, nullptr);
862 pa_stream_set_moved_callback(mStream, nullptr, nullptr);
863 pa_stream_set_write_callback(mStream, nullptr, nullptr);
864 pa_stream_set_buffer_attr_callback(mStream, nullptr, nullptr);
865 pa_stream_disconnect(mStream);
866 pa_stream_unref(mStream);
867 mStream = nullptr;
870 auto info_cb = [](pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept
871 { return static_cast<PulsePlayback*>(pdata)->sinkInfoCallback(context, info, eol); };
872 pa_operation *op{pa_context_get_sink_info_by_name(mMainloop.getContext(), deviceName, info_cb,
873 this)};
874 plock.waitForOperation(op);
876 pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_INTERPOLATE_TIMING |
877 PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_EARLY_REQUESTS};
878 if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
879 flags |= PA_STREAM_DONT_MOVE;
880 if(GetConfigValueBool(mDevice->DeviceName, "pulse", "adjust-latency", false))
882 /* ADJUST_LATENCY can't be specified with EARLY_REQUESTS, for some
883 * reason. So if the user wants to adjust the overall device latency,
884 * we can't ask to get write signals as soon as minreq is reached.
886 flags &= ~PA_STREAM_EARLY_REQUESTS;
887 flags |= PA_STREAM_ADJUST_LATENCY;
889 if(GetConfigValueBool(mDevice->DeviceName, "pulse", "fix-rate", false)
890 || !mDevice->Flags.test(FrequencyRequest))
891 flags |= PA_STREAM_FIX_RATE;
893 pa_channel_map chanmap{};
894 switch(mDevice->FmtChans)
896 case DevFmtMono:
897 chanmap = MonoChanMap;
898 break;
899 case DevFmtAmbi3D:
900 mDevice->FmtChans = DevFmtStereo;
901 /*fall-through*/
902 case DevFmtStereo:
903 chanmap = StereoChanMap;
904 break;
905 case DevFmtQuad:
906 chanmap = QuadChanMap;
907 break;
908 case DevFmtX51:
909 chanmap = (mIs51Rear ? X51RearChanMap : X51ChanMap);
910 break;
911 case DevFmtX61:
912 chanmap = X61ChanMap;
913 break;
914 case DevFmtX71:
915 case DevFmtX3D71:
916 chanmap = X71ChanMap;
917 break;
918 case DevFmtX7144:
919 mDevice->FmtChans = DevFmtX714;
920 /*fall-through*/
921 case DevFmtX714:
922 chanmap = X714ChanMap;
923 break;
925 setDefaultWFXChannelOrder();
927 switch(mDevice->FmtType)
929 case DevFmtByte:
930 mDevice->FmtType = DevFmtUByte;
931 /* fall-through */
932 case DevFmtUByte:
933 mSpec.format = PA_SAMPLE_U8;
934 break;
935 case DevFmtUShort:
936 mDevice->FmtType = DevFmtShort;
937 /* fall-through */
938 case DevFmtShort:
939 mSpec.format = PA_SAMPLE_S16NE;
940 break;
941 case DevFmtUInt:
942 mDevice->FmtType = DevFmtInt;
943 /* fall-through */
944 case DevFmtInt:
945 mSpec.format = PA_SAMPLE_S32NE;
946 break;
947 case DevFmtFloat:
948 mSpec.format = PA_SAMPLE_FLOAT32NE;
949 break;
951 mSpec.rate = mDevice->Frequency;
952 mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
953 if(pa_sample_spec_valid(&mSpec) == 0)
954 throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample spec"};
956 const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
957 mAttr.maxlength = ~0u;
958 mAttr.tlength = mDevice->BufferSize * frame_size;
959 mAttr.prebuf = 0u;
960 mAttr.minreq = mDevice->UpdateSize * frame_size;
961 mAttr.fragsize = ~0u;
963 mStream = plock.connectStream(deviceName, flags, &mAttr, &mSpec, &chanmap,
964 BackendType::Playback);
966 constexpr auto state_callback = [](pa_stream *stream, void *pdata) noexcept
967 { return static_cast<PulsePlayback*>(pdata)->streamStateCallback(stream); };
968 pa_stream_set_state_callback(mStream, state_callback, this);
970 constexpr auto move_callback = [](pa_stream *stream, void *pdata) noexcept
971 { return static_cast<PulsePlayback*>(pdata)->streamMovedCallback(stream); };
972 pa_stream_set_moved_callback(mStream, move_callback, this);
974 mSpec = *(pa_stream_get_sample_spec(mStream));
975 mFrameSize = static_cast<uint>(pa_frame_size(&mSpec));
977 if(mDevice->Frequency != mSpec.rate)
979 /* Server updated our playback rate, so modify the buffer attribs
980 * accordingly.
982 const auto scale = static_cast<double>(mSpec.rate) / mDevice->Frequency;
983 const auto perlen = std::clamp(std::round(scale*mDevice->UpdateSize), 64.0, 8192.0);
984 const auto bufmax = uint{std::numeric_limits<int>::max()} / mFrameSize;
985 const auto buflen = std::clamp(std::round(scale*mDevice->BufferSize), perlen*2.0,
986 static_cast<double>(bufmax));
988 mAttr.maxlength = ~0u;
989 mAttr.tlength = static_cast<uint>(buflen) * mFrameSize;
990 mAttr.prebuf = 0u;
991 mAttr.minreq = static_cast<uint>(perlen) * mFrameSize;
993 op = pa_stream_set_buffer_attr(mStream, &mAttr, &PulseMainloop::streamSuccessCallbackC,
994 &mMainloop);
995 plock.waitForOperation(op);
997 mDevice->Frequency = mSpec.rate;
1000 constexpr auto attr_callback = [](pa_stream *stream, void *pdata) noexcept
1001 { return static_cast<PulsePlayback*>(pdata)->bufferAttrCallback(stream); };
1002 pa_stream_set_buffer_attr_callback(mStream, attr_callback, this);
1003 bufferAttrCallback(mStream);
1005 mDevice->BufferSize = mAttr.tlength / mFrameSize;
1006 mDevice->UpdateSize = mAttr.minreq / mFrameSize;
1008 return true;
1011 void PulsePlayback::start()
1013 MainloopUniqueLock plock{mMainloop};
1015 /* Write some samples to fill the buffer before we start feeding it newly
1016 * mixed samples.
1018 if(size_t todo{pa_stream_writable_size(mStream)})
1020 void *buf{pa_xmalloc(todo)};
1021 mDevice->renderSamples(buf, static_cast<uint>(todo/mFrameSize), mSpec.channels);
1022 pa_stream_write(mStream, buf, todo, pa_xfree, 0, PA_SEEK_RELATIVE);
1025 constexpr auto stream_write = [](pa_stream *stream, size_t nbytes, void *pdata) noexcept
1026 { return static_cast<PulsePlayback*>(pdata)->streamWriteCallback(stream, nbytes); };
1027 pa_stream_set_write_callback(mStream, stream_write, this);
1028 pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
1029 &mMainloop)};
1031 plock.waitForOperation(op);
1034 void PulsePlayback::stop()
1036 MainloopUniqueLock plock{mMainloop};
1038 pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
1039 &mMainloop)};
1040 plock.waitForOperation(op);
1041 pa_stream_set_write_callback(mStream, nullptr, nullptr);
1045 ClockLatency PulsePlayback::getClockLatency()
1047 ClockLatency ret{};
1048 pa_usec_t latency{};
1049 int neg{}, err{};
1052 MainloopUniqueLock plock{mMainloop};
1053 ret.ClockTime = mDevice->getClockTime();
1054 err = pa_stream_get_latency(mStream, &latency, &neg);
1057 if(err != 0) UNLIKELY
1059 /* If err = -PA_ERR_NODATA, it means we were called too soon after
1060 * starting the stream and no timing info has been received from the
1061 * server yet. Give a generic value since nothing better is available.
1063 if(err != -PA_ERR_NODATA)
1064 ERR("Failed to get stream latency: 0x%x\n", err);
1065 latency = mDevice->BufferSize - mDevice->UpdateSize;
1066 neg = 0;
1068 else if(neg) UNLIKELY
1069 latency = 0;
1070 ret.Latency = std::chrono::microseconds{latency};
1072 return ret;
1076 struct PulseCapture final : public BackendBase {
1077 PulseCapture(DeviceBase *device) noexcept : BackendBase{device} { }
1078 ~PulseCapture() override;
1080 void streamStateCallback(pa_stream *stream) noexcept;
1081 void sourceNameCallback(pa_context *context, const pa_source_info *info, int eol) noexcept;
1082 void streamMovedCallback(pa_stream *stream) noexcept;
1084 void open(std::string_view name) override;
1085 void start() override;
1086 void stop() override;
1087 void captureSamples(std::byte *buffer, uint samples) override;
1088 uint availableSamples() override;
1089 ClockLatency getClockLatency() override;
1091 PulseMainloop mMainloop;
1093 std::optional<std::string> mDeviceName{std::nullopt};
1095 al::span<const std::byte> mCapBuffer;
1096 size_t mHoleLength{0};
1097 size_t mPacketLength{0};
1099 uint mLastReadable{0u};
1100 std::byte mSilentVal{};
1102 pa_buffer_attr mAttr{};
1103 pa_sample_spec mSpec{};
1105 pa_stream *mStream{nullptr};
1108 PulseCapture::~PulseCapture()
1109 { if(mStream) mMainloop.close(mStream); }
1112 void PulseCapture::streamStateCallback(pa_stream *stream) noexcept
1114 if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
1116 ERR("Received stream failure!\n");
1117 mDevice->handleDisconnect("Capture stream failure");
1119 mMainloop.signal();
1122 void PulseCapture::sourceNameCallback(pa_context*, const pa_source_info *info, int eol) noexcept
1124 if(eol)
1126 mMainloop.signal();
1127 return;
1129 mDevice->DeviceName = info->description;
1132 void PulseCapture::streamMovedCallback(pa_stream *stream) noexcept
1134 mDeviceName = pa_stream_get_device_name(stream);
1135 TRACE("Stream moved to %s\n", mDeviceName->c_str());
1139 void PulseCapture::open(std::string_view name)
1141 if(!mMainloop)
1143 mMainloop = PulseMainloop::Create();
1144 if(mMainloop.start() != 0)
1145 throw al::backend_exception{al::backend_error::DeviceError,
1146 "Failed to start device mainloop"};
1149 const char *pulse_name{nullptr};
1150 if(!name.empty())
1152 if(CaptureDevices.empty())
1153 mMainloop.probeCaptureDevices();
1155 auto match_name = [name](const DevMap &entry) -> bool
1156 { return entry.name == name || entry.device_name == name; };
1157 auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), match_name);
1158 if(iter == CaptureDevices.cend())
1159 throw al::backend_exception{al::backend_error::NoDevice,
1160 "Device name \"%.*s\" not found", al::sizei(name), name.data()};
1162 pulse_name = iter->device_name.c_str();
1163 mDevice->DeviceName = iter->name;
1166 MainloopUniqueLock plock{mMainloop};
1167 plock.connectContext();
1169 pa_channel_map chanmap{};
1170 switch(mDevice->FmtChans)
1172 case DevFmtMono: chanmap = MonoChanMap; break;
1173 case DevFmtStereo: chanmap = StereoChanMap; break;
1174 case DevFmtQuad: chanmap = QuadChanMap; break;
1175 case DevFmtX51: chanmap = X51ChanMap; break;
1176 case DevFmtX61: chanmap = X61ChanMap; break;
1177 case DevFmtX71: chanmap = X71ChanMap; break;
1178 case DevFmtX714: chanmap = X714ChanMap; break;
1179 case DevFmtX7144:
1180 case DevFmtX3D71:
1181 case DevFmtAmbi3D:
1182 throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported",
1183 DevFmtChannelsString(mDevice->FmtChans)};
1185 setDefaultWFXChannelOrder();
1187 switch(mDevice->FmtType)
1189 case DevFmtUByte:
1190 mSilentVal = std::byte(0x80);
1191 mSpec.format = PA_SAMPLE_U8;
1192 break;
1193 case DevFmtShort:
1194 mSpec.format = PA_SAMPLE_S16NE;
1195 break;
1196 case DevFmtInt:
1197 mSpec.format = PA_SAMPLE_S32NE;
1198 break;
1199 case DevFmtFloat:
1200 mSpec.format = PA_SAMPLE_FLOAT32NE;
1201 break;
1202 case DevFmtByte:
1203 case DevFmtUShort:
1204 case DevFmtUInt:
1205 throw al::backend_exception{al::backend_error::DeviceError,
1206 "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)};
1208 mSpec.rate = mDevice->Frequency;
1209 mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
1210 if(pa_sample_spec_valid(&mSpec) == 0)
1211 throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample format"};
1213 const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
1214 const uint samples{std::max(mDevice->BufferSize, mDevice->Frequency*100u/1000u)};
1215 mAttr.minreq = ~0u;
1216 mAttr.prebuf = ~0u;
1217 mAttr.maxlength = samples * frame_size;
1218 mAttr.tlength = ~0u;
1219 mAttr.fragsize = std::min(samples, mDevice->Frequency*50u/1000u) * frame_size;
1221 pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_ADJUST_LATENCY};
1222 if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
1223 flags |= PA_STREAM_DONT_MOVE;
1225 TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)");
1226 mStream = plock.connectStream(pulse_name, flags, &mAttr, &mSpec, &chanmap,
1227 BackendType::Capture);
1229 constexpr auto move_callback = [](pa_stream *stream, void *pdata) noexcept
1230 { return static_cast<PulseCapture*>(pdata)->streamMovedCallback(stream); };
1231 pa_stream_set_moved_callback(mStream, move_callback, this);
1233 constexpr auto state_callback = [](pa_stream *stream, void *pdata) noexcept
1234 { return static_cast<PulseCapture*>(pdata)->streamStateCallback(stream); };
1235 pa_stream_set_state_callback(mStream, state_callback, this);
1237 if(pulse_name) mDeviceName.emplace(pulse_name);
1238 else mDeviceName.reset();
1239 if(mDevice->DeviceName.empty())
1241 constexpr auto name_callback = [](pa_context *context, const pa_source_info *info, int eol,
1242 void *pdata) noexcept
1243 { return static_cast<PulseCapture*>(pdata)->sourceNameCallback(context, info, eol); };
1244 pa_operation *op{pa_context_get_source_info_by_name(mMainloop.getContext(),
1245 pa_stream_get_device_name(mStream), name_callback, this)};
1246 plock.waitForOperation(op);
1250 void PulseCapture::start()
1252 MainloopUniqueLock plock{mMainloop};
1253 pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
1254 &mMainloop)};
1255 plock.waitForOperation(op);
1258 void PulseCapture::stop()
1260 MainloopUniqueLock plock{mMainloop};
1261 pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
1262 &mMainloop)};
1263 plock.waitForOperation(op);
1266 void PulseCapture::captureSamples(std::byte *buffer, uint samples)
1268 al::span<std::byte> dstbuf{buffer, samples * pa_frame_size(&mSpec)};
1270 /* Capture is done in fragment-sized chunks, so we loop until we get all
1271 * that's available.
1273 mLastReadable -= static_cast<uint>(dstbuf.size());
1274 while(!dstbuf.empty())
1276 if(mHoleLength > 0) UNLIKELY
1278 const size_t rem{std::min(dstbuf.size(), mHoleLength)};
1279 std::fill_n(dstbuf.begin(), rem, mSilentVal);
1280 dstbuf = dstbuf.subspan(rem);
1281 mHoleLength -= rem;
1283 continue;
1285 if(!mCapBuffer.empty())
1287 const size_t rem{std::min(dstbuf.size(), mCapBuffer.size())};
1288 std::copy_n(mCapBuffer.begin(), rem, dstbuf.begin());
1289 dstbuf = dstbuf.subspan(rem);
1290 mCapBuffer = mCapBuffer.subspan(rem);
1292 continue;
1295 if(!mDevice->Connected.load(std::memory_order_acquire)) UNLIKELY
1296 break;
1298 MainloopUniqueLock plock{mMainloop};
1299 if(mPacketLength > 0)
1301 pa_stream_drop(mStream);
1302 mPacketLength = 0;
1305 const pa_stream_state_t state{pa_stream_get_state(mStream)};
1306 if(!PA_STREAM_IS_GOOD(state)) UNLIKELY
1308 mDevice->handleDisconnect("Bad capture state: %u", state);
1309 break;
1312 const void *capbuf{};
1313 size_t caplen{};
1314 if(pa_stream_peek(mStream, &capbuf, &caplen) < 0) UNLIKELY
1316 mDevice->handleDisconnect("Failed retrieving capture samples: %s",
1317 pa_strerror(pa_context_errno(mMainloop.getContext())));
1318 break;
1320 plock.unlock();
1322 if(caplen == 0) break;
1323 if(!capbuf) UNLIKELY
1324 mHoleLength = caplen;
1325 else
1326 mCapBuffer = {static_cast<const std::byte*>(capbuf), caplen};
1327 mPacketLength = caplen;
1329 if(!dstbuf.empty())
1330 std::fill(dstbuf.begin(), dstbuf.end(), mSilentVal);
1333 uint PulseCapture::availableSamples()
1335 size_t readable{std::max(mCapBuffer.size(), mHoleLength)};
1337 if(mDevice->Connected.load(std::memory_order_acquire))
1339 MainloopUniqueLock plock{mMainloop};
1340 size_t got{pa_stream_readable_size(mStream)};
1341 if(static_cast<ssize_t>(got) < 0) UNLIKELY
1343 const char *err{pa_strerror(static_cast<int>(got))};
1344 ERR("pa_stream_readable_size() failed: %s\n", err);
1345 mDevice->handleDisconnect("Failed getting readable size: %s", err);
1347 else
1349 /* "readable" is the number of bytes from the last packet that have
1350 * not yet been read by the caller. So add the stream's readable
1351 * size excluding the last packet (the stream size includes the
1352 * last packet until it's dropped).
1354 if(got > mPacketLength)
1355 readable += got - mPacketLength;
1359 /* Avoid uint overflow, and avoid decreasing the readable count. */
1360 readable = std::min<size_t>(readable, std::numeric_limits<uint>::max());
1361 mLastReadable = std::max(mLastReadable, static_cast<uint>(readable));
1362 return mLastReadable / static_cast<uint>(pa_frame_size(&mSpec));
1366 ClockLatency PulseCapture::getClockLatency()
1368 ClockLatency ret{};
1369 pa_usec_t latency{};
1370 int neg{}, err{};
1373 MainloopUniqueLock plock{mMainloop};
1374 ret.ClockTime = mDevice->getClockTime();
1375 err = pa_stream_get_latency(mStream, &latency, &neg);
1378 if(err != 0) UNLIKELY
1380 ERR("Failed to get stream latency: 0x%x\n", err);
1381 latency = 0;
1382 neg = 0;
1384 else if(neg) UNLIKELY
1385 latency = 0;
1386 ret.Latency = std::chrono::microseconds{latency};
1388 return ret;
1391 } // namespace
1394 bool PulseBackendFactory::init()
1396 #ifdef HAVE_DYNLOAD
1397 if(!pulse_handle)
1399 #ifdef _WIN32
1400 #define PALIB "libpulse-0.dll"
1401 #elif defined(__APPLE__) && defined(__MACH__)
1402 #define PALIB "libpulse.0.dylib"
1403 #else
1404 #define PALIB "libpulse.so.0"
1405 #endif
1406 pulse_handle = LoadLib(PALIB);
1407 if(!pulse_handle)
1409 WARN("Failed to load %s\n", PALIB);
1410 return false;
1413 std::string missing_funcs;
1414 #define LOAD_FUNC(x) do { \
1415 p##x = reinterpret_cast<decltype(p##x)>(GetSymbol(pulse_handle, #x)); \
1416 if(!(p##x)) missing_funcs += "\n" #x; \
1417 } while(0)
1418 PULSE_FUNCS(LOAD_FUNC)
1419 #undef LOAD_FUNC
1421 if(!missing_funcs.empty())
1423 WARN("Missing expected functions:%s\n", missing_funcs.c_str());
1424 CloseLib(pulse_handle);
1425 pulse_handle = nullptr;
1426 return false;
1429 #endif /* HAVE_DYNLOAD */
1431 pulse_ctx_flags = PA_CONTEXT_NOFLAGS;
1432 if(!GetConfigValueBool({}, "pulse", "spawn-server", false))
1433 pulse_ctx_flags |= PA_CONTEXT_NOAUTOSPAWN;
1435 try {
1436 if(!gGlobalMainloop)
1438 gGlobalMainloop = PulseMainloop::Create();
1439 if(gGlobalMainloop.start() != 0)
1441 gGlobalMainloop = nullptr;
1442 return false;
1446 MainloopUniqueLock plock{gGlobalMainloop};
1447 plock.connectContext();
1448 plock.setEventHandler();
1449 return true;
1451 catch(...) {
1452 return false;
1456 bool PulseBackendFactory::querySupport(BackendType type)
1457 { return type == BackendType::Playback || type == BackendType::Capture; }
1459 auto PulseBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
1461 std::vector<std::string> outnames;
1463 auto add_device = [&outnames](const DevMap &entry) -> void
1464 { outnames.push_back(entry.name); };
1466 switch(type)
1468 case BackendType::Playback:
1469 gGlobalMainloop.probePlaybackDevices();
1470 outnames.reserve(PlaybackDevices.size());
1471 std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
1472 break;
1474 case BackendType::Capture:
1475 gGlobalMainloop.probeCaptureDevices();
1476 outnames.reserve(CaptureDevices.size());
1477 std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
1478 break;
1481 return outnames;
1484 BackendPtr PulseBackendFactory::createBackend(DeviceBase *device, BackendType type)
1486 if(type == BackendType::Playback)
1487 return BackendPtr{new PulsePlayback{device}};
1488 if(type == BackendType::Capture)
1489 return BackendPtr{new PulseCapture{device}};
1490 return nullptr;
1493 BackendFactory &PulseBackendFactory::getFactory()
1495 static PulseBackendFactory factory{};
1496 return factory;
1499 alc::EventSupport PulseBackendFactory::queryEventSupport(alc::EventType eventType, BackendType)
1501 switch(eventType)
1503 case alc::EventType::DeviceAdded:
1504 case alc::EventType::DeviceRemoved:
1505 return alc::EventSupport::FullSupport;
1507 case alc::EventType::DefaultDeviceChanged:
1508 case alc::EventType::Count:
1509 break;
1511 return alc::EventSupport::NoSupport;