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
24 #include "pulseaudio.h"
40 #include <string_view>
41 #include <sys/types.h>
45 #include "alc/alconfig.h"
49 #include "core/devformat.h"
50 #include "core/device.h"
51 #include "core/logging.h"
53 #include "opthelpers.h"
56 #include <pulse/pulseaudio.h>
61 using uint
= unsigned int;
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); \
133 #define MAKE_FUNC(x) decltype(x) * p##x
134 PULSE_FUNCS(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 */
208 constexpr pa_channel_map MonoChanMap
{
209 1, {PA_CHANNEL_POSITION_MONO
}
211 2, {PA_CHANNEL_POSITION_FRONT_LEFT
, PA_CHANNEL_POSITION_FRONT_RIGHT
}
214 PA_CHANNEL_POSITION_FRONT_LEFT
, PA_CHANNEL_POSITION_FRONT_RIGHT
,
215 PA_CHANNEL_POSITION_REAR_LEFT
, PA_CHANNEL_POSITION_REAR_RIGHT
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
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
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
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
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 /* NOLINTBEGIN(*EnumCastOutOfRange) *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
)
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
);
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
)
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
)); }
281 /* NOLINTEND(*EnumCastOutOfRange) */
286 std::string device_name
;
289 bool checkName(const al::span
<const DevMap
> list
, const std::string
&name
)
291 auto match_name
= [&name
](const DevMap
&entry
) -> bool { return entry
.name
== name
; };
292 return std::find_if(list
.cbegin(), list
.cend(), match_name
) != list
.cend();
295 std::vector
<DevMap
> PlaybackDevices
;
296 std::vector
<DevMap
> CaptureDevices
;
299 /* Global flags and properties */
300 pa_context_flags_t pulse_ctx_flags
;
302 class PulseMainloop
{
303 pa_threaded_mainloop
*mLoop
{};
304 pa_context
*mContext
{};
307 PulseMainloop() = default;
308 PulseMainloop(const PulseMainloop
&) = delete;
309 PulseMainloop(PulseMainloop
&& rhs
) noexcept
: mLoop
{rhs
.mLoop
} { rhs
.mLoop
= nullptr; }
310 explicit PulseMainloop(pa_threaded_mainloop
*loop
) noexcept
: mLoop
{loop
} { }
313 PulseMainloop
& operator=(const PulseMainloop
&) = delete;
314 PulseMainloop
& operator=(PulseMainloop
&& rhs
) noexcept
315 { std::swap(mLoop
, rhs
.mLoop
); return *this; }
316 PulseMainloop
& operator=(std::nullptr_t
) noexcept
319 pa_threaded_mainloop_free(mLoop
);
324 explicit operator bool() const noexcept
{ return mLoop
!= nullptr; }
327 auto start() const { return pa_threaded_mainloop_start(mLoop
); }
328 auto stop() const { return pa_threaded_mainloop_stop(mLoop
); }
330 [[nodiscard
]] auto getApi() const { return pa_threaded_mainloop_get_api(mLoop
); }
331 [[nodiscard
]] auto getContext() const noexcept
{ return mContext
; }
333 auto lock() const { return pa_threaded_mainloop_lock(mLoop
); }
334 auto unlock() const { return pa_threaded_mainloop_unlock(mLoop
); }
336 auto signal(bool wait
=false) const { return pa_threaded_mainloop_signal(mLoop
, wait
); }
338 static auto Create() { return PulseMainloop
{pa_threaded_mainloop_new()}; }
341 void streamSuccessCallback(pa_stream
*, int) const noexcept
{ signal(); }
342 static void streamSuccessCallbackC(pa_stream
*stream
, int success
, void *pdata
) noexcept
343 { static_cast<PulseMainloop
*>(pdata
)->streamSuccessCallback(stream
, success
); }
345 void close(pa_stream
*stream
=nullptr);
348 void deviceSinkCallback(pa_context
*, const pa_sink_info
*info
, int eol
) const noexcept
356 /* Skip this device is if it's already in the list. */
357 auto match_devname
= [info
](const DevMap
&entry
) -> bool
358 { return entry
.device_name
== info
->name
; };
359 if(std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), match_devname
) != PlaybackDevices
.cend())
362 /* Make sure the display name (description) is unique. Append a number
366 std::string newname
{info
->description
};
367 while(checkName(PlaybackDevices
, newname
))
369 newname
= info
->description
;
371 newname
+= std::to_string(++count
);
373 PlaybackDevices
.emplace_back(DevMap
{std::move(newname
), info
->name
});
374 DevMap
&newentry
= PlaybackDevices
.back();
376 TRACE("Got device \"%s\", \"%s\"\n", newentry
.name
.c_str(), newentry
.device_name
.c_str());
379 void deviceSourceCallback(pa_context
*, const pa_source_info
*info
, int eol
) const noexcept
387 /* Skip this device is if it's already in the list. */
388 auto match_devname
= [info
](const DevMap
&entry
) -> bool
389 { return entry
.device_name
== info
->name
; };
390 if(std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(), match_devname
) != CaptureDevices
.cend())
393 /* Make sure the display name (description) is unique. Append a number
397 std::string newname
{info
->description
};
398 while(checkName(CaptureDevices
, newname
))
400 newname
= info
->description
;
402 newname
+= std::to_string(++count
);
404 CaptureDevices
.emplace_back(DevMap
{std::move(newname
), info
->name
});
405 DevMap
&newentry
= CaptureDevices
.back();
407 TRACE("Got device \"%s\", \"%s\"\n", newentry
.name
.c_str(), newentry
.device_name
.c_str());
410 void probePlaybackDevices();
411 void probeCaptureDevices();
413 friend struct MainloopUniqueLock
;
415 struct MainloopUniqueLock
: public std::unique_lock
<PulseMainloop
> {
416 using std::unique_lock
<PulseMainloop
>::unique_lock
;
417 MainloopUniqueLock
& operator=(MainloopUniqueLock
&&) = default;
419 auto wait() const -> void
420 { pa_threaded_mainloop_wait(mutex()->mLoop
); }
422 template<typename Predicate
>
423 auto wait(Predicate done_waiting
) const -> void
424 { while(!done_waiting()) wait(); }
426 void waitForOperation(pa_operation
*op
) const
430 wait([op
]{ return pa_operation_get_state(op
) != PA_OPERATION_RUNNING
; });
431 pa_operation_unref(op
);
436 void setEventHandler()
438 pa_operation
*op
{pa_context_subscribe(mutex()->mContext
,
439 PA_SUBSCRIPTION_MASK_SINK
| PA_SUBSCRIPTION_MASK_SOURCE
,
440 [](pa_context
*, int, void *pdata
) noexcept
441 { static_cast<PulseMainloop
*>(pdata
)->signal(); },
443 waitForOperation(op
);
445 /* Watch for device added/removed events.
447 * TODO: Also track the "default" device, in as much as PulseAudio has
448 * the concept of a default device (whatever device is opened when not
449 * specifying a specific sink or source name). There doesn't seem to be
452 auto handler
= [](pa_context
*, pa_subscription_event_type_t t
, uint32_t, void*) noexcept
454 const auto eventFacility
= (t
& PA_SUBSCRIPTION_EVENT_FACILITY_MASK
);
455 if(eventFacility
== PA_SUBSCRIPTION_EVENT_SINK
456 || eventFacility
== PA_SUBSCRIPTION_EVENT_SOURCE
)
458 const auto deviceType
= (eventFacility
== PA_SUBSCRIPTION_EVENT_SINK
)
459 ? alc::DeviceType::Playback
: alc::DeviceType::Capture
;
460 const auto eventType
= (t
& PA_SUBSCRIPTION_EVENT_TYPE_MASK
);
461 if(eventType
== PA_SUBSCRIPTION_EVENT_NEW
)
462 alc::Event(alc::EventType::DeviceAdded
, deviceType
, "Device added");
463 else if(eventType
== PA_SUBSCRIPTION_EVENT_REMOVE
)
464 alc::Event(alc::EventType::DeviceRemoved
, deviceType
, "Device removed");
467 pa_context_set_subscribe_callback(mutex()->mContext
, handler
, nullptr);
471 void contextStateCallback(pa_context
*context
) noexcept
473 pa_context_state_t state
{pa_context_get_state(context
)};
474 if(state
== PA_CONTEXT_READY
|| !PA_CONTEXT_IS_GOOD(state
))
478 void streamStateCallback(pa_stream
*stream
) noexcept
480 pa_stream_state_t state
{pa_stream_get_state(stream
)};
481 if(state
== PA_STREAM_READY
|| !PA_STREAM_IS_GOOD(state
))
485 void connectContext();
486 pa_stream
*connectStream(const char *device_name
, pa_stream_flags_t flags
,
487 pa_buffer_attr
*attr
, pa_sample_spec
*spec
, pa_channel_map
*chanmap
, BackendType type
);
489 using MainloopLockGuard
= std::lock_guard
<PulseMainloop
>;
491 PulseMainloop::~PulseMainloop()
495 MainloopUniqueLock looplock
{*this};
496 pa_context_disconnect(mContext
);
497 pa_context_unref(mContext
);
500 pa_threaded_mainloop_free(mLoop
);
504 void MainloopUniqueLock::connectContext()
506 if(mutex()->mContext
)
509 mutex()->mContext
= pa_context_new(mutex()->getApi(), nullptr);
510 if(!mutex()->mContext
) throw al::backend_exception
{al::backend_error::OutOfMemory
,
511 "pa_context_new() failed"};
513 pa_context_set_state_callback(mutex()->mContext
, [](pa_context
*ctx
, void *pdata
) noexcept
514 { return static_cast<MainloopUniqueLock
*>(pdata
)->contextStateCallback(ctx
); }, this);
516 int err
{pa_context_connect(mutex()->mContext
, nullptr, pulse_ctx_flags
, nullptr)};
521 pa_context_state_t state
{pa_context_get_state(mutex()->mContext
)};
522 if(!PA_CONTEXT_IS_GOOD(state
))
524 err
= pa_context_errno(mutex()->mContext
);
525 if(err
> 0) err
= -err
;
528 return state
== PA_CONTEXT_READY
;
531 pa_context_set_state_callback(mutex()->mContext
, nullptr, nullptr);
535 pa_context_unref(mutex()->mContext
);
536 mutex()->mContext
= nullptr;
537 throw al::backend_exception
{al::backend_error::DeviceError
, "Context did not connect (%s)",
542 pa_stream
*MainloopUniqueLock::connectStream(const char *device_name
, pa_stream_flags_t flags
,
543 pa_buffer_attr
*attr
, pa_sample_spec
*spec
, pa_channel_map
*chanmap
, BackendType type
)
545 const char *stream_id
{(type
==BackendType::Playback
) ? "Playback Stream" : "Capture Stream"};
546 pa_stream
*stream
{pa_stream_new(mutex()->mContext
, stream_id
, spec
, chanmap
)};
548 throw al::backend_exception
{al::backend_error::OutOfMemory
, "pa_stream_new() failed (%s)",
549 pa_strerror(pa_context_errno(mutex()->mContext
))};
551 pa_stream_set_state_callback(stream
, [](pa_stream
*strm
, void *pdata
) noexcept
552 { return static_cast<MainloopUniqueLock
*>(pdata
)->streamStateCallback(strm
); }, this);
554 int err
{(type
==BackendType::Playback
) ?
555 pa_stream_connect_playback(stream
, device_name
, attr
, flags
, nullptr, nullptr) :
556 pa_stream_connect_record(stream
, device_name
, attr
, flags
)};
559 pa_stream_unref(stream
);
560 throw al::backend_exception
{al::backend_error::DeviceError
, "%s did not connect (%s)",
561 stream_id
, pa_strerror(err
)};
564 wait([&err
,stream
,stream_id
,this]()
566 pa_stream_state_t state
{pa_stream_get_state(stream
)};
567 if(!PA_STREAM_IS_GOOD(state
))
569 err
= pa_context_errno(mutex()->mContext
);
570 pa_stream_unref(stream
);
571 throw al::backend_exception
{al::backend_error::DeviceError
,
572 "%s did not get ready (%s)", stream_id
, pa_strerror(err
)};
574 return state
== PA_STREAM_READY
;
577 pa_stream_set_state_callback(stream
, nullptr, nullptr);
582 void PulseMainloop::close(pa_stream
*stream
)
587 MainloopUniqueLock looplock
{*this};
588 pa_stream_set_state_callback(stream
, nullptr, nullptr);
589 pa_stream_set_moved_callback(stream
, nullptr, nullptr);
590 pa_stream_set_write_callback(stream
, nullptr, nullptr);
591 pa_stream_set_buffer_attr_callback(stream
, nullptr, nullptr);
592 pa_stream_disconnect(stream
);
593 pa_stream_unref(stream
);
597 void PulseMainloop::probePlaybackDevices()
599 PlaybackDevices
.clear();
601 MainloopUniqueLock plock
{*this};
602 plock
.connectContext();
604 auto sink_callback
= [](pa_context
*ctx
, const pa_sink_info
*info
, int eol
, void *pdata
) noexcept
605 { return static_cast<PulseMainloop
*>(pdata
)->deviceSinkCallback(ctx
, info
, eol
); };
607 pa_operation
*op
{pa_context_get_sink_info_by_name(mContext
, nullptr, sink_callback
, this)};
608 plock
.waitForOperation(op
);
610 op
= pa_context_get_sink_info_list(mContext
, sink_callback
, this);
611 plock
.waitForOperation(op
);
613 catch(std::exception
&e
) {
614 ERR("Error enumerating devices: %s\n", e
.what());
618 void PulseMainloop::probeCaptureDevices()
620 CaptureDevices
.clear();
622 MainloopUniqueLock plock
{*this};
623 plock
.connectContext();
625 auto src_callback
= [](pa_context
*ctx
, const pa_source_info
*info
, int eol
, void *pdata
) noexcept
626 { return static_cast<PulseMainloop
*>(pdata
)->deviceSourceCallback(ctx
, info
, eol
); };
628 pa_operation
*op
{pa_context_get_source_info_by_name(mContext
, nullptr, src_callback
,
630 plock
.waitForOperation(op
);
632 op
= pa_context_get_source_info_list(mContext
, src_callback
, this);
633 plock
.waitForOperation(op
);
635 catch(std::exception
&e
) {
636 ERR("Error enumerating devices: %s\n", e
.what());
641 /* Used for initial connection test and enumeration. */
642 PulseMainloop gGlobalMainloop
;
645 struct PulsePlayback final
: public BackendBase
{
646 PulsePlayback(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
647 ~PulsePlayback() override
;
649 void bufferAttrCallback(pa_stream
*stream
) noexcept
;
650 void streamStateCallback(pa_stream
*stream
) noexcept
;
651 void streamWriteCallback(pa_stream
*stream
, size_t nbytes
) noexcept
;
652 void sinkInfoCallback(pa_context
*context
, const pa_sink_info
*info
, int eol
) noexcept
;
653 void sinkNameCallback(pa_context
*context
, const pa_sink_info
*info
, int eol
) noexcept
;
654 void streamMovedCallback(pa_stream
*stream
) noexcept
;
656 void open(std::string_view name
) override
;
657 bool reset() override
;
658 void start() override
;
659 void stop() override
;
660 ClockLatency
getClockLatency() override
;
662 PulseMainloop mMainloop
;
664 std::optional
<std::string
> mDeviceId
{std::nullopt
};
666 bool mIs51Rear
{false};
667 pa_buffer_attr mAttr
{};
668 pa_sample_spec mSpec
{};
670 pa_stream
*mStream
{nullptr};
675 PulsePlayback::~PulsePlayback()
676 { if(mStream
) mMainloop
.close(mStream
); }
679 void PulsePlayback::bufferAttrCallback(pa_stream
*stream
) noexcept
681 /* FIXME: Update the device's UpdateSize (and/or BufferSize) using the new
682 * buffer attributes? Changing UpdateSize will change the ALC_REFRESH
683 * property, which probably shouldn't change between device resets. But
684 * leaving it alone means ALC_REFRESH will be off.
686 mAttr
= *(pa_stream_get_buffer_attr(stream
));
687 TRACE("minreq=%d, tlength=%d, prebuf=%d\n", mAttr
.minreq
, mAttr
.tlength
, mAttr
.prebuf
);
690 void PulsePlayback::streamStateCallback(pa_stream
*stream
) noexcept
692 if(pa_stream_get_state(stream
) == PA_STREAM_FAILED
)
694 ERR("Received stream failure!\n");
695 mDevice
->handleDisconnect("Playback stream failure");
700 void PulsePlayback::streamWriteCallback(pa_stream
*stream
, size_t nbytes
) noexcept
703 pa_free_cb_t free_func
{nullptr};
704 auto buflen
= static_cast<size_t>(-1);
706 if(pa_stream_begin_write(stream
, &buf
, &buflen
) || !buf
) UNLIKELY
709 buf
= pa_xmalloc(buflen
);
710 free_func
= pa_xfree
;
713 buflen
= std::min(buflen
, nbytes
);
716 mDevice
->renderSamples(buf
, static_cast<uint
>(buflen
/mFrameSize
), mSpec
.channels
);
718 int ret
{pa_stream_write(stream
, buf
, buflen
, free_func
, 0, PA_SEEK_RELATIVE
)};
719 if(ret
!= PA_OK
) UNLIKELY
720 ERR("Failed to write to stream: %d, %s\n", ret
, pa_strerror(ret
));
724 void PulsePlayback::sinkInfoCallback(pa_context
*, const pa_sink_info
*info
, int eol
) noexcept
731 static constexpr std::array
<ChannelMap
,8> chanmaps
{{
732 { DevFmtX714
, X714ChanMap
, false },
733 { DevFmtX71
, X71ChanMap
, false },
734 { DevFmtX61
, X61ChanMap
, false },
735 { DevFmtX51
, X51ChanMap
, false },
736 { DevFmtX51
, X51RearChanMap
, true },
737 { DevFmtQuad
, QuadChanMap
, false },
738 { DevFmtStereo
, StereoChanMap
, false },
739 { DevFmtMono
, MonoChanMap
, false }
748 auto chaniter
= std::find_if(chanmaps
.cbegin(), chanmaps
.cend(),
749 [info
](const ChannelMap
&chanmap
) -> bool
750 { return pa_channel_map_superset(&info
->channel_map
, &chanmap
.map
); }
752 if(chaniter
!= chanmaps
.cend())
754 if(!mDevice
->Flags
.test(ChannelsRequest
))
755 mDevice
->FmtChans
= chaniter
->fmt
;
756 mIs51Rear
= chaniter
->is_51rear
;
761 std::array
<char,PA_CHANNEL_MAP_SNPRINT_MAX
> chanmap_str
{};
762 pa_channel_map_snprint(chanmap_str
.data(), chanmap_str
.size(), &info
->channel_map
);
763 WARN("Failed to find format for channel map:\n %s\n", chanmap_str
.data());
766 if(info
->active_port
)
767 TRACE("Active port: %s (%s)\n", info
->active_port
->name
, info
->active_port
->description
);
768 mDevice
->Flags
.set(DirectEar
, (info
->active_port
769 && strcmp(info
->active_port
->name
, "analog-output-headphones") == 0));
772 void PulsePlayback::sinkNameCallback(pa_context
*, const pa_sink_info
*info
, int eol
) noexcept
779 mDeviceName
= info
->description
;
782 void PulsePlayback::streamMovedCallback(pa_stream
*stream
) noexcept
784 mDeviceId
= pa_stream_get_device_name(stream
);
785 TRACE("Stream moved to %s\n", mDeviceId
->c_str());
789 void PulsePlayback::open(std::string_view name
)
791 mMainloop
= PulseMainloop::Create();
792 if(mMainloop
.start() != 0)
793 throw al::backend_exception
{al::backend_error::DeviceError
,
794 "Failed to start device mainloop"};
796 const char *pulse_name
{nullptr};
797 std::string_view display_name
;
800 if(PlaybackDevices
.empty())
801 mMainloop
.probePlaybackDevices();
803 auto match_name
= [name
](const DevMap
&entry
) -> bool
804 { return entry
.name
== name
|| entry
.device_name
== name
; };
805 auto iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), match_name
);
806 if(iter
== PlaybackDevices
.cend())
807 throw al::backend_exception
{al::backend_error::NoDevice
,
808 "Device name \"%.*s\" not found", al::sizei(name
), name
.data()};
810 pulse_name
= iter
->device_name
.c_str();
811 display_name
= iter
->name
;
814 MainloopUniqueLock plock
{mMainloop
};
815 plock
.connectContext();
817 pa_stream_flags_t flags
{PA_STREAM_START_CORKED
| PA_STREAM_FIX_FORMAT
| PA_STREAM_FIX_RATE
|
818 PA_STREAM_FIX_CHANNELS
};
819 if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
820 flags
|= PA_STREAM_DONT_MOVE
;
822 pa_sample_spec spec
{};
823 spec
.format
= PA_SAMPLE_S16NE
;
829 static const auto defname
= al::getenv("ALSOFT_PULSE_DEFAULT");
830 if(defname
) pulse_name
= defname
->c_str();
832 TRACE("Connecting to \"%s\"\n", pulse_name
? pulse_name
: "(default)");
833 mStream
= plock
.connectStream(pulse_name
, flags
, nullptr, &spec
, nullptr,
834 BackendType::Playback
);
836 constexpr auto move_callback
= [](pa_stream
*stream
, void *pdata
) noexcept
837 { return static_cast<PulsePlayback
*>(pdata
)->streamMovedCallback(stream
); };
838 pa_stream_set_moved_callback(mStream
, move_callback
, this);
839 mFrameSize
= static_cast<uint
>(pa_frame_size(pa_stream_get_sample_spec(mStream
)));
841 if(pulse_name
) mDeviceId
.emplace(pulse_name
);
842 else mDeviceId
.reset();
843 if(display_name
.empty())
845 auto name_callback
= [](pa_context
*context
, const pa_sink_info
*info
, int eol
, void *pdata
) noexcept
846 { return static_cast<PulsePlayback
*>(pdata
)->sinkNameCallback(context
, info
, eol
); };
847 pa_operation
*op
{pa_context_get_sink_info_by_name(mMainloop
.getContext(),
848 pa_stream_get_device_name(mStream
), name_callback
, this)};
849 plock
.waitForOperation(op
);
852 mDeviceName
= display_name
;
855 bool PulsePlayback::reset()
857 MainloopUniqueLock plock
{mMainloop
};
858 const auto deviceName
= mDeviceId
? mDeviceId
->c_str() : nullptr;
862 pa_stream_set_state_callback(mStream
, nullptr, nullptr);
863 pa_stream_set_moved_callback(mStream
, nullptr, nullptr);
864 pa_stream_set_write_callback(mStream
, nullptr, nullptr);
865 pa_stream_set_buffer_attr_callback(mStream
, nullptr, nullptr);
866 pa_stream_disconnect(mStream
);
867 pa_stream_unref(mStream
);
871 auto info_cb
= [](pa_context
*context
, const pa_sink_info
*info
, int eol
, void *pdata
) noexcept
872 { return static_cast<PulsePlayback
*>(pdata
)->sinkInfoCallback(context
, info
, eol
); };
873 pa_operation
*op
{pa_context_get_sink_info_by_name(mMainloop
.getContext(), deviceName
, info_cb
,
875 plock
.waitForOperation(op
);
877 pa_stream_flags_t flags
{PA_STREAM_START_CORKED
| PA_STREAM_INTERPOLATE_TIMING
|
878 PA_STREAM_AUTO_TIMING_UPDATE
| PA_STREAM_EARLY_REQUESTS
};
879 if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
880 flags
|= PA_STREAM_DONT_MOVE
;
881 if(GetConfigValueBool(mDevice
->mDeviceName
, "pulse", "adjust-latency", false))
883 /* ADJUST_LATENCY can't be specified with EARLY_REQUESTS, for some
884 * reason. So if the user wants to adjust the overall device latency,
885 * we can't ask to get write signals as soon as minreq is reached.
887 flags
&= ~PA_STREAM_EARLY_REQUESTS
;
888 flags
|= PA_STREAM_ADJUST_LATENCY
;
890 if(GetConfigValueBool(mDevice
->mDeviceName
, "pulse", "fix-rate", false)
891 || !mDevice
->Flags
.test(FrequencyRequest
))
892 flags
|= PA_STREAM_FIX_RATE
;
894 pa_channel_map chanmap
{};
895 switch(mDevice
->FmtChans
)
898 chanmap
= MonoChanMap
;
901 mDevice
->FmtChans
= DevFmtStereo
;
904 chanmap
= StereoChanMap
;
907 chanmap
= QuadChanMap
;
910 chanmap
= (mIs51Rear
? X51RearChanMap
: X51ChanMap
);
913 chanmap
= X61ChanMap
;
917 chanmap
= X71ChanMap
;
920 mDevice
->FmtChans
= DevFmtX714
;
923 chanmap
= X714ChanMap
;
926 setDefaultWFXChannelOrder();
928 switch(mDevice
->FmtType
)
931 mDevice
->FmtType
= DevFmtUByte
;
934 mSpec
.format
= PA_SAMPLE_U8
;
937 mDevice
->FmtType
= DevFmtShort
;
940 mSpec
.format
= PA_SAMPLE_S16NE
;
943 mDevice
->FmtType
= DevFmtInt
;
946 mSpec
.format
= PA_SAMPLE_S32NE
;
949 mSpec
.format
= PA_SAMPLE_FLOAT32NE
;
952 mSpec
.rate
= mDevice
->Frequency
;
953 mSpec
.channels
= static_cast<uint8_t>(mDevice
->channelsFromFmt());
954 if(pa_sample_spec_valid(&mSpec
) == 0)
955 throw al::backend_exception
{al::backend_error::DeviceError
, "Invalid sample spec"};
957 const auto frame_size
= static_cast<uint
>(pa_frame_size(&mSpec
));
958 mAttr
.maxlength
= ~0u;
959 mAttr
.tlength
= mDevice
->BufferSize
* frame_size
;
961 mAttr
.minreq
= mDevice
->UpdateSize
* frame_size
;
962 mAttr
.fragsize
= ~0u;
964 mStream
= plock
.connectStream(deviceName
, flags
, &mAttr
, &mSpec
, &chanmap
,
965 BackendType::Playback
);
967 constexpr auto state_callback
= [](pa_stream
*stream
, void *pdata
) noexcept
968 { return static_cast<PulsePlayback
*>(pdata
)->streamStateCallback(stream
); };
969 pa_stream_set_state_callback(mStream
, state_callback
, this);
971 constexpr auto move_callback
= [](pa_stream
*stream
, void *pdata
) noexcept
972 { return static_cast<PulsePlayback
*>(pdata
)->streamMovedCallback(stream
); };
973 pa_stream_set_moved_callback(mStream
, move_callback
, this);
975 mSpec
= *(pa_stream_get_sample_spec(mStream
));
976 mFrameSize
= static_cast<uint
>(pa_frame_size(&mSpec
));
978 if(mDevice
->Frequency
!= mSpec
.rate
)
980 /* Server updated our playback rate, so modify the buffer attribs
983 const auto scale
= static_cast<double>(mSpec
.rate
) / mDevice
->Frequency
;
984 const auto perlen
= std::clamp(std::round(scale
*mDevice
->UpdateSize
), 64.0, 8192.0);
985 const auto bufmax
= uint
{std::numeric_limits
<int>::max()} / mFrameSize
;
986 const auto buflen
= std::clamp(std::round(scale
*mDevice
->BufferSize
), perlen
*2.0,
987 static_cast<double>(bufmax
));
989 mAttr
.maxlength
= ~0u;
990 mAttr
.tlength
= static_cast<uint
>(buflen
) * mFrameSize
;
992 mAttr
.minreq
= static_cast<uint
>(perlen
) * mFrameSize
;
994 op
= pa_stream_set_buffer_attr(mStream
, &mAttr
, &PulseMainloop::streamSuccessCallbackC
,
996 plock
.waitForOperation(op
);
998 mDevice
->Frequency
= mSpec
.rate
;
1001 constexpr auto attr_callback
= [](pa_stream
*stream
, void *pdata
) noexcept
1002 { return static_cast<PulsePlayback
*>(pdata
)->bufferAttrCallback(stream
); };
1003 pa_stream_set_buffer_attr_callback(mStream
, attr_callback
, this);
1004 bufferAttrCallback(mStream
);
1006 mDevice
->BufferSize
= mAttr
.tlength
/ mFrameSize
;
1007 mDevice
->UpdateSize
= mAttr
.minreq
/ mFrameSize
;
1012 void PulsePlayback::start()
1014 MainloopUniqueLock plock
{mMainloop
};
1016 /* Write some samples to fill the buffer before we start feeding it newly
1019 if(size_t todo
{pa_stream_writable_size(mStream
)})
1021 void *buf
{pa_xmalloc(todo
)};
1022 mDevice
->renderSamples(buf
, static_cast<uint
>(todo
/mFrameSize
), mSpec
.channels
);
1023 pa_stream_write(mStream
, buf
, todo
, pa_xfree
, 0, PA_SEEK_RELATIVE
);
1026 constexpr auto stream_write
= [](pa_stream
*stream
, size_t nbytes
, void *pdata
) noexcept
1027 { return static_cast<PulsePlayback
*>(pdata
)->streamWriteCallback(stream
, nbytes
); };
1028 pa_stream_set_write_callback(mStream
, stream_write
, this);
1029 pa_operation
*op
{pa_stream_cork(mStream
, 0, &PulseMainloop::streamSuccessCallbackC
,
1032 plock
.waitForOperation(op
);
1035 void PulsePlayback::stop()
1037 MainloopUniqueLock plock
{mMainloop
};
1039 pa_operation
*op
{pa_stream_cork(mStream
, 1, &PulseMainloop::streamSuccessCallbackC
,
1041 plock
.waitForOperation(op
);
1042 pa_stream_set_write_callback(mStream
, nullptr, nullptr);
1046 ClockLatency
PulsePlayback::getClockLatency()
1049 pa_usec_t latency
{};
1053 MainloopUniqueLock plock
{mMainloop
};
1054 ret
.ClockTime
= mDevice
->getClockTime();
1055 err
= pa_stream_get_latency(mStream
, &latency
, &neg
);
1058 if(err
!= 0) UNLIKELY
1060 /* If err = -PA_ERR_NODATA, it means we were called too soon after
1061 * starting the stream and no timing info has been received from the
1062 * server yet. Give a generic value since nothing better is available.
1064 if(err
!= -PA_ERR_NODATA
)
1065 ERR("Failed to get stream latency: 0x%x\n", err
);
1066 latency
= mDevice
->BufferSize
- mDevice
->UpdateSize
;
1069 else if(neg
) UNLIKELY
1071 ret
.Latency
= std::chrono::microseconds
{latency
};
1077 struct PulseCapture final
: public BackendBase
{
1078 PulseCapture(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
1079 ~PulseCapture() override
;
1081 void streamStateCallback(pa_stream
*stream
) noexcept
;
1082 void sourceNameCallback(pa_context
*context
, const pa_source_info
*info
, int eol
) noexcept
;
1083 void streamMovedCallback(pa_stream
*stream
) noexcept
;
1085 void open(std::string_view name
) override
;
1086 void start() override
;
1087 void stop() override
;
1088 void captureSamples(std::byte
*buffer
, uint samples
) override
;
1089 uint
availableSamples() override
;
1090 ClockLatency
getClockLatency() override
;
1092 PulseMainloop mMainloop
;
1094 std::optional
<std::string
> mDeviceId
{std::nullopt
};
1096 al::span
<const std::byte
> mCapBuffer
;
1097 size_t mHoleLength
{0};
1098 size_t mPacketLength
{0};
1100 uint mLastReadable
{0u};
1101 std::byte mSilentVal
{};
1103 pa_buffer_attr mAttr
{};
1104 pa_sample_spec mSpec
{};
1106 pa_stream
*mStream
{nullptr};
1109 PulseCapture::~PulseCapture()
1110 { if(mStream
) mMainloop
.close(mStream
); }
1113 void PulseCapture::streamStateCallback(pa_stream
*stream
) noexcept
1115 if(pa_stream_get_state(stream
) == PA_STREAM_FAILED
)
1117 ERR("Received stream failure!\n");
1118 mDevice
->handleDisconnect("Capture stream failure");
1123 void PulseCapture::sourceNameCallback(pa_context
*, const pa_source_info
*info
, int eol
) noexcept
1130 mDeviceName
= info
->description
;
1133 void PulseCapture::streamMovedCallback(pa_stream
*stream
) noexcept
1135 mDeviceId
= pa_stream_get_device_name(stream
);
1136 TRACE("Stream moved to %s\n", mDeviceId
->c_str());
1140 void PulseCapture::open(std::string_view name
)
1144 mMainloop
= PulseMainloop::Create();
1145 if(mMainloop
.start() != 0)
1146 throw al::backend_exception
{al::backend_error::DeviceError
,
1147 "Failed to start device mainloop"};
1150 const char *pulse_name
{nullptr};
1153 if(CaptureDevices
.empty())
1154 mMainloop
.probeCaptureDevices();
1156 auto match_name
= [name
](const DevMap
&entry
) -> bool
1157 { return entry
.name
== name
|| entry
.device_name
== name
; };
1158 auto iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(), match_name
);
1159 if(iter
== CaptureDevices
.cend())
1160 throw al::backend_exception
{al::backend_error::NoDevice
,
1161 "Device name \"%.*s\" not found", al::sizei(name
), name
.data()};
1163 pulse_name
= iter
->device_name
.c_str();
1164 mDeviceName
= iter
->name
;
1167 MainloopUniqueLock plock
{mMainloop
};
1168 plock
.connectContext();
1170 pa_channel_map chanmap
{};
1171 switch(mDevice
->FmtChans
)
1173 case DevFmtMono
: chanmap
= MonoChanMap
; break;
1174 case DevFmtStereo
: chanmap
= StereoChanMap
; break;
1175 case DevFmtQuad
: chanmap
= QuadChanMap
; break;
1176 case DevFmtX51
: chanmap
= X51ChanMap
; break;
1177 case DevFmtX61
: chanmap
= X61ChanMap
; break;
1178 case DevFmtX71
: chanmap
= X71ChanMap
; break;
1179 case DevFmtX714
: chanmap
= X714ChanMap
; break;
1183 throw al::backend_exception
{al::backend_error::DeviceError
, "%s capture not supported",
1184 DevFmtChannelsString(mDevice
->FmtChans
)};
1186 setDefaultWFXChannelOrder();
1188 switch(mDevice
->FmtType
)
1191 mSilentVal
= std::byte(0x80);
1192 mSpec
.format
= PA_SAMPLE_U8
;
1195 mSpec
.format
= PA_SAMPLE_S16NE
;
1198 mSpec
.format
= PA_SAMPLE_S32NE
;
1201 mSpec
.format
= PA_SAMPLE_FLOAT32NE
;
1206 throw al::backend_exception
{al::backend_error::DeviceError
,
1207 "%s capture samples not supported", DevFmtTypeString(mDevice
->FmtType
)};
1209 mSpec
.rate
= mDevice
->Frequency
;
1210 mSpec
.channels
= static_cast<uint8_t>(mDevice
->channelsFromFmt());
1211 if(pa_sample_spec_valid(&mSpec
) == 0)
1212 throw al::backend_exception
{al::backend_error::DeviceError
, "Invalid sample format"};
1214 const auto frame_size
= static_cast<uint
>(pa_frame_size(&mSpec
));
1215 const uint samples
{std::max(mDevice
->BufferSize
, mDevice
->Frequency
*100u/1000u)};
1218 mAttr
.maxlength
= samples
* frame_size
;
1219 mAttr
.tlength
= ~0u;
1220 mAttr
.fragsize
= std::min(samples
, mDevice
->Frequency
*50u/1000u) * frame_size
;
1222 pa_stream_flags_t flags
{PA_STREAM_START_CORKED
| PA_STREAM_ADJUST_LATENCY
};
1223 if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
1224 flags
|= PA_STREAM_DONT_MOVE
;
1226 TRACE("Connecting to \"%s\"\n", pulse_name
? pulse_name
: "(default)");
1227 mStream
= plock
.connectStream(pulse_name
, flags
, &mAttr
, &mSpec
, &chanmap
,
1228 BackendType::Capture
);
1230 constexpr auto move_callback
= [](pa_stream
*stream
, void *pdata
) noexcept
1231 { return static_cast<PulseCapture
*>(pdata
)->streamMovedCallback(stream
); };
1232 pa_stream_set_moved_callback(mStream
, move_callback
, this);
1234 constexpr auto state_callback
= [](pa_stream
*stream
, void *pdata
) noexcept
1235 { return static_cast<PulseCapture
*>(pdata
)->streamStateCallback(stream
); };
1236 pa_stream_set_state_callback(mStream
, state_callback
, this);
1238 if(pulse_name
) mDeviceId
.emplace(pulse_name
);
1239 else mDeviceId
.reset();
1240 if(mDeviceName
.empty())
1242 constexpr auto name_callback
= [](pa_context
*context
, const pa_source_info
*info
, int eol
,
1243 void *pdata
) noexcept
1244 { return static_cast<PulseCapture
*>(pdata
)->sourceNameCallback(context
, info
, eol
); };
1245 pa_operation
*op
{pa_context_get_source_info_by_name(mMainloop
.getContext(),
1246 pa_stream_get_device_name(mStream
), name_callback
, this)};
1247 plock
.waitForOperation(op
);
1251 void PulseCapture::start()
1253 MainloopUniqueLock plock
{mMainloop
};
1254 pa_operation
*op
{pa_stream_cork(mStream
, 0, &PulseMainloop::streamSuccessCallbackC
,
1256 plock
.waitForOperation(op
);
1259 void PulseCapture::stop()
1261 MainloopUniqueLock plock
{mMainloop
};
1262 pa_operation
*op
{pa_stream_cork(mStream
, 1, &PulseMainloop::streamSuccessCallbackC
,
1264 plock
.waitForOperation(op
);
1267 void PulseCapture::captureSamples(std::byte
*buffer
, uint samples
)
1269 al::span
<std::byte
> dstbuf
{buffer
, samples
* pa_frame_size(&mSpec
)};
1271 /* Capture is done in fragment-sized chunks, so we loop until we get all
1274 mLastReadable
-= static_cast<uint
>(dstbuf
.size());
1275 while(!dstbuf
.empty())
1277 if(mHoleLength
> 0) UNLIKELY
1279 const size_t rem
{std::min(dstbuf
.size(), mHoleLength
)};
1280 std::fill_n(dstbuf
.begin(), rem
, mSilentVal
);
1281 dstbuf
= dstbuf
.subspan(rem
);
1286 if(!mCapBuffer
.empty())
1288 const size_t rem
{std::min(dstbuf
.size(), mCapBuffer
.size())};
1289 std::copy_n(mCapBuffer
.begin(), rem
, dstbuf
.begin());
1290 dstbuf
= dstbuf
.subspan(rem
);
1291 mCapBuffer
= mCapBuffer
.subspan(rem
);
1296 if(!mDevice
->Connected
.load(std::memory_order_acquire
)) UNLIKELY
1299 MainloopUniqueLock plock
{mMainloop
};
1300 if(mPacketLength
> 0)
1302 pa_stream_drop(mStream
);
1306 const pa_stream_state_t state
{pa_stream_get_state(mStream
)};
1307 if(!PA_STREAM_IS_GOOD(state
)) UNLIKELY
1309 mDevice
->handleDisconnect("Bad capture state: %u", state
);
1313 const void *capbuf
{};
1315 if(pa_stream_peek(mStream
, &capbuf
, &caplen
) < 0) UNLIKELY
1317 mDevice
->handleDisconnect("Failed retrieving capture samples: %s",
1318 pa_strerror(pa_context_errno(mMainloop
.getContext())));
1323 if(caplen
== 0) break;
1324 if(!capbuf
) UNLIKELY
1325 mHoleLength
= caplen
;
1327 mCapBuffer
= {static_cast<const std::byte
*>(capbuf
), caplen
};
1328 mPacketLength
= caplen
;
1331 std::fill(dstbuf
.begin(), dstbuf
.end(), mSilentVal
);
1334 uint
PulseCapture::availableSamples()
1336 size_t readable
{std::max(mCapBuffer
.size(), mHoleLength
)};
1338 if(mDevice
->Connected
.load(std::memory_order_acquire
))
1340 MainloopUniqueLock plock
{mMainloop
};
1341 size_t got
{pa_stream_readable_size(mStream
)};
1342 if(static_cast<ssize_t
>(got
) < 0) UNLIKELY
1344 const char *err
{pa_strerror(static_cast<int>(got
))};
1345 ERR("pa_stream_readable_size() failed: %s\n", err
);
1346 mDevice
->handleDisconnect("Failed getting readable size: %s", err
);
1350 /* "readable" is the number of bytes from the last packet that have
1351 * not yet been read by the caller. So add the stream's readable
1352 * size excluding the last packet (the stream size includes the
1353 * last packet until it's dropped).
1355 if(got
> mPacketLength
)
1356 readable
+= got
- mPacketLength
;
1360 /* Avoid uint overflow, and avoid decreasing the readable count. */
1361 readable
= std::min
<size_t>(readable
, std::numeric_limits
<uint
>::max());
1362 mLastReadable
= std::max(mLastReadable
, static_cast<uint
>(readable
));
1363 return mLastReadable
/ static_cast<uint
>(pa_frame_size(&mSpec
));
1367 ClockLatency
PulseCapture::getClockLatency()
1370 pa_usec_t latency
{};
1374 MainloopUniqueLock plock
{mMainloop
};
1375 ret
.ClockTime
= mDevice
->getClockTime();
1376 err
= pa_stream_get_latency(mStream
, &latency
, &neg
);
1379 if(err
!= 0) UNLIKELY
1381 ERR("Failed to get stream latency: 0x%x\n", err
);
1385 else if(neg
) UNLIKELY
1387 ret
.Latency
= std::chrono::microseconds
{latency
};
1395 bool PulseBackendFactory::init()
1401 #define PALIB "libpulse-0.dll"
1402 #elif defined(__APPLE__) && defined(__MACH__)
1403 #define PALIB "libpulse.0.dylib"
1405 #define PALIB "libpulse.so.0"
1407 pulse_handle
= LoadLib(PALIB
);
1410 WARN("Failed to load %s\n", PALIB
);
1414 std::string missing_funcs
;
1415 #define LOAD_FUNC(x) do { \
1416 p##x = reinterpret_cast<decltype(p##x)>(GetSymbol(pulse_handle, #x)); \
1417 if(!(p##x)) missing_funcs += "\n" #x; \
1419 PULSE_FUNCS(LOAD_FUNC
)
1422 if(!missing_funcs
.empty())
1424 WARN("Missing expected functions:%s\n", missing_funcs
.c_str());
1425 CloseLib(pulse_handle
);
1426 pulse_handle
= nullptr;
1430 #endif /* HAVE_DYNLOAD */
1432 pulse_ctx_flags
= PA_CONTEXT_NOFLAGS
;
1433 if(!GetConfigValueBool({}, "pulse", "spawn-server", false))
1434 pulse_ctx_flags
|= PA_CONTEXT_NOAUTOSPAWN
;
1437 if(!gGlobalMainloop
)
1439 gGlobalMainloop
= PulseMainloop::Create();
1440 if(gGlobalMainloop
.start() != 0)
1442 gGlobalMainloop
= nullptr;
1447 MainloopUniqueLock plock
{gGlobalMainloop
};
1448 plock
.connectContext();
1449 plock
.setEventHandler();
1457 bool PulseBackendFactory::querySupport(BackendType type
)
1458 { return type
== BackendType::Playback
|| type
== BackendType::Capture
; }
1460 auto PulseBackendFactory::enumerate(BackendType type
) -> std::vector
<std::string
>
1462 std::vector
<std::string
> outnames
;
1464 auto add_device
= [&outnames
](const DevMap
&entry
) -> void
1465 { outnames
.push_back(entry
.name
); };
1469 case BackendType::Playback
:
1470 gGlobalMainloop
.probePlaybackDevices();
1471 outnames
.reserve(PlaybackDevices
.size());
1472 std::for_each(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), add_device
);
1475 case BackendType::Capture
:
1476 gGlobalMainloop
.probeCaptureDevices();
1477 outnames
.reserve(CaptureDevices
.size());
1478 std::for_each(CaptureDevices
.cbegin(), CaptureDevices
.cend(), add_device
);
1485 BackendPtr
PulseBackendFactory::createBackend(DeviceBase
*device
, BackendType type
)
1487 if(type
== BackendType::Playback
)
1488 return BackendPtr
{new PulsePlayback
{device
}};
1489 if(type
== BackendType::Capture
)
1490 return BackendPtr
{new PulseCapture
{device
}};
1494 BackendFactory
&PulseBackendFactory::getFactory()
1496 static PulseBackendFactory factory
{};
1500 alc::EventSupport
PulseBackendFactory::queryEventSupport(alc::EventType eventType
, BackendType
)
1504 case alc::EventType::DeviceAdded
:
1505 case alc::EventType::DeviceRemoved
:
1506 return alc::EventSupport::FullSupport
;
1508 case alc::EventType::DefaultDeviceChanged
:
1509 case alc::EventType::Count
:
1512 return alc::EventSupport::NoSupport
;