2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
36 #include <string_view>
42 #include "alc/alconfig.h"
44 #include "alnumeric.h"
46 #include "althrd_setname.h"
47 #include "core/device.h"
48 #include "core/helpers.h"
49 #include "core/logging.h"
51 #include "ringbuffer.h"
53 #include <alsa/asoundlib.h>
58 using namespace std::string_view_literals
;
60 [[nodiscard
]] constexpr auto GetDefaultName() noexcept
{ return "ALSA Default"sv
; }
64 #define ALSA_FUNCS(MAGIC) \
65 MAGIC(snd_strerror); \
66 MAGIC(snd_pcm_open); \
67 MAGIC(snd_pcm_close); \
68 MAGIC(snd_pcm_nonblock); \
69 MAGIC(snd_pcm_frames_to_bytes); \
70 MAGIC(snd_pcm_bytes_to_frames); \
71 MAGIC(snd_pcm_hw_params_malloc); \
72 MAGIC(snd_pcm_hw_params_free); \
73 MAGIC(snd_pcm_hw_params_any); \
74 MAGIC(snd_pcm_hw_params_current); \
75 MAGIC(snd_pcm_hw_params_get_access); \
76 MAGIC(snd_pcm_hw_params_get_buffer_size); \
77 MAGIC(snd_pcm_hw_params_get_buffer_time_min); \
78 MAGIC(snd_pcm_hw_params_get_buffer_time_max); \
79 MAGIC(snd_pcm_hw_params_get_channels); \
80 MAGIC(snd_pcm_hw_params_get_period_size); \
81 MAGIC(snd_pcm_hw_params_get_period_time_max); \
82 MAGIC(snd_pcm_hw_params_get_period_time_min); \
83 MAGIC(snd_pcm_hw_params_get_periods); \
84 MAGIC(snd_pcm_hw_params_set_access); \
85 MAGIC(snd_pcm_hw_params_set_buffer_size_min); \
86 MAGIC(snd_pcm_hw_params_set_buffer_size_near); \
87 MAGIC(snd_pcm_hw_params_set_buffer_time_near); \
88 MAGIC(snd_pcm_hw_params_set_channels); \
89 MAGIC(snd_pcm_hw_params_set_channels_near); \
90 MAGIC(snd_pcm_hw_params_set_format); \
91 MAGIC(snd_pcm_hw_params_set_period_time_near); \
92 MAGIC(snd_pcm_hw_params_set_period_size_near); \
93 MAGIC(snd_pcm_hw_params_set_periods_near); \
94 MAGIC(snd_pcm_hw_params_set_rate_near); \
95 MAGIC(snd_pcm_hw_params_set_rate); \
96 MAGIC(snd_pcm_hw_params_set_rate_resample); \
97 MAGIC(snd_pcm_hw_params_test_format); \
98 MAGIC(snd_pcm_hw_params_test_channels); \
99 MAGIC(snd_pcm_hw_params); \
100 MAGIC(snd_pcm_sw_params); \
101 MAGIC(snd_pcm_sw_params_current); \
102 MAGIC(snd_pcm_sw_params_free); \
103 MAGIC(snd_pcm_sw_params_malloc); \
104 MAGIC(snd_pcm_sw_params_set_avail_min); \
105 MAGIC(snd_pcm_sw_params_set_stop_threshold); \
106 MAGIC(snd_pcm_prepare); \
107 MAGIC(snd_pcm_start); \
108 MAGIC(snd_pcm_resume); \
109 MAGIC(snd_pcm_reset); \
110 MAGIC(snd_pcm_wait); \
111 MAGIC(snd_pcm_delay); \
112 MAGIC(snd_pcm_state); \
113 MAGIC(snd_pcm_avail_update); \
114 MAGIC(snd_pcm_mmap_begin); \
115 MAGIC(snd_pcm_mmap_commit); \
116 MAGIC(snd_pcm_readi); \
117 MAGIC(snd_pcm_writei); \
118 MAGIC(snd_pcm_drain); \
119 MAGIC(snd_pcm_drop); \
120 MAGIC(snd_pcm_recover); \
121 MAGIC(snd_pcm_info_malloc); \
122 MAGIC(snd_pcm_info_free); \
123 MAGIC(snd_pcm_info_set_device); \
124 MAGIC(snd_pcm_info_set_subdevice); \
125 MAGIC(snd_pcm_info_set_stream); \
126 MAGIC(snd_pcm_info_get_name); \
127 MAGIC(snd_ctl_pcm_next_device); \
128 MAGIC(snd_ctl_pcm_info); \
129 MAGIC(snd_ctl_open); \
130 MAGIC(snd_ctl_close); \
131 MAGIC(snd_ctl_card_info_malloc); \
132 MAGIC(snd_ctl_card_info_free); \
133 MAGIC(snd_ctl_card_info); \
134 MAGIC(snd_ctl_card_info_get_name); \
135 MAGIC(snd_ctl_card_info_get_id); \
136 MAGIC(snd_card_next); \
137 MAGIC(snd_config_update_free_global)
140 #define MAKE_FUNC(f) decltype(f) * p##f
141 ALSA_FUNCS(MAKE_FUNC
);
144 #ifndef IN_IDE_PARSER
145 #define snd_strerror psnd_strerror
146 #define snd_pcm_open psnd_pcm_open
147 #define snd_pcm_close psnd_pcm_close
148 #define snd_pcm_nonblock psnd_pcm_nonblock
149 #define snd_pcm_frames_to_bytes psnd_pcm_frames_to_bytes
150 #define snd_pcm_bytes_to_frames psnd_pcm_bytes_to_frames
151 #define snd_pcm_hw_params_malloc psnd_pcm_hw_params_malloc
152 #define snd_pcm_hw_params_free psnd_pcm_hw_params_free
153 #define snd_pcm_hw_params_any psnd_pcm_hw_params_any
154 #define snd_pcm_hw_params_current psnd_pcm_hw_params_current
155 #define snd_pcm_hw_params_set_access psnd_pcm_hw_params_set_access
156 #define snd_pcm_hw_params_set_format psnd_pcm_hw_params_set_format
157 #define snd_pcm_hw_params_set_channels psnd_pcm_hw_params_set_channels
158 #define snd_pcm_hw_params_set_channels_near psnd_pcm_hw_params_set_channels_near
159 #define snd_pcm_hw_params_set_periods_near psnd_pcm_hw_params_set_periods_near
160 #define snd_pcm_hw_params_set_rate_near psnd_pcm_hw_params_set_rate_near
161 #define snd_pcm_hw_params_set_rate psnd_pcm_hw_params_set_rate
162 #define snd_pcm_hw_params_set_rate_resample psnd_pcm_hw_params_set_rate_resample
163 #define snd_pcm_hw_params_set_buffer_time_near psnd_pcm_hw_params_set_buffer_time_near
164 #define snd_pcm_hw_params_set_period_time_near psnd_pcm_hw_params_set_period_time_near
165 #define snd_pcm_hw_params_set_buffer_size_near psnd_pcm_hw_params_set_buffer_size_near
166 #define snd_pcm_hw_params_set_period_size_near psnd_pcm_hw_params_set_period_size_near
167 #define snd_pcm_hw_params_set_buffer_size_min psnd_pcm_hw_params_set_buffer_size_min
168 #define snd_pcm_hw_params_get_buffer_time_min psnd_pcm_hw_params_get_buffer_time_min
169 #define snd_pcm_hw_params_get_buffer_time_max psnd_pcm_hw_params_get_buffer_time_max
170 #define snd_pcm_hw_params_get_period_time_min psnd_pcm_hw_params_get_period_time_min
171 #define snd_pcm_hw_params_get_period_time_max psnd_pcm_hw_params_get_period_time_max
172 #define snd_pcm_hw_params_get_buffer_size psnd_pcm_hw_params_get_buffer_size
173 #define snd_pcm_hw_params_get_period_size psnd_pcm_hw_params_get_period_size
174 #define snd_pcm_hw_params_get_access psnd_pcm_hw_params_get_access
175 #define snd_pcm_hw_params_get_periods psnd_pcm_hw_params_get_periods
176 #define snd_pcm_hw_params_get_channels psnd_pcm_hw_params_get_channels
177 #define snd_pcm_hw_params_test_format psnd_pcm_hw_params_test_format
178 #define snd_pcm_hw_params_test_channels psnd_pcm_hw_params_test_channels
179 #define snd_pcm_hw_params psnd_pcm_hw_params
180 #define snd_pcm_sw_params_malloc psnd_pcm_sw_params_malloc
181 #define snd_pcm_sw_params_current psnd_pcm_sw_params_current
182 #define snd_pcm_sw_params_set_avail_min psnd_pcm_sw_params_set_avail_min
183 #define snd_pcm_sw_params_set_stop_threshold psnd_pcm_sw_params_set_stop_threshold
184 #define snd_pcm_sw_params psnd_pcm_sw_params
185 #define snd_pcm_sw_params_free psnd_pcm_sw_params_free
186 #define snd_pcm_prepare psnd_pcm_prepare
187 #define snd_pcm_start psnd_pcm_start
188 #define snd_pcm_resume psnd_pcm_resume
189 #define snd_pcm_reset psnd_pcm_reset
190 #define snd_pcm_wait psnd_pcm_wait
191 #define snd_pcm_delay psnd_pcm_delay
192 #define snd_pcm_state psnd_pcm_state
193 #define snd_pcm_avail_update psnd_pcm_avail_update
194 #define snd_pcm_mmap_begin psnd_pcm_mmap_begin
195 #define snd_pcm_mmap_commit psnd_pcm_mmap_commit
196 #define snd_pcm_readi psnd_pcm_readi
197 #define snd_pcm_writei psnd_pcm_writei
198 #define snd_pcm_drain psnd_pcm_drain
199 #define snd_pcm_drop psnd_pcm_drop
200 #define snd_pcm_recover psnd_pcm_recover
201 #define snd_pcm_info_malloc psnd_pcm_info_malloc
202 #define snd_pcm_info_free psnd_pcm_info_free
203 #define snd_pcm_info_set_device psnd_pcm_info_set_device
204 #define snd_pcm_info_set_subdevice psnd_pcm_info_set_subdevice
205 #define snd_pcm_info_set_stream psnd_pcm_info_set_stream
206 #define snd_pcm_info_get_name psnd_pcm_info_get_name
207 #define snd_ctl_pcm_next_device psnd_ctl_pcm_next_device
208 #define snd_ctl_pcm_info psnd_ctl_pcm_info
209 #define snd_ctl_open psnd_ctl_open
210 #define snd_ctl_close psnd_ctl_close
211 #define snd_ctl_card_info_malloc psnd_ctl_card_info_malloc
212 #define snd_ctl_card_info_free psnd_ctl_card_info_free
213 #define snd_ctl_card_info psnd_ctl_card_info
214 #define snd_ctl_card_info_get_name psnd_ctl_card_info_get_name
215 #define snd_ctl_card_info_get_id psnd_ctl_card_info_get_id
216 #define snd_card_next psnd_card_next
217 #define snd_config_update_free_global psnd_config_update_free_global
222 struct HwParamsDeleter
{
223 void operator()(snd_pcm_hw_params_t
*ptr
) { snd_pcm_hw_params_free(ptr
); }
225 using HwParamsPtr
= std::unique_ptr
<snd_pcm_hw_params_t
,HwParamsDeleter
>;
226 HwParamsPtr
CreateHwParams()
228 snd_pcm_hw_params_t
*hp
{};
229 snd_pcm_hw_params_malloc(&hp
);
230 return HwParamsPtr
{hp
};
233 struct SwParamsDeleter
{
234 void operator()(snd_pcm_sw_params_t
*ptr
) { snd_pcm_sw_params_free(ptr
); }
236 using SwParamsPtr
= std::unique_ptr
<snd_pcm_sw_params_t
,SwParamsDeleter
>;
237 SwParamsPtr
CreateSwParams()
239 snd_pcm_sw_params_t
*sp
{};
240 snd_pcm_sw_params_malloc(&sp
);
241 return SwParamsPtr
{sp
};
247 std::string device_name
;
249 template<typename T
, typename U
>
250 DevMap(T
&& name_
, U
&& devname
)
251 : name
{std::forward
<T
>(name_
)}, device_name
{std::forward
<U
>(devname
)}
255 std::vector
<DevMap
> PlaybackDevices
;
256 std::vector
<DevMap
> CaptureDevices
;
259 std::string_view
prefix_name(snd_pcm_stream_t stream
) noexcept
261 if(stream
== SND_PCM_STREAM_PLAYBACK
)
262 return "device-prefix"sv
;
263 return "capture-prefix"sv
;
266 struct SndCtlCardInfo
{
267 snd_ctl_card_info_t
*mInfo
{};
269 SndCtlCardInfo() { snd_ctl_card_info_malloc(&mInfo
); }
270 ~SndCtlCardInfo() { if(mInfo
) snd_ctl_card_info_free(mInfo
); }
271 SndCtlCardInfo(const SndCtlCardInfo
&) = delete;
272 SndCtlCardInfo
& operator=(const SndCtlCardInfo
&) = delete;
275 operator snd_ctl_card_info_t
*() const noexcept
{ return mInfo
; }
279 snd_pcm_info_t
*mInfo
{};
281 SndPcmInfo() { snd_pcm_info_malloc(&mInfo
); }
282 ~SndPcmInfo() { if(mInfo
) snd_pcm_info_free(mInfo
); }
283 SndPcmInfo(const SndPcmInfo
&) = delete;
284 SndPcmInfo
& operator=(const SndPcmInfo
&) = delete;
287 operator snd_pcm_info_t
*() const noexcept
{ return mInfo
; }
291 snd_ctl_t
*mHandle
{};
294 ~SndCtl() { if(mHandle
) snd_ctl_close(mHandle
); }
295 SndCtl(const SndCtl
&) = delete;
296 SndCtl
& operator=(const SndCtl
&) = delete;
299 auto open(const char *name
, int mode
) { return snd_ctl_open(&mHandle
, name
, mode
); }
302 operator snd_ctl_t
*() const noexcept
{ return mHandle
; }
306 std::vector
<DevMap
> probe_devices(snd_pcm_stream_t stream
)
308 std::vector
<DevMap
> devlist
;
313 auto defname
= ConfigValueStr({}, "alsa"sv
,
314 (stream
== SND_PCM_STREAM_PLAYBACK
) ? "device"sv
: "capture"sv
);
315 devlist
.emplace_back(GetDefaultName(), defname
? std::string_view
{*defname
} : "default"sv
);
317 if(auto customdevs
= ConfigValueStr({}, "alsa"sv
,
318 (stream
== SND_PCM_STREAM_PLAYBACK
) ? "custom-devices"sv
: "custom-captures"sv
))
320 size_t curpos
{customdevs
->find_first_not_of(';')};
321 while(curpos
< customdevs
->length())
323 size_t nextpos
{customdevs
->find(';', curpos
+1)};
324 const size_t seppos
{customdevs
->find('=', curpos
)};
325 if(seppos
== curpos
|| seppos
>= nextpos
)
327 const std::string spec
{customdevs
->substr(curpos
, nextpos
-curpos
)};
328 ERR("Invalid ALSA device specification \"%s\"\n", spec
.c_str());
332 const std::string_view strview
{*customdevs
};
333 const auto &entry
= devlist
.emplace_back(strview
.substr(curpos
, seppos
-curpos
),
334 strview
.substr(seppos
+1, nextpos
-seppos
-1));
335 TRACE("Got device \"%s\", \"%s\"\n", entry
.name
.c_str(), entry
.device_name
.c_str());
338 if(nextpos
< customdevs
->length())
339 nextpos
= customdevs
->find_first_not_of(';', nextpos
+1);
344 const std::string main_prefix
{ConfigValueStr({}, "alsa"sv
, prefix_name(stream
))
345 .value_or("plughw:")};
348 int err
{snd_card_next(&card
)};
349 for(;err
>= 0 && card
>= 0;err
= snd_card_next(&card
))
351 std::string name
{"hw:" + std::to_string(card
)};
354 err
= handle
.open(name
.c_str(), 0);
357 ERR("control open (hw:%d): %s\n", card
, snd_strerror(err
));
360 err
= snd_ctl_card_info(handle
, info
);
363 ERR("control hardware info (hw:%d): %s\n", card
, snd_strerror(err
));
367 const char *cardname
{snd_ctl_card_info_get_name(info
)};
368 const char *cardid
{snd_ctl_card_info_get_id(info
)};
369 name
= prefix_name(stream
);
372 const std::string card_prefix
{ConfigValueStr({}, "alsa"sv
, name
).value_or(main_prefix
)};
377 if(snd_ctl_pcm_next_device(handle
, &dev
) < 0)
378 ERR("snd_ctl_pcm_next_device failed\n");
381 snd_pcm_info_set_device(pcminfo
, static_cast<uint
>(dev
));
382 snd_pcm_info_set_subdevice(pcminfo
, 0);
383 snd_pcm_info_set_stream(pcminfo
, stream
);
384 err
= snd_ctl_pcm_info(handle
, pcminfo
);
388 ERR("control digital audio info (hw:%d): %s\n", card
, snd_strerror(err
));
392 /* "prefix-cardid-dev" */
393 name
= prefix_name(stream
);
397 name
+= std::to_string(dev
);
398 const std::string device_prefix
{ConfigValueStr({}, "alsa"sv
, name
)
399 .value_or(card_prefix
)};
401 /* "CardName, PcmName (CARD=cardid,DEV=dev)" */
404 name
+= snd_pcm_info_get_name(pcminfo
);
408 name
+= std::to_string(dev
);
411 /* "devprefixCARD=cardid,DEV=dev" */
412 std::string device
{device_prefix
};
416 device
+= std::to_string(dev
);
418 const auto &entry
= devlist
.emplace_back(std::move(name
), std::move(device
));
419 TRACE("Got device \"%s\", \"%s\"\n", entry
.name
.c_str(), entry
.device_name
.c_str());
423 ERR("snd_card_next failed: %s\n", snd_strerror(err
));
429 int verify_state(snd_pcm_t
*handle
)
431 snd_pcm_state_t state
{snd_pcm_state(handle
)};
435 case SND_PCM_STATE_OPEN
:
436 case SND_PCM_STATE_SETUP
:
437 case SND_PCM_STATE_PREPARED
:
438 case SND_PCM_STATE_RUNNING
:
439 case SND_PCM_STATE_DRAINING
:
440 case SND_PCM_STATE_PAUSED
:
444 case SND_PCM_STATE_XRUN
:
445 if(int err
{snd_pcm_recover(handle
, -EPIPE
, 1)}; err
< 0)
448 case SND_PCM_STATE_SUSPENDED
:
449 if(int err
{snd_pcm_recover(handle
, -ESTRPIPE
, 1)}; err
< 0)
453 case SND_PCM_STATE_DISCONNECTED
:
456 /* ALSA headers have made this enum public, leaving us in a bind: use
457 * the enum despite being private and internal to the libasound, or
458 * ignore when an enum value isn't handled. We can't rely on it being
459 * declared either, since older headers don't have it and it could be
460 * removed in the future. We can't even really rely on its value, since
461 * being private/internal means it's subject to change, but this is the
464 case 1024 /*SND_PCM_STATE_PRIVATE1*/:
465 assert(state
!= 1024);
472 struct AlsaPlayback final
: public BackendBase
{
473 AlsaPlayback(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
474 ~AlsaPlayback() override
;
477 int mixerNoMMapProc();
479 void open(std::string_view name
) override
;
480 bool reset() override
;
481 void start() override
;
482 void stop() override
;
484 ClockLatency
getClockLatency() override
;
486 snd_pcm_t
*mPcmHandle
{nullptr};
491 std::vector
<std::byte
> mBuffer
;
493 std::atomic
<bool> mKillNow
{true};
497 AlsaPlayback::~AlsaPlayback()
500 snd_pcm_close(mPcmHandle
);
501 mPcmHandle
= nullptr;
505 int AlsaPlayback::mixerProc()
508 althrd_setname(GetMixerThreadName());
510 const snd_pcm_uframes_t update_size
{mDevice
->UpdateSize
};
511 const snd_pcm_uframes_t buffer_size
{mDevice
->BufferSize
};
512 while(!mKillNow
.load(std::memory_order_acquire
))
514 int state
{verify_state(mPcmHandle
)};
517 ERR("Invalid state detected: %s\n", snd_strerror(state
));
518 mDevice
->handleDisconnect("Bad state: %s", snd_strerror(state
));
522 snd_pcm_sframes_t avails
{snd_pcm_avail_update(mPcmHandle
)};
525 ERR("available update failed: %s\n", snd_strerror(static_cast<int>(avails
)));
528 snd_pcm_uframes_t avail
{static_cast<snd_pcm_uframes_t
>(avails
)};
530 if(avail
> buffer_size
)
532 WARN("available samples exceeds the buffer size\n");
533 snd_pcm_reset(mPcmHandle
);
537 // make sure there's frames to process
538 if(avail
< update_size
)
540 if(state
!= SND_PCM_STATE_RUNNING
)
542 int err
{snd_pcm_start(mPcmHandle
)};
545 ERR("start failed: %s\n", snd_strerror(err
));
549 if(snd_pcm_wait(mPcmHandle
, 1000) == 0)
550 ERR("Wait timeout... buffer size too low?\n");
553 avail
-= avail
%update_size
;
555 // it is possible that contiguous areas are smaller, thus we use a loop
556 std::lock_guard
<std::mutex
> dlock
{mMutex
};
559 snd_pcm_uframes_t frames
{avail
};
561 const snd_pcm_channel_area_t
*areas
{};
562 snd_pcm_uframes_t offset
{};
563 int err
{snd_pcm_mmap_begin(mPcmHandle
, &areas
, &offset
, &frames
)};
566 ERR("mmap begin error: %s\n", snd_strerror(err
));
570 /* NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) */
571 char *WritePtr
{static_cast<char*>(areas
->addr
) + (offset
* areas
->step
/ 8)};
572 mDevice
->renderSamples(WritePtr
, static_cast<uint
>(frames
), mFrameStep
);
574 snd_pcm_sframes_t commitres
{snd_pcm_mmap_commit(mPcmHandle
, offset
, frames
)};
575 if(commitres
< 0 || static_cast<snd_pcm_uframes_t
>(commitres
) != frames
)
577 ERR("mmap commit error: %s\n",
578 snd_strerror(commitres
>= 0 ? -EPIPE
: static_cast<int>(commitres
)));
589 int AlsaPlayback::mixerNoMMapProc()
592 althrd_setname(GetMixerThreadName());
594 const snd_pcm_uframes_t update_size
{mDevice
->UpdateSize
};
595 const snd_pcm_uframes_t buffer_size
{mDevice
->BufferSize
};
596 while(!mKillNow
.load(std::memory_order_acquire
))
598 int state
{verify_state(mPcmHandle
)};
601 ERR("Invalid state detected: %s\n", snd_strerror(state
));
602 mDevice
->handleDisconnect("Bad state: %s", snd_strerror(state
));
606 snd_pcm_sframes_t avail
{snd_pcm_avail_update(mPcmHandle
)};
609 ERR("available update failed: %s\n", snd_strerror(static_cast<int>(avail
)));
613 if(static_cast<snd_pcm_uframes_t
>(avail
) > buffer_size
)
615 WARN("available samples exceeds the buffer size\n");
616 snd_pcm_reset(mPcmHandle
);
620 if(static_cast<snd_pcm_uframes_t
>(avail
) < update_size
)
622 if(state
!= SND_PCM_STATE_RUNNING
)
624 int err
{snd_pcm_start(mPcmHandle
)};
627 ERR("start failed: %s\n", snd_strerror(err
));
631 if(snd_pcm_wait(mPcmHandle
, 1000) == 0)
632 ERR("Wait timeout... buffer size too low?\n");
636 auto WritePtr
= mBuffer
.begin();
637 avail
= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
638 std::lock_guard
<std::mutex
> dlock
{mMutex
};
639 mDevice
->renderSamples(al::to_address(WritePtr
), static_cast<uint
>(avail
), mFrameStep
);
642 snd_pcm_sframes_t ret
{snd_pcm_writei(mPcmHandle
, al::to_address(WritePtr
),
643 static_cast<snd_pcm_uframes_t
>(avail
))};
648 #if ESTRPIPE != EPIPE
653 ret
= snd_pcm_recover(mPcmHandle
, static_cast<int>(ret
), 1);
660 WritePtr
+= snd_pcm_frames_to_bytes(mPcmHandle
, ret
);
667 ret
= snd_pcm_prepare(mPcmHandle
);
677 void AlsaPlayback::open(std::string_view name
)
679 std::string driver
{"default"};
682 if(PlaybackDevices
.empty())
683 PlaybackDevices
= probe_devices(SND_PCM_STREAM_PLAYBACK
);
685 auto iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
686 [name
](const DevMap
&entry
) -> bool { return entry
.name
== name
; });
687 if(iter
== PlaybackDevices
.cend())
688 throw al::backend_exception
{al::backend_error::NoDevice
,
689 "Device name \"%.*s\" not found", al::sizei(name
), name
.data()};
690 driver
= iter
->device_name
;
694 name
= GetDefaultName();
695 if(auto driveropt
= ConfigValueStr({}, "alsa"sv
, "device"sv
))
696 driver
= std::move(driveropt
).value();
698 TRACE("Opening device \"%s\"\n", driver
.c_str());
700 snd_pcm_t
*pcmHandle
{};
701 int err
{snd_pcm_open(&pcmHandle
, driver
.c_str(), SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)};
703 throw al::backend_exception
{al::backend_error::NoDevice
,
704 "Could not open ALSA device \"%s\"", driver
.c_str()};
706 snd_pcm_close(mPcmHandle
);
707 mPcmHandle
= pcmHandle
;
709 /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */
710 snd_config_update_free_global();
715 bool AlsaPlayback::reset()
717 snd_pcm_format_t format
{SND_PCM_FORMAT_UNKNOWN
};
718 switch(mDevice
->FmtType
)
721 format
= SND_PCM_FORMAT_S8
;
724 format
= SND_PCM_FORMAT_U8
;
727 format
= SND_PCM_FORMAT_S16
;
730 format
= SND_PCM_FORMAT_U16
;
733 format
= SND_PCM_FORMAT_S32
;
736 format
= SND_PCM_FORMAT_U32
;
739 format
= SND_PCM_FORMAT_FLOAT
;
743 bool allowmmap
{GetConfigValueBool(mDevice
->mDeviceName
, "alsa"sv
, "mmap"sv
, true)};
744 uint periodLen
{static_cast<uint
>(mDevice
->UpdateSize
* 1000000_u64
/ mDevice
->Frequency
)};
745 uint bufferLen
{static_cast<uint
>(mDevice
->BufferSize
* 1000000_u64
/ mDevice
->Frequency
)};
746 uint rate
{mDevice
->Frequency
};
748 HwParamsPtr hp
{CreateHwParams()};
749 #define CHECK(x) do { \
750 if(int err{x}; err < 0) \
751 throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \
752 snd_strerror(err)}; \
754 CHECK(snd_pcm_hw_params_any(mPcmHandle
, hp
.get()));
755 /* set interleaved access */
757 || snd_pcm_hw_params_set_access(mPcmHandle
, hp
.get(), SND_PCM_ACCESS_MMAP_INTERLEAVED
) < 0)
760 CHECK(snd_pcm_hw_params_set_access(mPcmHandle
, hp
.get(), SND_PCM_ACCESS_RW_INTERLEAVED
));
762 /* test and set format (implicitly sets sample bits) */
763 if(snd_pcm_hw_params_test_format(mPcmHandle
, hp
.get(), format
) < 0)
766 snd_pcm_format_t format
;
769 static constexpr std::array formatlist
{
770 FormatMap
{SND_PCM_FORMAT_FLOAT
, DevFmtFloat
},
771 FormatMap
{SND_PCM_FORMAT_S32
, DevFmtInt
},
772 FormatMap
{SND_PCM_FORMAT_U32
, DevFmtUInt
},
773 FormatMap
{SND_PCM_FORMAT_S16
, DevFmtShort
},
774 FormatMap
{SND_PCM_FORMAT_U16
, DevFmtUShort
},
775 FormatMap
{SND_PCM_FORMAT_S8
, DevFmtByte
},
776 FormatMap
{SND_PCM_FORMAT_U8
, DevFmtUByte
},
779 for(const auto &fmt
: formatlist
)
782 if(snd_pcm_hw_params_test_format(mPcmHandle
, hp
.get(), format
) >= 0)
784 mDevice
->FmtType
= fmt
.fmttype
;
789 CHECK(snd_pcm_hw_params_set_format(mPcmHandle
, hp
.get(), format
));
790 /* set channels (implicitly sets frame bits) */
791 if(snd_pcm_hw_params_set_channels(mPcmHandle
, hp
.get(), mDevice
->channelsFromFmt()) < 0)
794 CHECK(snd_pcm_hw_params_set_channels_near(mPcmHandle
, hp
.get(), &numchans
));
796 throw al::backend_exception
{al::backend_error::DeviceError
, "Got 0 device channels"};
797 if(numchans
== 1) mDevice
->FmtChans
= DevFmtMono
;
798 else mDevice
->FmtChans
= DevFmtStereo
;
800 /* set rate (implicitly constrains period/buffer parameters) */
801 if(!GetConfigValueBool(mDevice
->mDeviceName
, "alsa", "allow-resampler", false)
802 || !mDevice
->Flags
.test(FrequencyRequest
))
804 if(snd_pcm_hw_params_set_rate_resample(mPcmHandle
, hp
.get(), 0) < 0)
805 WARN("Failed to disable ALSA resampler\n");
807 else if(snd_pcm_hw_params_set_rate_resample(mPcmHandle
, hp
.get(), 1) < 0)
808 WARN("Failed to enable ALSA resampler\n");
809 CHECK(snd_pcm_hw_params_set_rate_near(mPcmHandle
, hp
.get(), &rate
, nullptr));
810 /* set period time (implicitly constrains period/buffer parameters) */
811 if(int err
{snd_pcm_hw_params_set_period_time_near(mPcmHandle
, hp
.get(), &periodLen
, nullptr)}; err
< 0)
812 ERR("snd_pcm_hw_params_set_period_time_near failed: %s\n", snd_strerror(err
));
813 /* set buffer time (implicitly sets buffer size/bytes/time and period size/bytes) */
814 if(int err
{snd_pcm_hw_params_set_buffer_time_near(mPcmHandle
, hp
.get(), &bufferLen
, nullptr)}; err
< 0)
815 ERR("snd_pcm_hw_params_set_buffer_time_near failed: %s\n", snd_strerror(err
));
816 /* install and prepare hardware configuration */
817 CHECK(snd_pcm_hw_params(mPcmHandle
, hp
.get()));
819 /* retrieve configuration info */
820 snd_pcm_uframes_t periodSizeInFrames
{};
821 snd_pcm_uframes_t bufferSizeInFrames
{};
822 snd_pcm_access_t access
{};
824 CHECK(snd_pcm_hw_params_get_access(hp
.get(), &access
));
825 CHECK(snd_pcm_hw_params_get_period_size(hp
.get(), &periodSizeInFrames
, nullptr));
826 CHECK(snd_pcm_hw_params_get_buffer_size(hp
.get(), &bufferSizeInFrames
));
827 CHECK(snd_pcm_hw_params_get_channels(hp
.get(), &mFrameStep
));
830 SwParamsPtr sp
{CreateSwParams()};
831 CHECK(snd_pcm_sw_params_current(mPcmHandle
, sp
.get()));
832 CHECK(snd_pcm_sw_params_set_avail_min(mPcmHandle
, sp
.get(), periodSizeInFrames
));
833 CHECK(snd_pcm_sw_params_set_stop_threshold(mPcmHandle
, sp
.get(), bufferSizeInFrames
));
834 CHECK(snd_pcm_sw_params(mPcmHandle
, sp
.get()));
838 mDevice
->BufferSize
= static_cast<uint
>(bufferSizeInFrames
);
839 mDevice
->UpdateSize
= static_cast<uint
>(periodSizeInFrames
);
840 mDevice
->Frequency
= rate
;
842 setDefaultChannelOrder();
847 void AlsaPlayback::start()
849 snd_pcm_access_t access
{};
850 HwParamsPtr hp
{CreateHwParams()};
851 #define CHECK(x) do { \
852 if(int err{x}; err < 0) \
853 throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \
854 snd_strerror(err)}; \
856 CHECK(snd_pcm_hw_params_current(mPcmHandle
, hp
.get()));
857 /* retrieve configuration info */
858 CHECK(snd_pcm_hw_params_get_access(hp
.get(), &access
));
861 int (AlsaPlayback::*thread_func
)(){};
862 if(access
== SND_PCM_ACCESS_RW_INTERLEAVED
)
864 auto datalen
= snd_pcm_frames_to_bytes(mPcmHandle
, mDevice
->UpdateSize
);
865 mBuffer
.resize(static_cast<size_t>(datalen
));
866 thread_func
= &AlsaPlayback::mixerNoMMapProc
;
870 CHECK(snd_pcm_prepare(mPcmHandle
));
871 thread_func
= &AlsaPlayback::mixerProc
;
876 mKillNow
.store(false, std::memory_order_release
);
877 mThread
= std::thread
{std::mem_fn(thread_func
), this};
879 catch(std::exception
& e
) {
880 throw al::backend_exception
{al::backend_error::DeviceError
,
881 "Failed to start mixing thread: %s", e
.what()};
885 void AlsaPlayback::stop()
887 if(mKillNow
.exchange(true, std::memory_order_acq_rel
) || !mThread
.joinable())
892 int err
{snd_pcm_drop(mPcmHandle
)};
894 ERR("snd_pcm_drop failed: %s\n", snd_strerror(err
));
897 ClockLatency
AlsaPlayback::getClockLatency()
899 std::lock_guard
<std::mutex
> dlock
{mMutex
};
901 ret
.ClockTime
= mDevice
->getClockTime();
902 snd_pcm_sframes_t delay
{};
903 int err
{snd_pcm_delay(mPcmHandle
, &delay
)};
906 ERR("Failed to get pcm delay: %s\n", snd_strerror(err
));
909 ret
.Latency
= std::chrono::seconds
{std::max
<snd_pcm_sframes_t
>(0, delay
)};
910 ret
.Latency
/= mDevice
->Frequency
;
916 struct AlsaCapture final
: public BackendBase
{
917 AlsaCapture(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
918 ~AlsaCapture() override
;
920 void open(std::string_view name
) override
;
921 void start() override
;
922 void stop() override
;
923 void captureSamples(std::byte
*buffer
, uint samples
) override
;
924 uint
availableSamples() override
;
925 ClockLatency
getClockLatency() override
;
927 snd_pcm_t
*mPcmHandle
{nullptr};
929 std::vector
<std::byte
> mBuffer
;
931 bool mDoCapture
{false};
932 RingBufferPtr mRing
{nullptr};
934 snd_pcm_sframes_t mLastAvail
{0};
937 AlsaCapture::~AlsaCapture()
940 snd_pcm_close(mPcmHandle
);
941 mPcmHandle
= nullptr;
945 void AlsaCapture::open(std::string_view name
)
947 std::string driver
{"default"};
950 if(CaptureDevices
.empty())
951 CaptureDevices
= probe_devices(SND_PCM_STREAM_CAPTURE
);
953 auto iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
954 [name
](const DevMap
&entry
) -> bool { return entry
.name
== name
; });
955 if(iter
== CaptureDevices
.cend())
956 throw al::backend_exception
{al::backend_error::NoDevice
,
957 "Device name \"%.*s\" not found", al::sizei(name
), name
.data()};
958 driver
= iter
->device_name
;
962 name
= GetDefaultName();
963 if(auto driveropt
= ConfigValueStr({}, "alsa"sv
, "capture"sv
))
964 driver
= std::move(driveropt
).value();
967 TRACE("Opening device \"%s\"\n", driver
.c_str());
968 if(int err
{snd_pcm_open(&mPcmHandle
, driver
.c_str(), SND_PCM_STREAM_CAPTURE
, SND_PCM_NONBLOCK
)}; err
< 0)
969 throw al::backend_exception
{al::backend_error::NoDevice
,
970 "Could not open ALSA device \"%s\"", driver
.c_str()};
972 /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */
973 snd_config_update_free_global();
975 snd_pcm_format_t format
{SND_PCM_FORMAT_UNKNOWN
};
976 switch(mDevice
->FmtType
)
979 format
= SND_PCM_FORMAT_S8
;
982 format
= SND_PCM_FORMAT_U8
;
985 format
= SND_PCM_FORMAT_S16
;
988 format
= SND_PCM_FORMAT_U16
;
991 format
= SND_PCM_FORMAT_S32
;
994 format
= SND_PCM_FORMAT_U32
;
997 format
= SND_PCM_FORMAT_FLOAT
;
1001 snd_pcm_uframes_t bufferSizeInFrames
{std::max(mDevice
->BufferSize
,
1002 100u*mDevice
->Frequency
/1000u)};
1003 snd_pcm_uframes_t periodSizeInFrames
{std::min(mDevice
->BufferSize
,
1004 25u*mDevice
->Frequency
/1000u)};
1006 bool needring
{false};
1007 HwParamsPtr hp
{CreateHwParams()};
1008 #define CHECK(x) do { \
1009 if(int err{x}; err < 0) \
1010 throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \
1011 snd_strerror(err)}; \
1013 CHECK(snd_pcm_hw_params_any(mPcmHandle
, hp
.get()));
1014 /* set interleaved access */
1015 CHECK(snd_pcm_hw_params_set_access(mPcmHandle
, hp
.get(), SND_PCM_ACCESS_RW_INTERLEAVED
));
1016 /* set format (implicitly sets sample bits) */
1017 CHECK(snd_pcm_hw_params_set_format(mPcmHandle
, hp
.get(), format
));
1018 /* set channels (implicitly sets frame bits) */
1019 CHECK(snd_pcm_hw_params_set_channels(mPcmHandle
, hp
.get(), mDevice
->channelsFromFmt()));
1020 /* set rate (implicitly constrains period/buffer parameters) */
1021 CHECK(snd_pcm_hw_params_set_rate(mPcmHandle
, hp
.get(), mDevice
->Frequency
, 0));
1022 /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */
1023 if(snd_pcm_hw_params_set_buffer_size_min(mPcmHandle
, hp
.get(), &bufferSizeInFrames
) < 0)
1025 TRACE("Buffer too large, using intermediate ring buffer\n");
1027 CHECK(snd_pcm_hw_params_set_buffer_size_near(mPcmHandle
, hp
.get(), &bufferSizeInFrames
));
1029 /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */
1030 CHECK(snd_pcm_hw_params_set_period_size_near(mPcmHandle
, hp
.get(), &periodSizeInFrames
, nullptr));
1031 /* install and prepare hardware configuration */
1032 CHECK(snd_pcm_hw_params(mPcmHandle
, hp
.get()));
1033 /* retrieve configuration info */
1034 CHECK(snd_pcm_hw_params_get_period_size(hp
.get(), &periodSizeInFrames
, nullptr));
1039 mRing
= RingBuffer::Create(mDevice
->BufferSize
, mDevice
->frameSizeFromFmt(), false);
1045 void AlsaCapture::start()
1047 if(int err
{snd_pcm_prepare(mPcmHandle
)}; err
< 0)
1048 throw al::backend_exception
{al::backend_error::DeviceError
, "snd_pcm_prepare failed: %s",
1051 if(int err
{snd_pcm_start(mPcmHandle
)}; err
< 0)
1052 throw al::backend_exception
{al::backend_error::DeviceError
, "snd_pcm_start failed: %s",
1058 void AlsaCapture::stop()
1060 /* OpenAL requires access to unread audio after stopping, but ALSA's
1061 * snd_pcm_drain is unreliable and snd_pcm_drop drops it. Capture what's
1062 * available now so it'll be available later after the drop.
1064 uint avail
{availableSamples()};
1065 if(!mRing
&& avail
> 0)
1067 /* The ring buffer implicitly captures when checking availability.
1068 * Direct access needs to explicitly capture it into temp storage.
1070 auto temp
= std::vector
<std::byte
>(
1071 static_cast<size_t>(snd_pcm_frames_to_bytes(mPcmHandle
, avail
)));
1072 captureSamples(temp
.data(), avail
);
1073 mBuffer
= std::move(temp
);
1075 if(int err
{snd_pcm_drop(mPcmHandle
)}; err
< 0)
1076 ERR("drop failed: %s\n", snd_strerror(err
));
1080 void AlsaCapture::captureSamples(std::byte
*buffer
, uint samples
)
1084 std::ignore
= mRing
->read(buffer
, samples
);
1088 const auto outspan
= al::span
{buffer
,
1089 static_cast<size_t>(snd_pcm_frames_to_bytes(mPcmHandle
, samples
))};
1090 auto outiter
= outspan
.begin();
1091 mLastAvail
-= samples
;
1092 while(mDevice
->Connected
.load(std::memory_order_acquire
) && samples
> 0)
1094 snd_pcm_sframes_t amt
{0};
1096 if(!mBuffer
.empty())
1098 /* First get any data stored from the last stop */
1099 amt
= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
1100 if(static_cast<snd_pcm_uframes_t
>(amt
) > samples
) amt
= samples
;
1102 amt
= snd_pcm_frames_to_bytes(mPcmHandle
, amt
);
1103 std::copy_n(mBuffer
.begin(), amt
, outiter
);
1105 mBuffer
.erase(mBuffer
.begin(), mBuffer
.begin()+amt
);
1106 amt
= snd_pcm_bytes_to_frames(mPcmHandle
, amt
);
1109 amt
= snd_pcm_readi(mPcmHandle
, al::to_address(outiter
), samples
);
1112 ERR("read error: %s\n", snd_strerror(static_cast<int>(amt
)));
1116 amt
= snd_pcm_recover(mPcmHandle
, static_cast<int>(amt
), 1);
1119 amt
= snd_pcm_start(mPcmHandle
);
1121 amt
= snd_pcm_avail_update(mPcmHandle
);
1125 const char *err
{snd_strerror(static_cast<int>(amt
))};
1126 ERR("restore error: %s\n", err
);
1127 mDevice
->handleDisconnect("Capture recovery failure: %s", err
);
1130 /* If the amount available is less than what's asked, we lost it
1131 * during recovery. So just give silence instead. */
1132 if(static_cast<snd_pcm_uframes_t
>(amt
) < samples
)
1138 samples
-= static_cast<uint
>(amt
);
1141 std::fill_n(outiter
, snd_pcm_frames_to_bytes(mPcmHandle
, samples
),
1142 std::byte((mDevice
->FmtType
== DevFmtUByte
) ? 0x80 : 0));
1145 uint
AlsaCapture::availableSamples()
1147 snd_pcm_sframes_t avail
{0};
1148 if(mDevice
->Connected
.load(std::memory_order_acquire
) && mDoCapture
)
1149 avail
= snd_pcm_avail_update(mPcmHandle
);
1152 ERR("avail update failed: %s\n", snd_strerror(static_cast<int>(avail
)));
1154 avail
= snd_pcm_recover(mPcmHandle
, static_cast<int>(avail
), 1);
1158 avail
= snd_pcm_start(mPcmHandle
);
1160 avail
= snd_pcm_avail_update(mPcmHandle
);
1164 const char *err
{snd_strerror(static_cast<int>(avail
))};
1165 ERR("restore error: %s\n", err
);
1166 mDevice
->handleDisconnect("Capture recovery failure: %s", err
);
1172 if(avail
< 0) avail
= 0;
1173 avail
+= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
1174 if(avail
> mLastAvail
) mLastAvail
= avail
;
1175 return static_cast<uint
>(mLastAvail
);
1180 auto vec
= mRing
->getWriteVector();
1181 if(vec
.first
.len
== 0) break;
1183 snd_pcm_sframes_t amt
{std::min(static_cast<snd_pcm_sframes_t
>(vec
.first
.len
), avail
)};
1184 amt
= snd_pcm_readi(mPcmHandle
, vec
.first
.buf
, static_cast<snd_pcm_uframes_t
>(amt
));
1187 ERR("read error: %s\n", snd_strerror(static_cast<int>(amt
)));
1191 amt
= snd_pcm_recover(mPcmHandle
, static_cast<int>(amt
), 1);
1195 amt
= snd_pcm_start(mPcmHandle
);
1197 amt
= snd_pcm_avail_update(mPcmHandle
);
1201 const char *err
{snd_strerror(static_cast<int>(amt
))};
1202 ERR("restore error: %s\n", err
);
1203 mDevice
->handleDisconnect("Capture recovery failure: %s", err
);
1210 mRing
->writeAdvance(static_cast<snd_pcm_uframes_t
>(amt
));
1214 return static_cast<uint
>(mRing
->readSpace());
1217 ClockLatency
AlsaCapture::getClockLatency()
1220 ret
.ClockTime
= mDevice
->getClockTime();
1221 snd_pcm_sframes_t delay
{};
1222 int err
{snd_pcm_delay(mPcmHandle
, &delay
)};
1225 ERR("Failed to get pcm delay: %s\n", snd_strerror(err
));
1228 ret
.Latency
= std::chrono::seconds
{std::max
<snd_pcm_sframes_t
>(0, delay
)};
1229 ret
.Latency
/= mDevice
->Frequency
;
1237 bool AlsaBackendFactory::init()
1242 alsa_handle
= LoadLib("libasound.so.2");
1245 WARN("Failed to load %s\n", "libasound.so.2");
1249 std::string missing_funcs
;
1250 #define LOAD_FUNC(f) do { \
1251 p##f = reinterpret_cast<decltype(p##f)>(GetSymbol(alsa_handle, #f)); \
1252 if(p##f == nullptr) missing_funcs += "\n" #f; \
1254 ALSA_FUNCS(LOAD_FUNC
);
1257 if(!missing_funcs
.empty())
1259 WARN("Missing expected functions:%s\n", missing_funcs
.c_str());
1260 CloseLib(alsa_handle
);
1261 alsa_handle
= nullptr;
1270 bool AlsaBackendFactory::querySupport(BackendType type
)
1271 { return (type
== BackendType::Playback
|| type
== BackendType::Capture
); }
1273 auto AlsaBackendFactory::enumerate(BackendType type
) -> std::vector
<std::string
>
1275 std::vector
<std::string
> outnames
;
1276 auto add_device
= [&outnames
](const DevMap
&entry
) -> void
1277 { outnames
.emplace_back(entry
.name
); };
1281 case BackendType::Playback
:
1282 PlaybackDevices
= probe_devices(SND_PCM_STREAM_PLAYBACK
);
1283 outnames
.reserve(PlaybackDevices
.size());
1284 std::for_each(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), add_device
);
1287 case BackendType::Capture
:
1288 CaptureDevices
= probe_devices(SND_PCM_STREAM_CAPTURE
);
1289 outnames
.reserve(CaptureDevices
.size());
1290 std::for_each(CaptureDevices
.cbegin(), CaptureDevices
.cend(), add_device
);
1297 BackendPtr
AlsaBackendFactory::createBackend(DeviceBase
*device
, BackendType type
)
1299 if(type
== BackendType::Playback
)
1300 return BackendPtr
{new AlsaPlayback
{device
}};
1301 if(type
== BackendType::Capture
)
1302 return BackendPtr
{new AlsaCapture
{device
}};
1306 BackendFactory
&AlsaBackendFactory::getFactory()
1308 static AlsaBackendFactory factory
{};