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"
45 #include "althrd_setname.h"
46 #include "core/device.h"
47 #include "core/helpers.h"
48 #include "core/logging.h"
50 #include "ringbuffer.h"
52 #include <alsa/asoundlib.h>
57 using namespace std::string_view_literals
;
59 [[nodiscard
]] constexpr auto GetDefaultName() noexcept
{ return "ALSA Default"sv
; }
63 #define ALSA_FUNCS(MAGIC) \
64 MAGIC(snd_strerror); \
65 MAGIC(snd_pcm_open); \
66 MAGIC(snd_pcm_close); \
67 MAGIC(snd_pcm_nonblock); \
68 MAGIC(snd_pcm_frames_to_bytes); \
69 MAGIC(snd_pcm_bytes_to_frames); \
70 MAGIC(snd_pcm_hw_params_malloc); \
71 MAGIC(snd_pcm_hw_params_free); \
72 MAGIC(snd_pcm_hw_params_any); \
73 MAGIC(snd_pcm_hw_params_current); \
74 MAGIC(snd_pcm_hw_params_get_access); \
75 MAGIC(snd_pcm_hw_params_get_buffer_size); \
76 MAGIC(snd_pcm_hw_params_get_buffer_time_min); \
77 MAGIC(snd_pcm_hw_params_get_buffer_time_max); \
78 MAGIC(snd_pcm_hw_params_get_channels); \
79 MAGIC(snd_pcm_hw_params_get_period_size); \
80 MAGIC(snd_pcm_hw_params_get_period_time_max); \
81 MAGIC(snd_pcm_hw_params_get_period_time_min); \
82 MAGIC(snd_pcm_hw_params_get_periods); \
83 MAGIC(snd_pcm_hw_params_set_access); \
84 MAGIC(snd_pcm_hw_params_set_buffer_size_min); \
85 MAGIC(snd_pcm_hw_params_set_buffer_size_near); \
86 MAGIC(snd_pcm_hw_params_set_buffer_time_near); \
87 MAGIC(snd_pcm_hw_params_set_channels); \
88 MAGIC(snd_pcm_hw_params_set_channels_near); \
89 MAGIC(snd_pcm_hw_params_set_format); \
90 MAGIC(snd_pcm_hw_params_set_period_time_near); \
91 MAGIC(snd_pcm_hw_params_set_period_size_near); \
92 MAGIC(snd_pcm_hw_params_set_periods_near); \
93 MAGIC(snd_pcm_hw_params_set_rate_near); \
94 MAGIC(snd_pcm_hw_params_set_rate); \
95 MAGIC(snd_pcm_hw_params_set_rate_resample); \
96 MAGIC(snd_pcm_hw_params_test_format); \
97 MAGIC(snd_pcm_hw_params_test_channels); \
98 MAGIC(snd_pcm_hw_params); \
99 MAGIC(snd_pcm_sw_params); \
100 MAGIC(snd_pcm_sw_params_current); \
101 MAGIC(snd_pcm_sw_params_free); \
102 MAGIC(snd_pcm_sw_params_malloc); \
103 MAGIC(snd_pcm_sw_params_set_avail_min); \
104 MAGIC(snd_pcm_sw_params_set_stop_threshold); \
105 MAGIC(snd_pcm_prepare); \
106 MAGIC(snd_pcm_start); \
107 MAGIC(snd_pcm_resume); \
108 MAGIC(snd_pcm_reset); \
109 MAGIC(snd_pcm_wait); \
110 MAGIC(snd_pcm_delay); \
111 MAGIC(snd_pcm_state); \
112 MAGIC(snd_pcm_avail_update); \
113 MAGIC(snd_pcm_mmap_begin); \
114 MAGIC(snd_pcm_mmap_commit); \
115 MAGIC(snd_pcm_readi); \
116 MAGIC(snd_pcm_writei); \
117 MAGIC(snd_pcm_drain); \
118 MAGIC(snd_pcm_drop); \
119 MAGIC(snd_pcm_recover); \
120 MAGIC(snd_pcm_info_malloc); \
121 MAGIC(snd_pcm_info_free); \
122 MAGIC(snd_pcm_info_set_device); \
123 MAGIC(snd_pcm_info_set_subdevice); \
124 MAGIC(snd_pcm_info_set_stream); \
125 MAGIC(snd_pcm_info_get_name); \
126 MAGIC(snd_ctl_pcm_next_device); \
127 MAGIC(snd_ctl_pcm_info); \
128 MAGIC(snd_ctl_open); \
129 MAGIC(snd_ctl_close); \
130 MAGIC(snd_ctl_card_info_malloc); \
131 MAGIC(snd_ctl_card_info_free); \
132 MAGIC(snd_ctl_card_info); \
133 MAGIC(snd_ctl_card_info_get_name); \
134 MAGIC(snd_ctl_card_info_get_id); \
135 MAGIC(snd_card_next); \
136 MAGIC(snd_config_update_free_global)
139 #define MAKE_FUNC(f) decltype(f) * p##f
140 ALSA_FUNCS(MAKE_FUNC
);
143 #ifndef IN_IDE_PARSER
144 #define snd_strerror psnd_strerror
145 #define snd_pcm_open psnd_pcm_open
146 #define snd_pcm_close psnd_pcm_close
147 #define snd_pcm_nonblock psnd_pcm_nonblock
148 #define snd_pcm_frames_to_bytes psnd_pcm_frames_to_bytes
149 #define snd_pcm_bytes_to_frames psnd_pcm_bytes_to_frames
150 #define snd_pcm_hw_params_malloc psnd_pcm_hw_params_malloc
151 #define snd_pcm_hw_params_free psnd_pcm_hw_params_free
152 #define snd_pcm_hw_params_any psnd_pcm_hw_params_any
153 #define snd_pcm_hw_params_current psnd_pcm_hw_params_current
154 #define snd_pcm_hw_params_set_access psnd_pcm_hw_params_set_access
155 #define snd_pcm_hw_params_set_format psnd_pcm_hw_params_set_format
156 #define snd_pcm_hw_params_set_channels psnd_pcm_hw_params_set_channels
157 #define snd_pcm_hw_params_set_channels_near psnd_pcm_hw_params_set_channels_near
158 #define snd_pcm_hw_params_set_periods_near psnd_pcm_hw_params_set_periods_near
159 #define snd_pcm_hw_params_set_rate_near psnd_pcm_hw_params_set_rate_near
160 #define snd_pcm_hw_params_set_rate psnd_pcm_hw_params_set_rate
161 #define snd_pcm_hw_params_set_rate_resample psnd_pcm_hw_params_set_rate_resample
162 #define snd_pcm_hw_params_set_buffer_time_near psnd_pcm_hw_params_set_buffer_time_near
163 #define snd_pcm_hw_params_set_period_time_near psnd_pcm_hw_params_set_period_time_near
164 #define snd_pcm_hw_params_set_buffer_size_near psnd_pcm_hw_params_set_buffer_size_near
165 #define snd_pcm_hw_params_set_period_size_near psnd_pcm_hw_params_set_period_size_near
166 #define snd_pcm_hw_params_set_buffer_size_min psnd_pcm_hw_params_set_buffer_size_min
167 #define snd_pcm_hw_params_get_buffer_time_min psnd_pcm_hw_params_get_buffer_time_min
168 #define snd_pcm_hw_params_get_buffer_time_max psnd_pcm_hw_params_get_buffer_time_max
169 #define snd_pcm_hw_params_get_period_time_min psnd_pcm_hw_params_get_period_time_min
170 #define snd_pcm_hw_params_get_period_time_max psnd_pcm_hw_params_get_period_time_max
171 #define snd_pcm_hw_params_get_buffer_size psnd_pcm_hw_params_get_buffer_size
172 #define snd_pcm_hw_params_get_period_size psnd_pcm_hw_params_get_period_size
173 #define snd_pcm_hw_params_get_access psnd_pcm_hw_params_get_access
174 #define snd_pcm_hw_params_get_periods psnd_pcm_hw_params_get_periods
175 #define snd_pcm_hw_params_get_channels psnd_pcm_hw_params_get_channels
176 #define snd_pcm_hw_params_test_format psnd_pcm_hw_params_test_format
177 #define snd_pcm_hw_params_test_channels psnd_pcm_hw_params_test_channels
178 #define snd_pcm_hw_params psnd_pcm_hw_params
179 #define snd_pcm_sw_params_malloc psnd_pcm_sw_params_malloc
180 #define snd_pcm_sw_params_current psnd_pcm_sw_params_current
181 #define snd_pcm_sw_params_set_avail_min psnd_pcm_sw_params_set_avail_min
182 #define snd_pcm_sw_params_set_stop_threshold psnd_pcm_sw_params_set_stop_threshold
183 #define snd_pcm_sw_params psnd_pcm_sw_params
184 #define snd_pcm_sw_params_free psnd_pcm_sw_params_free
185 #define snd_pcm_prepare psnd_pcm_prepare
186 #define snd_pcm_start psnd_pcm_start
187 #define snd_pcm_resume psnd_pcm_resume
188 #define snd_pcm_reset psnd_pcm_reset
189 #define snd_pcm_wait psnd_pcm_wait
190 #define snd_pcm_delay psnd_pcm_delay
191 #define snd_pcm_state psnd_pcm_state
192 #define snd_pcm_avail_update psnd_pcm_avail_update
193 #define snd_pcm_mmap_begin psnd_pcm_mmap_begin
194 #define snd_pcm_mmap_commit psnd_pcm_mmap_commit
195 #define snd_pcm_readi psnd_pcm_readi
196 #define snd_pcm_writei psnd_pcm_writei
197 #define snd_pcm_drain psnd_pcm_drain
198 #define snd_pcm_drop psnd_pcm_drop
199 #define snd_pcm_recover psnd_pcm_recover
200 #define snd_pcm_info_malloc psnd_pcm_info_malloc
201 #define snd_pcm_info_free psnd_pcm_info_free
202 #define snd_pcm_info_set_device psnd_pcm_info_set_device
203 #define snd_pcm_info_set_subdevice psnd_pcm_info_set_subdevice
204 #define snd_pcm_info_set_stream psnd_pcm_info_set_stream
205 #define snd_pcm_info_get_name psnd_pcm_info_get_name
206 #define snd_ctl_pcm_next_device psnd_ctl_pcm_next_device
207 #define snd_ctl_pcm_info psnd_ctl_pcm_info
208 #define snd_ctl_open psnd_ctl_open
209 #define snd_ctl_close psnd_ctl_close
210 #define snd_ctl_card_info_malloc psnd_ctl_card_info_malloc
211 #define snd_ctl_card_info_free psnd_ctl_card_info_free
212 #define snd_ctl_card_info psnd_ctl_card_info
213 #define snd_ctl_card_info_get_name psnd_ctl_card_info_get_name
214 #define snd_ctl_card_info_get_id psnd_ctl_card_info_get_id
215 #define snd_card_next psnd_card_next
216 #define snd_config_update_free_global psnd_config_update_free_global
221 struct HwParamsDeleter
{
222 void operator()(snd_pcm_hw_params_t
*ptr
) { snd_pcm_hw_params_free(ptr
); }
224 using HwParamsPtr
= std::unique_ptr
<snd_pcm_hw_params_t
,HwParamsDeleter
>;
225 HwParamsPtr
CreateHwParams()
227 snd_pcm_hw_params_t
*hp
{};
228 snd_pcm_hw_params_malloc(&hp
);
229 return HwParamsPtr
{hp
};
232 struct SwParamsDeleter
{
233 void operator()(snd_pcm_sw_params_t
*ptr
) { snd_pcm_sw_params_free(ptr
); }
235 using SwParamsPtr
= std::unique_ptr
<snd_pcm_sw_params_t
,SwParamsDeleter
>;
236 SwParamsPtr
CreateSwParams()
238 snd_pcm_sw_params_t
*sp
{};
239 snd_pcm_sw_params_malloc(&sp
);
240 return SwParamsPtr
{sp
};
246 std::string device_name
;
248 template<typename T
, typename U
>
249 DevMap(T
&& name_
, U
&& devname
)
250 : name
{std::forward
<T
>(name_
)}, device_name
{std::forward
<U
>(devname
)}
254 std::vector
<DevMap
> PlaybackDevices
;
255 std::vector
<DevMap
> CaptureDevices
;
258 const std::string_view
prefix_name(snd_pcm_stream_t stream
)
260 if(stream
== SND_PCM_STREAM_PLAYBACK
)
261 return "device-prefix"sv
;
262 return "capture-prefix"sv
;
265 struct SndCtlCardInfo
{
266 snd_ctl_card_info_t
*mInfo
{};
268 SndCtlCardInfo() { snd_ctl_card_info_malloc(&mInfo
); }
269 ~SndCtlCardInfo() { if(mInfo
) snd_ctl_card_info_free(mInfo
); }
270 SndCtlCardInfo(const SndCtlCardInfo
&) = delete;
271 SndCtlCardInfo
& operator=(const SndCtlCardInfo
&) = delete;
274 operator snd_ctl_card_info_t
*() const noexcept
{ return mInfo
; }
278 snd_pcm_info_t
*mInfo
{};
280 SndPcmInfo() { snd_pcm_info_malloc(&mInfo
); }
281 ~SndPcmInfo() { if(mInfo
) snd_pcm_info_free(mInfo
); }
282 SndPcmInfo(const SndPcmInfo
&) = delete;
283 SndPcmInfo
& operator=(const SndPcmInfo
&) = delete;
286 operator snd_pcm_info_t
*() const noexcept
{ return mInfo
; }
290 snd_ctl_t
*mHandle
{};
293 ~SndCtl() { if(mHandle
) snd_ctl_close(mHandle
); }
294 SndCtl(const SndCtl
&) = delete;
295 SndCtl
& operator=(const SndCtl
&) = delete;
298 auto open(const char *name
, int mode
) { return snd_ctl_open(&mHandle
, name
, mode
); }
301 operator snd_ctl_t
*() const noexcept
{ return mHandle
; }
305 std::vector
<DevMap
> probe_devices(snd_pcm_stream_t stream
)
307 std::vector
<DevMap
> devlist
;
312 auto defname
= ConfigValueStr({}, "alsa"sv
,
313 (stream
== SND_PCM_STREAM_PLAYBACK
) ? "device"sv
: "capture"sv
);
314 devlist
.emplace_back(GetDefaultName(), defname
? std::string_view
{*defname
} : "default"sv
);
316 if(auto customdevs
= ConfigValueStr({}, "alsa"sv
,
317 (stream
== SND_PCM_STREAM_PLAYBACK
) ? "custom-devices"sv
: "custom-captures"sv
))
319 size_t curpos
{customdevs
->find_first_not_of(';')};
320 while(curpos
< customdevs
->length())
322 size_t nextpos
{customdevs
->find(';', curpos
+1)};
323 const size_t seppos
{customdevs
->find('=', curpos
)};
324 if(seppos
== curpos
|| seppos
>= nextpos
)
326 const std::string spec
{customdevs
->substr(curpos
, nextpos
-curpos
)};
327 ERR("Invalid ALSA device specification \"%s\"\n", spec
.c_str());
331 const std::string_view strview
{*customdevs
};
332 const auto &entry
= devlist
.emplace_back(strview
.substr(curpos
, seppos
-curpos
),
333 strview
.substr(seppos
+1, nextpos
-seppos
-1));
334 TRACE("Got device \"%s\", \"%s\"\n", entry
.name
.c_str(), entry
.device_name
.c_str());
337 if(nextpos
< customdevs
->length())
338 nextpos
= customdevs
->find_first_not_of(';', nextpos
+1);
343 const std::string main_prefix
{ConfigValueStr({}, "alsa"sv
, prefix_name(stream
))
344 .value_or("plughw:")};
347 int err
{snd_card_next(&card
)};
348 for(;err
>= 0 && card
>= 0;err
= snd_card_next(&card
))
350 std::string name
{"hw:" + std::to_string(card
)};
353 err
= handle
.open(name
.c_str(), 0);
356 ERR("control open (hw:%d): %s\n", card
, snd_strerror(err
));
359 err
= snd_ctl_card_info(handle
, info
);
362 ERR("control hardware info (hw:%d): %s\n", card
, snd_strerror(err
));
366 const char *cardname
{snd_ctl_card_info_get_name(info
)};
367 const char *cardid
{snd_ctl_card_info_get_id(info
)};
368 name
= prefix_name(stream
);
371 const std::string card_prefix
{ConfigValueStr({}, "alsa"sv
, name
).value_or(main_prefix
)};
376 if(snd_ctl_pcm_next_device(handle
, &dev
) < 0)
377 ERR("snd_ctl_pcm_next_device failed\n");
380 snd_pcm_info_set_device(pcminfo
, static_cast<uint
>(dev
));
381 snd_pcm_info_set_subdevice(pcminfo
, 0);
382 snd_pcm_info_set_stream(pcminfo
, stream
);
383 err
= snd_ctl_pcm_info(handle
, pcminfo
);
387 ERR("control digital audio info (hw:%d): %s\n", card
, snd_strerror(err
));
391 /* "prefix-cardid-dev" */
392 name
= prefix_name(stream
);
396 name
+= std::to_string(dev
);
397 const std::string device_prefix
{ConfigValueStr({}, "alsa"sv
, name
)
398 .value_or(card_prefix
)};
400 /* "CardName, PcmName (CARD=cardid,DEV=dev)" */
403 name
+= snd_pcm_info_get_name(pcminfo
);
407 name
+= std::to_string(dev
);
410 /* "devprefixCARD=cardid,DEV=dev" */
411 std::string device
{device_prefix
};
415 device
+= std::to_string(dev
);
417 const auto &entry
= devlist
.emplace_back(std::move(name
), std::move(device
));
418 TRACE("Got device \"%s\", \"%s\"\n", entry
.name
.c_str(), entry
.device_name
.c_str());
422 ERR("snd_card_next failed: %s\n", snd_strerror(err
));
428 int verify_state(snd_pcm_t
*handle
)
430 snd_pcm_state_t state
{snd_pcm_state(handle
)};
434 case SND_PCM_STATE_OPEN
:
435 case SND_PCM_STATE_SETUP
:
436 case SND_PCM_STATE_PREPARED
:
437 case SND_PCM_STATE_RUNNING
:
438 case SND_PCM_STATE_DRAINING
:
439 case SND_PCM_STATE_PAUSED
:
443 case SND_PCM_STATE_XRUN
:
444 if(int err
{snd_pcm_recover(handle
, -EPIPE
, 1)}; err
< 0)
447 case SND_PCM_STATE_SUSPENDED
:
448 if(int err
{snd_pcm_recover(handle
, -ESTRPIPE
, 1)}; err
< 0)
452 case SND_PCM_STATE_DISCONNECTED
:
460 struct AlsaPlayback final
: public BackendBase
{
461 AlsaPlayback(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
462 ~AlsaPlayback() override
;
465 int mixerNoMMapProc();
467 void open(std::string_view name
) override
;
468 bool reset() override
;
469 void start() override
;
470 void stop() override
;
472 ClockLatency
getClockLatency() override
;
474 snd_pcm_t
*mPcmHandle
{nullptr};
479 std::vector
<std::byte
> mBuffer
;
481 std::atomic
<bool> mKillNow
{true};
485 AlsaPlayback::~AlsaPlayback()
488 snd_pcm_close(mPcmHandle
);
489 mPcmHandle
= nullptr;
493 int AlsaPlayback::mixerProc()
496 althrd_setname(MIXER_THREAD_NAME
);
498 const snd_pcm_uframes_t update_size
{mDevice
->UpdateSize
};
499 const snd_pcm_uframes_t buffer_size
{mDevice
->BufferSize
};
500 while(!mKillNow
.load(std::memory_order_acquire
))
502 int state
{verify_state(mPcmHandle
)};
505 ERR("Invalid state detected: %s\n", snd_strerror(state
));
506 mDevice
->handleDisconnect("Bad state: %s", snd_strerror(state
));
510 snd_pcm_sframes_t avails
{snd_pcm_avail_update(mPcmHandle
)};
513 ERR("available update failed: %s\n", snd_strerror(static_cast<int>(avails
)));
516 snd_pcm_uframes_t avail
{static_cast<snd_pcm_uframes_t
>(avails
)};
518 if(avail
> buffer_size
)
520 WARN("available samples exceeds the buffer size\n");
521 snd_pcm_reset(mPcmHandle
);
525 // make sure there's frames to process
526 if(avail
< update_size
)
528 if(state
!= SND_PCM_STATE_RUNNING
)
530 int err
{snd_pcm_start(mPcmHandle
)};
533 ERR("start failed: %s\n", snd_strerror(err
));
537 if(snd_pcm_wait(mPcmHandle
, 1000) == 0)
538 ERR("Wait timeout... buffer size too low?\n");
541 avail
-= avail
%update_size
;
543 // it is possible that contiguous areas are smaller, thus we use a loop
544 std::lock_guard
<std::mutex
> dlock
{mMutex
};
547 snd_pcm_uframes_t frames
{avail
};
549 const snd_pcm_channel_area_t
*areas
{};
550 snd_pcm_uframes_t offset
{};
551 int err
{snd_pcm_mmap_begin(mPcmHandle
, &areas
, &offset
, &frames
)};
554 ERR("mmap begin error: %s\n", snd_strerror(err
));
558 char *WritePtr
{static_cast<char*>(areas
->addr
) + (offset
* areas
->step
/ 8)};
559 mDevice
->renderSamples(WritePtr
, static_cast<uint
>(frames
), mFrameStep
);
561 snd_pcm_sframes_t commitres
{snd_pcm_mmap_commit(mPcmHandle
, offset
, frames
)};
562 if(commitres
< 0 || static_cast<snd_pcm_uframes_t
>(commitres
) != frames
)
564 ERR("mmap commit error: %s\n",
565 snd_strerror(commitres
>= 0 ? -EPIPE
: static_cast<int>(commitres
)));
576 int AlsaPlayback::mixerNoMMapProc()
579 althrd_setname(MIXER_THREAD_NAME
);
581 const snd_pcm_uframes_t update_size
{mDevice
->UpdateSize
};
582 const snd_pcm_uframes_t buffer_size
{mDevice
->BufferSize
};
583 while(!mKillNow
.load(std::memory_order_acquire
))
585 int state
{verify_state(mPcmHandle
)};
588 ERR("Invalid state detected: %s\n", snd_strerror(state
));
589 mDevice
->handleDisconnect("Bad state: %s", snd_strerror(state
));
593 snd_pcm_sframes_t avail
{snd_pcm_avail_update(mPcmHandle
)};
596 ERR("available update failed: %s\n", snd_strerror(static_cast<int>(avail
)));
600 if(static_cast<snd_pcm_uframes_t
>(avail
) > buffer_size
)
602 WARN("available samples exceeds the buffer size\n");
603 snd_pcm_reset(mPcmHandle
);
607 if(static_cast<snd_pcm_uframes_t
>(avail
) < update_size
)
609 if(state
!= SND_PCM_STATE_RUNNING
)
611 int err
{snd_pcm_start(mPcmHandle
)};
614 ERR("start failed: %s\n", snd_strerror(err
));
618 if(snd_pcm_wait(mPcmHandle
, 1000) == 0)
619 ERR("Wait timeout... buffer size too low?\n");
623 std::byte
*WritePtr
{mBuffer
.data()};
624 avail
= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
625 std::lock_guard
<std::mutex
> dlock
{mMutex
};
626 mDevice
->renderSamples(WritePtr
, static_cast<uint
>(avail
), mFrameStep
);
629 snd_pcm_sframes_t ret
{snd_pcm_writei(mPcmHandle
, WritePtr
,
630 static_cast<snd_pcm_uframes_t
>(avail
))};
635 #if ESTRPIPE != EPIPE
640 ret
= snd_pcm_recover(mPcmHandle
, static_cast<int>(ret
), 1);
647 WritePtr
+= snd_pcm_frames_to_bytes(mPcmHandle
, ret
);
654 ret
= snd_pcm_prepare(mPcmHandle
);
664 void AlsaPlayback::open(std::string_view name
)
666 std::string driver
{"default"};
669 if(PlaybackDevices
.empty())
670 PlaybackDevices
= probe_devices(SND_PCM_STREAM_PLAYBACK
);
672 auto iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
673 [name
](const DevMap
&entry
) -> bool { return entry
.name
== name
; });
674 if(iter
== PlaybackDevices
.cend())
675 throw al::backend_exception
{al::backend_error::NoDevice
,
676 "Device name \"%.*s\" not found", static_cast<int>(name
.length()), name
.data()};
677 driver
= iter
->device_name
;
681 name
= GetDefaultName();
682 if(auto driveropt
= ConfigValueStr({}, "alsa"sv
, "device"sv
))
683 driver
= std::move(driveropt
).value();
685 TRACE("Opening device \"%s\"\n", driver
.c_str());
687 snd_pcm_t
*pcmHandle
{};
688 int err
{snd_pcm_open(&pcmHandle
, driver
.c_str(), SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)};
690 throw al::backend_exception
{al::backend_error::NoDevice
,
691 "Could not open ALSA device \"%s\"", driver
.c_str()};
693 snd_pcm_close(mPcmHandle
);
694 mPcmHandle
= pcmHandle
;
696 /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */
697 snd_config_update_free_global();
699 mDevice
->DeviceName
= name
;
702 bool AlsaPlayback::reset()
704 snd_pcm_format_t format
{SND_PCM_FORMAT_UNKNOWN
};
705 switch(mDevice
->FmtType
)
708 format
= SND_PCM_FORMAT_S8
;
711 format
= SND_PCM_FORMAT_U8
;
714 format
= SND_PCM_FORMAT_S16
;
717 format
= SND_PCM_FORMAT_U16
;
720 format
= SND_PCM_FORMAT_S32
;
723 format
= SND_PCM_FORMAT_U32
;
726 format
= SND_PCM_FORMAT_FLOAT
;
730 bool allowmmap
{GetConfigValueBool(mDevice
->DeviceName
, "alsa"sv
, "mmap"sv
, true)};
731 uint periodLen
{static_cast<uint
>(mDevice
->UpdateSize
* 1000000_u64
/ mDevice
->Frequency
)};
732 uint bufferLen
{static_cast<uint
>(mDevice
->BufferSize
* 1000000_u64
/ mDevice
->Frequency
)};
733 uint rate
{mDevice
->Frequency
};
735 HwParamsPtr hp
{CreateHwParams()};
736 #define CHECK(x) do { \
737 if(int err{x}; err < 0) \
738 throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \
739 snd_strerror(err)}; \
741 CHECK(snd_pcm_hw_params_any(mPcmHandle
, hp
.get()));
742 /* set interleaved access */
744 || snd_pcm_hw_params_set_access(mPcmHandle
, hp
.get(), SND_PCM_ACCESS_MMAP_INTERLEAVED
) < 0)
747 CHECK(snd_pcm_hw_params_set_access(mPcmHandle
, hp
.get(), SND_PCM_ACCESS_RW_INTERLEAVED
));
749 /* test and set format (implicitly sets sample bits) */
750 if(snd_pcm_hw_params_test_format(mPcmHandle
, hp
.get(), format
) < 0)
753 snd_pcm_format_t format
;
756 static constexpr std::array formatlist
{
757 FormatMap
{SND_PCM_FORMAT_FLOAT
, DevFmtFloat
},
758 FormatMap
{SND_PCM_FORMAT_S32
, DevFmtInt
},
759 FormatMap
{SND_PCM_FORMAT_U32
, DevFmtUInt
},
760 FormatMap
{SND_PCM_FORMAT_S16
, DevFmtShort
},
761 FormatMap
{SND_PCM_FORMAT_U16
, DevFmtUShort
},
762 FormatMap
{SND_PCM_FORMAT_S8
, DevFmtByte
},
763 FormatMap
{SND_PCM_FORMAT_U8
, DevFmtUByte
},
766 for(const auto &fmt
: formatlist
)
769 if(snd_pcm_hw_params_test_format(mPcmHandle
, hp
.get(), format
) >= 0)
771 mDevice
->FmtType
= fmt
.fmttype
;
776 CHECK(snd_pcm_hw_params_set_format(mPcmHandle
, hp
.get(), format
));
777 /* set channels (implicitly sets frame bits) */
778 if(snd_pcm_hw_params_set_channels(mPcmHandle
, hp
.get(), mDevice
->channelsFromFmt()) < 0)
781 CHECK(snd_pcm_hw_params_set_channels_near(mPcmHandle
, hp
.get(), &numchans
));
783 throw al::backend_exception
{al::backend_error::DeviceError
, "Got 0 device channels"};
784 if(numchans
== 1) mDevice
->FmtChans
= DevFmtMono
;
785 else mDevice
->FmtChans
= DevFmtStereo
;
787 /* set rate (implicitly constrains period/buffer parameters) */
788 if(!GetConfigValueBool(mDevice
->DeviceName
, "alsa", "allow-resampler", false)
789 || !mDevice
->Flags
.test(FrequencyRequest
))
791 if(snd_pcm_hw_params_set_rate_resample(mPcmHandle
, hp
.get(), 0) < 0)
792 WARN("Failed to disable ALSA resampler\n");
794 else if(snd_pcm_hw_params_set_rate_resample(mPcmHandle
, hp
.get(), 1) < 0)
795 WARN("Failed to enable ALSA resampler\n");
796 CHECK(snd_pcm_hw_params_set_rate_near(mPcmHandle
, hp
.get(), &rate
, nullptr));
797 /* set period time (implicitly constrains period/buffer parameters) */
798 if(int err
{snd_pcm_hw_params_set_period_time_near(mPcmHandle
, hp
.get(), &periodLen
, nullptr)}; err
< 0)
799 ERR("snd_pcm_hw_params_set_period_time_near failed: %s\n", snd_strerror(err
));
800 /* set buffer time (implicitly sets buffer size/bytes/time and period size/bytes) */
801 if(int err
{snd_pcm_hw_params_set_buffer_time_near(mPcmHandle
, hp
.get(), &bufferLen
, nullptr)}; err
< 0)
802 ERR("snd_pcm_hw_params_set_buffer_time_near failed: %s\n", snd_strerror(err
));
803 /* install and prepare hardware configuration */
804 CHECK(snd_pcm_hw_params(mPcmHandle
, hp
.get()));
806 /* retrieve configuration info */
807 snd_pcm_uframes_t periodSizeInFrames
{};
808 snd_pcm_uframes_t bufferSizeInFrames
{};
809 snd_pcm_access_t access
{};
811 CHECK(snd_pcm_hw_params_get_access(hp
.get(), &access
));
812 CHECK(snd_pcm_hw_params_get_period_size(hp
.get(), &periodSizeInFrames
, nullptr));
813 CHECK(snd_pcm_hw_params_get_buffer_size(hp
.get(), &bufferSizeInFrames
));
814 CHECK(snd_pcm_hw_params_get_channels(hp
.get(), &mFrameStep
));
817 SwParamsPtr sp
{CreateSwParams()};
818 CHECK(snd_pcm_sw_params_current(mPcmHandle
, sp
.get()));
819 CHECK(snd_pcm_sw_params_set_avail_min(mPcmHandle
, sp
.get(), periodSizeInFrames
));
820 CHECK(snd_pcm_sw_params_set_stop_threshold(mPcmHandle
, sp
.get(), bufferSizeInFrames
));
821 CHECK(snd_pcm_sw_params(mPcmHandle
, sp
.get()));
825 mDevice
->BufferSize
= static_cast<uint
>(bufferSizeInFrames
);
826 mDevice
->UpdateSize
= static_cast<uint
>(periodSizeInFrames
);
827 mDevice
->Frequency
= rate
;
829 setDefaultChannelOrder();
834 void AlsaPlayback::start()
836 snd_pcm_access_t access
{};
837 HwParamsPtr hp
{CreateHwParams()};
838 #define CHECK(x) do { \
839 if(int err{x}; err < 0) \
840 throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \
841 snd_strerror(err)}; \
843 CHECK(snd_pcm_hw_params_current(mPcmHandle
, hp
.get()));
844 /* retrieve configuration info */
845 CHECK(snd_pcm_hw_params_get_access(hp
.get(), &access
));
848 int (AlsaPlayback::*thread_func
)(){};
849 if(access
== SND_PCM_ACCESS_RW_INTERLEAVED
)
851 auto datalen
= snd_pcm_frames_to_bytes(mPcmHandle
, mDevice
->UpdateSize
);
852 mBuffer
.resize(static_cast<size_t>(datalen
));
853 thread_func
= &AlsaPlayback::mixerNoMMapProc
;
857 CHECK(snd_pcm_prepare(mPcmHandle
));
858 thread_func
= &AlsaPlayback::mixerProc
;
863 mKillNow
.store(false, std::memory_order_release
);
864 mThread
= std::thread
{std::mem_fn(thread_func
), this};
866 catch(std::exception
& e
) {
867 throw al::backend_exception
{al::backend_error::DeviceError
,
868 "Failed to start mixing thread: %s", e
.what()};
872 void AlsaPlayback::stop()
874 if(mKillNow
.exchange(true, std::memory_order_acq_rel
) || !mThread
.joinable())
879 int err
{snd_pcm_drop(mPcmHandle
)};
881 ERR("snd_pcm_drop failed: %s\n", snd_strerror(err
));
884 ClockLatency
AlsaPlayback::getClockLatency()
888 std::lock_guard
<std::mutex
> dlock
{mMutex
};
889 ret
.ClockTime
= mDevice
->getClockTime();
890 snd_pcm_sframes_t delay
{};
891 int err
{snd_pcm_delay(mPcmHandle
, &delay
)};
894 ERR("Failed to get pcm delay: %s\n", snd_strerror(err
));
897 ret
.Latency
= std::chrono::seconds
{std::max
<snd_pcm_sframes_t
>(0, delay
)};
898 ret
.Latency
/= mDevice
->Frequency
;
904 struct AlsaCapture final
: public BackendBase
{
905 AlsaCapture(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
906 ~AlsaCapture() override
;
908 void open(std::string_view name
) override
;
909 void start() override
;
910 void stop() override
;
911 void captureSamples(std::byte
*buffer
, uint samples
) override
;
912 uint
availableSamples() override
;
913 ClockLatency
getClockLatency() override
;
915 snd_pcm_t
*mPcmHandle
{nullptr};
917 std::vector
<std::byte
> mBuffer
;
919 bool mDoCapture
{false};
920 RingBufferPtr mRing
{nullptr};
922 snd_pcm_sframes_t mLastAvail
{0};
925 AlsaCapture::~AlsaCapture()
928 snd_pcm_close(mPcmHandle
);
929 mPcmHandle
= nullptr;
933 void AlsaCapture::open(std::string_view name
)
935 std::string driver
{"default"};
938 if(CaptureDevices
.empty())
939 CaptureDevices
= probe_devices(SND_PCM_STREAM_CAPTURE
);
941 auto iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
942 [name
](const DevMap
&entry
) -> bool { return entry
.name
== name
; });
943 if(iter
== CaptureDevices
.cend())
944 throw al::backend_exception
{al::backend_error::NoDevice
,
945 "Device name \"%.*s\" not found", static_cast<int>(name
.length()), name
.data()};
946 driver
= iter
->device_name
;
950 name
= GetDefaultName();
951 if(auto driveropt
= ConfigValueStr({}, "alsa"sv
, "capture"sv
))
952 driver
= std::move(driveropt
).value();
955 TRACE("Opening device \"%s\"\n", driver
.c_str());
956 if(int err
{snd_pcm_open(&mPcmHandle
, driver
.c_str(), SND_PCM_STREAM_CAPTURE
, SND_PCM_NONBLOCK
)}; err
< 0)
957 throw al::backend_exception
{al::backend_error::NoDevice
,
958 "Could not open ALSA device \"%s\"", driver
.c_str()};
960 /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */
961 snd_config_update_free_global();
963 snd_pcm_format_t format
{SND_PCM_FORMAT_UNKNOWN
};
964 switch(mDevice
->FmtType
)
967 format
= SND_PCM_FORMAT_S8
;
970 format
= SND_PCM_FORMAT_U8
;
973 format
= SND_PCM_FORMAT_S16
;
976 format
= SND_PCM_FORMAT_U16
;
979 format
= SND_PCM_FORMAT_S32
;
982 format
= SND_PCM_FORMAT_U32
;
985 format
= SND_PCM_FORMAT_FLOAT
;
989 snd_pcm_uframes_t bufferSizeInFrames
{maxu(mDevice
->BufferSize
, 100*mDevice
->Frequency
/1000)};
990 snd_pcm_uframes_t periodSizeInFrames
{minu(mDevice
->BufferSize
, 25*mDevice
->Frequency
/1000)};
992 bool needring
{false};
993 HwParamsPtr hp
{CreateHwParams()};
994 #define CHECK(x) do { \
995 if(int err{x}; err < 0) \
996 throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \
997 snd_strerror(err)}; \
999 CHECK(snd_pcm_hw_params_any(mPcmHandle
, hp
.get()));
1000 /* set interleaved access */
1001 CHECK(snd_pcm_hw_params_set_access(mPcmHandle
, hp
.get(), SND_PCM_ACCESS_RW_INTERLEAVED
));
1002 /* set format (implicitly sets sample bits) */
1003 CHECK(snd_pcm_hw_params_set_format(mPcmHandle
, hp
.get(), format
));
1004 /* set channels (implicitly sets frame bits) */
1005 CHECK(snd_pcm_hw_params_set_channels(mPcmHandle
, hp
.get(), mDevice
->channelsFromFmt()));
1006 /* set rate (implicitly constrains period/buffer parameters) */
1007 CHECK(snd_pcm_hw_params_set_rate(mPcmHandle
, hp
.get(), mDevice
->Frequency
, 0));
1008 /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */
1009 if(snd_pcm_hw_params_set_buffer_size_min(mPcmHandle
, hp
.get(), &bufferSizeInFrames
) < 0)
1011 TRACE("Buffer too large, using intermediate ring buffer\n");
1013 CHECK(snd_pcm_hw_params_set_buffer_size_near(mPcmHandle
, hp
.get(), &bufferSizeInFrames
));
1015 /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */
1016 CHECK(snd_pcm_hw_params_set_period_size_near(mPcmHandle
, hp
.get(), &periodSizeInFrames
, nullptr));
1017 /* install and prepare hardware configuration */
1018 CHECK(snd_pcm_hw_params(mPcmHandle
, hp
.get()));
1019 /* retrieve configuration info */
1020 CHECK(snd_pcm_hw_params_get_period_size(hp
.get(), &periodSizeInFrames
, nullptr));
1025 mRing
= RingBuffer::Create(mDevice
->BufferSize
, mDevice
->frameSizeFromFmt(), false);
1027 mDevice
->DeviceName
= name
;
1031 void AlsaCapture::start()
1033 if(int err
{snd_pcm_prepare(mPcmHandle
)}; err
< 0)
1034 throw al::backend_exception
{al::backend_error::DeviceError
, "snd_pcm_prepare failed: %s",
1037 if(int err
{snd_pcm_start(mPcmHandle
)}; err
< 0)
1038 throw al::backend_exception
{al::backend_error::DeviceError
, "snd_pcm_start failed: %s",
1044 void AlsaCapture::stop()
1046 /* OpenAL requires access to unread audio after stopping, but ALSA's
1047 * snd_pcm_drain is unreliable and snd_pcm_drop drops it. Capture what's
1048 * available now so it'll be available later after the drop.
1050 uint avail
{availableSamples()};
1051 if(!mRing
&& avail
> 0)
1053 /* The ring buffer implicitly captures when checking availability.
1054 * Direct access needs to explicitly capture it into temp storage.
1056 auto temp
= std::vector
<std::byte
>(
1057 static_cast<size_t>(snd_pcm_frames_to_bytes(mPcmHandle
, avail
)));
1058 captureSamples(temp
.data(), avail
);
1059 mBuffer
= std::move(temp
);
1061 if(int err
{snd_pcm_drop(mPcmHandle
)}; err
< 0)
1062 ERR("drop failed: %s\n", snd_strerror(err
));
1066 void AlsaCapture::captureSamples(std::byte
*buffer
, uint samples
)
1070 std::ignore
= mRing
->read(buffer
, samples
);
1074 mLastAvail
-= samples
;
1075 while(mDevice
->Connected
.load(std::memory_order_acquire
) && samples
> 0)
1077 snd_pcm_sframes_t amt
{0};
1079 if(!mBuffer
.empty())
1081 /* First get any data stored from the last stop */
1082 amt
= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
1083 if(static_cast<snd_pcm_uframes_t
>(amt
) > samples
) amt
= samples
;
1085 amt
= snd_pcm_frames_to_bytes(mPcmHandle
, amt
);
1086 std::copy_n(mBuffer
.begin(), amt
, buffer
);
1088 mBuffer
.erase(mBuffer
.begin(), mBuffer
.begin()+amt
);
1089 amt
= snd_pcm_bytes_to_frames(mPcmHandle
, amt
);
1092 amt
= snd_pcm_readi(mPcmHandle
, buffer
, samples
);
1095 ERR("read error: %s\n", snd_strerror(static_cast<int>(amt
)));
1099 amt
= snd_pcm_recover(mPcmHandle
, static_cast<int>(amt
), 1);
1102 amt
= snd_pcm_start(mPcmHandle
);
1104 amt
= snd_pcm_avail_update(mPcmHandle
);
1108 const char *err
{snd_strerror(static_cast<int>(amt
))};
1109 ERR("restore error: %s\n", err
);
1110 mDevice
->handleDisconnect("Capture recovery failure: %s", err
);
1113 /* If the amount available is less than what's asked, we lost it
1114 * during recovery. So just give silence instead. */
1115 if(static_cast<snd_pcm_uframes_t
>(amt
) < samples
)
1120 buffer
= buffer
+ amt
;
1121 samples
-= static_cast<uint
>(amt
);
1124 std::fill_n(buffer
, snd_pcm_frames_to_bytes(mPcmHandle
, samples
),
1125 std::byte((mDevice
->FmtType
== DevFmtUByte
) ? 0x80 : 0));
1128 uint
AlsaCapture::availableSamples()
1130 snd_pcm_sframes_t avail
{0};
1131 if(mDevice
->Connected
.load(std::memory_order_acquire
) && mDoCapture
)
1132 avail
= snd_pcm_avail_update(mPcmHandle
);
1135 ERR("avail update failed: %s\n", snd_strerror(static_cast<int>(avail
)));
1137 avail
= snd_pcm_recover(mPcmHandle
, static_cast<int>(avail
), 1);
1141 avail
= snd_pcm_start(mPcmHandle
);
1143 avail
= snd_pcm_avail_update(mPcmHandle
);
1147 const char *err
{snd_strerror(static_cast<int>(avail
))};
1148 ERR("restore error: %s\n", err
);
1149 mDevice
->handleDisconnect("Capture recovery failure: %s", err
);
1155 if(avail
< 0) avail
= 0;
1156 avail
+= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
1157 if(avail
> mLastAvail
) mLastAvail
= avail
;
1158 return static_cast<uint
>(mLastAvail
);
1163 auto vec
= mRing
->getWriteVector();
1164 if(vec
.first
.len
== 0) break;
1166 snd_pcm_sframes_t amt
{std::min(static_cast<snd_pcm_sframes_t
>(vec
.first
.len
), avail
)};
1167 amt
= snd_pcm_readi(mPcmHandle
, vec
.first
.buf
, static_cast<snd_pcm_uframes_t
>(amt
));
1170 ERR("read error: %s\n", snd_strerror(static_cast<int>(amt
)));
1174 amt
= snd_pcm_recover(mPcmHandle
, static_cast<int>(amt
), 1);
1178 amt
= snd_pcm_start(mPcmHandle
);
1180 amt
= snd_pcm_avail_update(mPcmHandle
);
1184 const char *err
{snd_strerror(static_cast<int>(amt
))};
1185 ERR("restore error: %s\n", err
);
1186 mDevice
->handleDisconnect("Capture recovery failure: %s", err
);
1193 mRing
->writeAdvance(static_cast<snd_pcm_uframes_t
>(amt
));
1197 return static_cast<uint
>(mRing
->readSpace());
1200 ClockLatency
AlsaCapture::getClockLatency()
1204 ret
.ClockTime
= mDevice
->getClockTime();
1205 snd_pcm_sframes_t delay
{};
1206 int err
{snd_pcm_delay(mPcmHandle
, &delay
)};
1209 ERR("Failed to get pcm delay: %s\n", snd_strerror(err
));
1212 ret
.Latency
= std::chrono::seconds
{std::max
<snd_pcm_sframes_t
>(0, delay
)};
1213 ret
.Latency
/= mDevice
->Frequency
;
1221 bool AlsaBackendFactory::init()
1226 alsa_handle
= LoadLib("libasound.so.2");
1229 WARN("Failed to load %s\n", "libasound.so.2");
1233 std::string missing_funcs
;
1234 #define LOAD_FUNC(f) do { \
1235 p##f = reinterpret_cast<decltype(p##f)>(GetSymbol(alsa_handle, #f)); \
1236 if(p##f == nullptr) missing_funcs += "\n" #f; \
1238 ALSA_FUNCS(LOAD_FUNC
);
1241 if(!missing_funcs
.empty())
1243 WARN("Missing expected functions:%s\n", missing_funcs
.c_str());
1244 CloseLib(alsa_handle
);
1245 alsa_handle
= nullptr;
1254 bool AlsaBackendFactory::querySupport(BackendType type
)
1255 { return (type
== BackendType::Playback
|| type
== BackendType::Capture
); }
1257 std::string
AlsaBackendFactory::probe(BackendType type
)
1259 std::string outnames
;
1261 auto add_device
= [&outnames
](const DevMap
&entry
) -> void
1263 /* +1 to also append the null char (to ensure a null-separated list and
1264 * double-null terminated list).
1266 outnames
.append(entry
.name
.c_str(), entry
.name
.length()+1);
1270 case BackendType::Playback
:
1271 PlaybackDevices
= probe_devices(SND_PCM_STREAM_PLAYBACK
);
1272 std::for_each(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), add_device
);
1275 case BackendType::Capture
:
1276 CaptureDevices
= probe_devices(SND_PCM_STREAM_CAPTURE
);
1277 std::for_each(CaptureDevices
.cbegin(), CaptureDevices
.cend(), add_device
);
1284 BackendPtr
AlsaBackendFactory::createBackend(DeviceBase
*device
, BackendType type
)
1286 if(type
== BackendType::Playback
)
1287 return BackendPtr
{new AlsaPlayback
{device
}};
1288 if(type
== BackendType::Capture
)
1289 return BackendPtr
{new AlsaCapture
{device
}};
1293 BackendFactory
&AlsaBackendFactory::getFactory()
1295 static AlsaBackendFactory factory
{};