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
39 #include "alc/alconfig.h"
41 #include "alnumeric.h"
42 #include "aloptional.h"
43 #include "core/device.h"
44 #include "core/helpers.h"
45 #include "core/logging.h"
47 #include "ringbuffer.h"
51 #include <alsa/asoundlib.h>
56 constexpr char alsaDevice
[] = "ALSA Default";
60 #define ALSA_FUNCS(MAGIC) \
61 MAGIC(snd_strerror); \
62 MAGIC(snd_pcm_open); \
63 MAGIC(snd_pcm_close); \
64 MAGIC(snd_pcm_nonblock); \
65 MAGIC(snd_pcm_frames_to_bytes); \
66 MAGIC(snd_pcm_bytes_to_frames); \
67 MAGIC(snd_pcm_hw_params_malloc); \
68 MAGIC(snd_pcm_hw_params_free); \
69 MAGIC(snd_pcm_hw_params_any); \
70 MAGIC(snd_pcm_hw_params_current); \
71 MAGIC(snd_pcm_hw_params_get_access); \
72 MAGIC(snd_pcm_hw_params_get_buffer_size); \
73 MAGIC(snd_pcm_hw_params_get_buffer_time_min); \
74 MAGIC(snd_pcm_hw_params_get_buffer_time_max); \
75 MAGIC(snd_pcm_hw_params_get_channels); \
76 MAGIC(snd_pcm_hw_params_get_period_size); \
77 MAGIC(snd_pcm_hw_params_get_period_time_max); \
78 MAGIC(snd_pcm_hw_params_get_period_time_min); \
79 MAGIC(snd_pcm_hw_params_get_periods); \
80 MAGIC(snd_pcm_hw_params_set_access); \
81 MAGIC(snd_pcm_hw_params_set_buffer_size_min); \
82 MAGIC(snd_pcm_hw_params_set_buffer_size_near); \
83 MAGIC(snd_pcm_hw_params_set_buffer_time_near); \
84 MAGIC(snd_pcm_hw_params_set_channels); \
85 MAGIC(snd_pcm_hw_params_set_channels_near); \
86 MAGIC(snd_pcm_hw_params_set_format); \
87 MAGIC(snd_pcm_hw_params_set_period_time_near); \
88 MAGIC(snd_pcm_hw_params_set_period_size_near); \
89 MAGIC(snd_pcm_hw_params_set_periods_near); \
90 MAGIC(snd_pcm_hw_params_set_rate_near); \
91 MAGIC(snd_pcm_hw_params_set_rate); \
92 MAGIC(snd_pcm_hw_params_set_rate_resample); \
93 MAGIC(snd_pcm_hw_params_test_format); \
94 MAGIC(snd_pcm_hw_params_test_channels); \
95 MAGIC(snd_pcm_hw_params); \
96 MAGIC(snd_pcm_sw_params); \
97 MAGIC(snd_pcm_sw_params_current); \
98 MAGIC(snd_pcm_sw_params_free); \
99 MAGIC(snd_pcm_sw_params_malloc); \
100 MAGIC(snd_pcm_sw_params_set_avail_min); \
101 MAGIC(snd_pcm_sw_params_set_stop_threshold); \
102 MAGIC(snd_pcm_prepare); \
103 MAGIC(snd_pcm_start); \
104 MAGIC(snd_pcm_resume); \
105 MAGIC(snd_pcm_reset); \
106 MAGIC(snd_pcm_wait); \
107 MAGIC(snd_pcm_delay); \
108 MAGIC(snd_pcm_state); \
109 MAGIC(snd_pcm_avail_update); \
110 MAGIC(snd_pcm_mmap_begin); \
111 MAGIC(snd_pcm_mmap_commit); \
112 MAGIC(snd_pcm_readi); \
113 MAGIC(snd_pcm_writei); \
114 MAGIC(snd_pcm_drain); \
115 MAGIC(snd_pcm_drop); \
116 MAGIC(snd_pcm_recover); \
117 MAGIC(snd_pcm_info_malloc); \
118 MAGIC(snd_pcm_info_free); \
119 MAGIC(snd_pcm_info_set_device); \
120 MAGIC(snd_pcm_info_set_subdevice); \
121 MAGIC(snd_pcm_info_set_stream); \
122 MAGIC(snd_pcm_info_get_name); \
123 MAGIC(snd_ctl_pcm_next_device); \
124 MAGIC(snd_ctl_pcm_info); \
125 MAGIC(snd_ctl_open); \
126 MAGIC(snd_ctl_close); \
127 MAGIC(snd_ctl_card_info_malloc); \
128 MAGIC(snd_ctl_card_info_free); \
129 MAGIC(snd_ctl_card_info); \
130 MAGIC(snd_ctl_card_info_get_name); \
131 MAGIC(snd_ctl_card_info_get_id); \
132 MAGIC(snd_card_next); \
133 MAGIC(snd_config_update_free_global)
135 static void *alsa_handle
;
136 #define MAKE_FUNC(f) decltype(f) * p##f
137 ALSA_FUNCS(MAKE_FUNC
);
140 #ifndef IN_IDE_PARSER
141 #define snd_strerror psnd_strerror
142 #define snd_pcm_open psnd_pcm_open
143 #define snd_pcm_close psnd_pcm_close
144 #define snd_pcm_nonblock psnd_pcm_nonblock
145 #define snd_pcm_frames_to_bytes psnd_pcm_frames_to_bytes
146 #define snd_pcm_bytes_to_frames psnd_pcm_bytes_to_frames
147 #define snd_pcm_hw_params_malloc psnd_pcm_hw_params_malloc
148 #define snd_pcm_hw_params_free psnd_pcm_hw_params_free
149 #define snd_pcm_hw_params_any psnd_pcm_hw_params_any
150 #define snd_pcm_hw_params_current psnd_pcm_hw_params_current
151 #define snd_pcm_hw_params_set_access psnd_pcm_hw_params_set_access
152 #define snd_pcm_hw_params_set_format psnd_pcm_hw_params_set_format
153 #define snd_pcm_hw_params_set_channels psnd_pcm_hw_params_set_channels
154 #define snd_pcm_hw_params_set_channels_near psnd_pcm_hw_params_set_channels_near
155 #define snd_pcm_hw_params_set_periods_near psnd_pcm_hw_params_set_periods_near
156 #define snd_pcm_hw_params_set_rate_near psnd_pcm_hw_params_set_rate_near
157 #define snd_pcm_hw_params_set_rate psnd_pcm_hw_params_set_rate
158 #define snd_pcm_hw_params_set_rate_resample psnd_pcm_hw_params_set_rate_resample
159 #define snd_pcm_hw_params_set_buffer_time_near psnd_pcm_hw_params_set_buffer_time_near
160 #define snd_pcm_hw_params_set_period_time_near psnd_pcm_hw_params_set_period_time_near
161 #define snd_pcm_hw_params_set_buffer_size_near psnd_pcm_hw_params_set_buffer_size_near
162 #define snd_pcm_hw_params_set_period_size_near psnd_pcm_hw_params_set_period_size_near
163 #define snd_pcm_hw_params_set_buffer_size_min psnd_pcm_hw_params_set_buffer_size_min
164 #define snd_pcm_hw_params_get_buffer_time_min psnd_pcm_hw_params_get_buffer_time_min
165 #define snd_pcm_hw_params_get_buffer_time_max psnd_pcm_hw_params_get_buffer_time_max
166 #define snd_pcm_hw_params_get_period_time_min psnd_pcm_hw_params_get_period_time_min
167 #define snd_pcm_hw_params_get_period_time_max psnd_pcm_hw_params_get_period_time_max
168 #define snd_pcm_hw_params_get_buffer_size psnd_pcm_hw_params_get_buffer_size
169 #define snd_pcm_hw_params_get_period_size psnd_pcm_hw_params_get_period_size
170 #define snd_pcm_hw_params_get_access psnd_pcm_hw_params_get_access
171 #define snd_pcm_hw_params_get_periods psnd_pcm_hw_params_get_periods
172 #define snd_pcm_hw_params_get_channels psnd_pcm_hw_params_get_channels
173 #define snd_pcm_hw_params_test_format psnd_pcm_hw_params_test_format
174 #define snd_pcm_hw_params_test_channels psnd_pcm_hw_params_test_channels
175 #define snd_pcm_hw_params psnd_pcm_hw_params
176 #define snd_pcm_sw_params_malloc psnd_pcm_sw_params_malloc
177 #define snd_pcm_sw_params_current psnd_pcm_sw_params_current
178 #define snd_pcm_sw_params_set_avail_min psnd_pcm_sw_params_set_avail_min
179 #define snd_pcm_sw_params_set_stop_threshold psnd_pcm_sw_params_set_stop_threshold
180 #define snd_pcm_sw_params psnd_pcm_sw_params
181 #define snd_pcm_sw_params_free psnd_pcm_sw_params_free
182 #define snd_pcm_prepare psnd_pcm_prepare
183 #define snd_pcm_start psnd_pcm_start
184 #define snd_pcm_resume psnd_pcm_resume
185 #define snd_pcm_reset psnd_pcm_reset
186 #define snd_pcm_wait psnd_pcm_wait
187 #define snd_pcm_delay psnd_pcm_delay
188 #define snd_pcm_state psnd_pcm_state
189 #define snd_pcm_avail_update psnd_pcm_avail_update
190 #define snd_pcm_mmap_begin psnd_pcm_mmap_begin
191 #define snd_pcm_mmap_commit psnd_pcm_mmap_commit
192 #define snd_pcm_readi psnd_pcm_readi
193 #define snd_pcm_writei psnd_pcm_writei
194 #define snd_pcm_drain psnd_pcm_drain
195 #define snd_pcm_drop psnd_pcm_drop
196 #define snd_pcm_recover psnd_pcm_recover
197 #define snd_pcm_info_malloc psnd_pcm_info_malloc
198 #define snd_pcm_info_free psnd_pcm_info_free
199 #define snd_pcm_info_set_device psnd_pcm_info_set_device
200 #define snd_pcm_info_set_subdevice psnd_pcm_info_set_subdevice
201 #define snd_pcm_info_set_stream psnd_pcm_info_set_stream
202 #define snd_pcm_info_get_name psnd_pcm_info_get_name
203 #define snd_ctl_pcm_next_device psnd_ctl_pcm_next_device
204 #define snd_ctl_pcm_info psnd_ctl_pcm_info
205 #define snd_ctl_open psnd_ctl_open
206 #define snd_ctl_close psnd_ctl_close
207 #define snd_ctl_card_info_malloc psnd_ctl_card_info_malloc
208 #define snd_ctl_card_info_free psnd_ctl_card_info_free
209 #define snd_ctl_card_info psnd_ctl_card_info
210 #define snd_ctl_card_info_get_name psnd_ctl_card_info_get_name
211 #define snd_ctl_card_info_get_id psnd_ctl_card_info_get_id
212 #define snd_card_next psnd_card_next
213 #define snd_config_update_free_global psnd_config_update_free_global
218 struct HwParamsDeleter
{
219 void operator()(snd_pcm_hw_params_t
*ptr
) { snd_pcm_hw_params_free(ptr
); }
221 using HwParamsPtr
= std::unique_ptr
<snd_pcm_hw_params_t
,HwParamsDeleter
>;
222 HwParamsPtr
CreateHwParams()
224 snd_pcm_hw_params_t
*hp
{};
225 snd_pcm_hw_params_malloc(&hp
);
226 return HwParamsPtr
{hp
};
229 struct SwParamsDeleter
{
230 void operator()(snd_pcm_sw_params_t
*ptr
) { snd_pcm_sw_params_free(ptr
); }
232 using SwParamsPtr
= std::unique_ptr
<snd_pcm_sw_params_t
,SwParamsDeleter
>;
233 SwParamsPtr
CreateSwParams()
235 snd_pcm_sw_params_t
*sp
{};
236 snd_pcm_sw_params_malloc(&sp
);
237 return SwParamsPtr
{sp
};
243 std::string device_name
;
246 al::vector
<DevMap
> PlaybackDevices
;
247 al::vector
<DevMap
> CaptureDevices
;
250 const char *prefix_name(snd_pcm_stream_t stream
)
252 assert(stream
== SND_PCM_STREAM_PLAYBACK
|| stream
== SND_PCM_STREAM_CAPTURE
);
253 return (stream
==SND_PCM_STREAM_PLAYBACK
) ? "device-prefix" : "capture-prefix";
256 al::vector
<DevMap
> probe_devices(snd_pcm_stream_t stream
)
258 al::vector
<DevMap
> devlist
;
260 snd_ctl_card_info_t
*info
;
261 snd_ctl_card_info_malloc(&info
);
262 snd_pcm_info_t
*pcminfo
;
263 snd_pcm_info_malloc(&pcminfo
);
265 auto defname
= ConfigValueStr(nullptr, "alsa",
266 (stream
== SND_PCM_STREAM_PLAYBACK
) ? "device" : "capture");
267 devlist
.emplace_back(DevMap
{alsaDevice
, defname
? defname
->c_str() : "default"});
269 if(auto customdevs
= ConfigValueStr(nullptr, "alsa",
270 (stream
== SND_PCM_STREAM_PLAYBACK
) ? "custom-devices" : "custom-captures"))
272 size_t nextpos
{customdevs
->find_first_not_of(';')};
274 while((curpos
=nextpos
) < customdevs
->length())
276 nextpos
= customdevs
->find_first_of(';', curpos
+1);
278 size_t seppos
{customdevs
->find_first_of('=', curpos
)};
279 if(seppos
== curpos
|| seppos
>= nextpos
)
281 std::string spec
{customdevs
->substr(curpos
, nextpos
-curpos
)};
282 ERR("Invalid ALSA device specification \"%s\"\n", spec
.c_str());
286 devlist
.emplace_back(DevMap
{customdevs
->substr(curpos
, seppos
-curpos
),
287 customdevs
->substr(seppos
+1, nextpos
-seppos
-1)});
288 const auto &entry
= devlist
.back();
289 TRACE("Got device \"%s\", \"%s\"\n", entry
.name
.c_str(), entry
.device_name
.c_str());
292 if(nextpos
< customdevs
->length())
293 nextpos
= customdevs
->find_first_not_of(';', nextpos
+1);
297 const std::string main_prefix
{
298 ConfigValueStr(nullptr, "alsa", prefix_name(stream
)).value_or("plughw:")};
301 int err
{snd_card_next(&card
)};
302 for(;err
>= 0 && card
>= 0;err
= snd_card_next(&card
))
304 std::string name
{"hw:" + std::to_string(card
)};
307 if((err
=snd_ctl_open(&handle
, name
.c_str(), 0)) < 0)
309 ERR("control open (hw:%d): %s\n", card
, snd_strerror(err
));
312 if((err
=snd_ctl_card_info(handle
, info
)) < 0)
314 ERR("control hardware info (hw:%d): %s\n", card
, snd_strerror(err
));
315 snd_ctl_close(handle
);
319 const char *cardname
{snd_ctl_card_info_get_name(info
)};
320 const char *cardid
{snd_ctl_card_info_get_id(info
)};
321 name
= prefix_name(stream
);
324 const std::string card_prefix
{
325 ConfigValueStr(nullptr, "alsa", name
.c_str()).value_or(main_prefix
)};
330 if(snd_ctl_pcm_next_device(handle
, &dev
) < 0)
331 ERR("snd_ctl_pcm_next_device failed\n");
334 snd_pcm_info_set_device(pcminfo
, static_cast<uint
>(dev
));
335 snd_pcm_info_set_subdevice(pcminfo
, 0);
336 snd_pcm_info_set_stream(pcminfo
, stream
);
337 if((err
=snd_ctl_pcm_info(handle
, pcminfo
)) < 0)
340 ERR("control digital audio info (hw:%d): %s\n", card
, snd_strerror(err
));
344 /* "prefix-cardid-dev" */
345 name
= prefix_name(stream
);
349 name
+= std::to_string(dev
);
350 const std::string device_prefix
{
351 ConfigValueStr(nullptr, "alsa", name
.c_str()).value_or(card_prefix
)};
353 /* "CardName, PcmName (CARD=cardid,DEV=dev)" */
356 name
+= snd_pcm_info_get_name(pcminfo
);
360 name
+= std::to_string(dev
);
363 /* "devprefixCARD=cardid,DEV=dev" */
364 std::string device
{device_prefix
};
368 device
+= std::to_string(dev
);
370 devlist
.emplace_back(DevMap
{std::move(name
), std::move(device
)});
371 const auto &entry
= devlist
.back();
372 TRACE("Got device \"%s\", \"%s\"\n", entry
.name
.c_str(), entry
.device_name
.c_str());
374 snd_ctl_close(handle
);
377 ERR("snd_card_next failed: %s\n", snd_strerror(err
));
379 snd_pcm_info_free(pcminfo
);
380 snd_ctl_card_info_free(info
);
386 int verify_state(snd_pcm_t
*handle
)
388 snd_pcm_state_t state
{snd_pcm_state(handle
)};
393 case SND_PCM_STATE_OPEN
:
394 case SND_PCM_STATE_SETUP
:
395 case SND_PCM_STATE_PREPARED
:
396 case SND_PCM_STATE_RUNNING
:
397 case SND_PCM_STATE_DRAINING
:
398 case SND_PCM_STATE_PAUSED
:
402 case SND_PCM_STATE_XRUN
:
403 if((err
=snd_pcm_recover(handle
, -EPIPE
, 1)) < 0)
406 case SND_PCM_STATE_SUSPENDED
:
407 if((err
=snd_pcm_recover(handle
, -ESTRPIPE
, 1)) < 0)
410 case SND_PCM_STATE_DISCONNECTED
:
418 struct AlsaPlayback final
: public BackendBase
{
419 AlsaPlayback(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
420 ~AlsaPlayback() override
;
423 int mixerNoMMapProc();
425 void open(const char *name
) override
;
426 bool reset() override
;
427 void start() override
;
428 void stop() override
;
430 ClockLatency
getClockLatency() override
;
432 snd_pcm_t
*mPcmHandle
{nullptr};
437 al::vector
<al::byte
> mBuffer
;
439 std::atomic
<bool> mKillNow
{true};
442 DEF_NEWDEL(AlsaPlayback
)
445 AlsaPlayback::~AlsaPlayback()
448 snd_pcm_close(mPcmHandle
);
449 mPcmHandle
= nullptr;
453 int AlsaPlayback::mixerProc()
456 althrd_setname(MIXER_THREAD_NAME
);
458 const snd_pcm_uframes_t update_size
{mDevice
->UpdateSize
};
459 const snd_pcm_uframes_t buffer_size
{mDevice
->BufferSize
};
460 while(!mKillNow
.load(std::memory_order_acquire
))
462 int state
{verify_state(mPcmHandle
)};
465 ERR("Invalid state detected: %s\n", snd_strerror(state
));
466 mDevice
->handleDisconnect("Bad state: %s", snd_strerror(state
));
470 snd_pcm_sframes_t avails
{snd_pcm_avail_update(mPcmHandle
)};
473 ERR("available update failed: %s\n", snd_strerror(static_cast<int>(avails
)));
476 snd_pcm_uframes_t avail
{static_cast<snd_pcm_uframes_t
>(avails
)};
478 if(avail
> buffer_size
)
480 WARN("available samples exceeds the buffer size\n");
481 snd_pcm_reset(mPcmHandle
);
485 // make sure there's frames to process
486 if(avail
< update_size
)
488 if(state
!= SND_PCM_STATE_RUNNING
)
490 int err
{snd_pcm_start(mPcmHandle
)};
493 ERR("start failed: %s\n", snd_strerror(err
));
497 if(snd_pcm_wait(mPcmHandle
, 1000) == 0)
498 ERR("Wait timeout... buffer size too low?\n");
501 avail
-= avail
%update_size
;
503 // it is possible that contiguous areas are smaller, thus we use a loop
504 std::lock_guard
<std::mutex
> _
{mMutex
};
507 snd_pcm_uframes_t frames
{avail
};
509 const snd_pcm_channel_area_t
*areas
{};
510 snd_pcm_uframes_t offset
{};
511 int err
{snd_pcm_mmap_begin(mPcmHandle
, &areas
, &offset
, &frames
)};
514 ERR("mmap begin error: %s\n", snd_strerror(err
));
518 char *WritePtr
{static_cast<char*>(areas
->addr
) + (offset
* areas
->step
/ 8)};
519 mDevice
->renderSamples(WritePtr
, static_cast<uint
>(frames
), mFrameStep
);
521 snd_pcm_sframes_t commitres
{snd_pcm_mmap_commit(mPcmHandle
, offset
, frames
)};
522 if(commitres
< 0 || static_cast<snd_pcm_uframes_t
>(commitres
) != frames
)
524 ERR("mmap commit error: %s\n",
525 snd_strerror(commitres
>= 0 ? -EPIPE
: static_cast<int>(commitres
)));
536 int AlsaPlayback::mixerNoMMapProc()
539 althrd_setname(MIXER_THREAD_NAME
);
541 const snd_pcm_uframes_t update_size
{mDevice
->UpdateSize
};
542 const snd_pcm_uframes_t buffer_size
{mDevice
->BufferSize
};
543 while(!mKillNow
.load(std::memory_order_acquire
))
545 int state
{verify_state(mPcmHandle
)};
548 ERR("Invalid state detected: %s\n", snd_strerror(state
));
549 mDevice
->handleDisconnect("Bad state: %s", snd_strerror(state
));
553 snd_pcm_sframes_t avail
{snd_pcm_avail_update(mPcmHandle
)};
556 ERR("available update failed: %s\n", snd_strerror(static_cast<int>(avail
)));
560 if(static_cast<snd_pcm_uframes_t
>(avail
) > buffer_size
)
562 WARN("available samples exceeds the buffer size\n");
563 snd_pcm_reset(mPcmHandle
);
567 if(static_cast<snd_pcm_uframes_t
>(avail
) < update_size
)
569 if(state
!= SND_PCM_STATE_RUNNING
)
571 int err
{snd_pcm_start(mPcmHandle
)};
574 ERR("start failed: %s\n", snd_strerror(err
));
578 if(snd_pcm_wait(mPcmHandle
, 1000) == 0)
579 ERR("Wait timeout... buffer size too low?\n");
583 al::byte
*WritePtr
{mBuffer
.data()};
584 avail
= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
585 std::lock_guard
<std::mutex
> _
{mMutex
};
586 mDevice
->renderSamples(WritePtr
, static_cast<uint
>(avail
), mFrameStep
);
589 snd_pcm_sframes_t ret
{snd_pcm_writei(mPcmHandle
, WritePtr
,
590 static_cast<snd_pcm_uframes_t
>(avail
))};
595 #if ESTRPIPE != EPIPE
600 ret
= snd_pcm_recover(mPcmHandle
, static_cast<int>(ret
), 1);
607 WritePtr
+= snd_pcm_frames_to_bytes(mPcmHandle
, ret
);
614 ret
= snd_pcm_prepare(mPcmHandle
);
624 void AlsaPlayback::open(const char *name
)
626 al::optional
<std::string
> driveropt
;
627 const char *driver
{"default"};
630 if(PlaybackDevices
.empty())
631 PlaybackDevices
= probe_devices(SND_PCM_STREAM_PLAYBACK
);
633 auto iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
634 [name
](const DevMap
&entry
) -> bool { return entry
.name
== name
; });
635 if(iter
== PlaybackDevices
.cend())
636 throw al::backend_exception
{al::backend_error::NoDevice
,
637 "Device name \"%s\" not found", name
};
638 driver
= iter
->device_name
.c_str();
643 if(bool{driveropt
= ConfigValueStr(nullptr, "alsa", "device")})
644 driver
= driveropt
->c_str();
646 TRACE("Opening device \"%s\"\n", driver
);
648 snd_pcm_t
*pcmHandle
{};
649 int err
{snd_pcm_open(&pcmHandle
, driver
, SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)};
651 throw al::backend_exception
{al::backend_error::NoDevice
,
652 "Could not open ALSA device \"%s\"", driver
};
654 snd_pcm_close(mPcmHandle
);
655 mPcmHandle
= pcmHandle
;
657 /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */
658 snd_config_update_free_global();
660 mDevice
->DeviceName
= name
;
663 bool AlsaPlayback::reset()
665 snd_pcm_format_t format
{SND_PCM_FORMAT_UNKNOWN
};
666 switch(mDevice
->FmtType
)
669 format
= SND_PCM_FORMAT_S8
;
672 format
= SND_PCM_FORMAT_U8
;
675 format
= SND_PCM_FORMAT_S16
;
678 format
= SND_PCM_FORMAT_U16
;
681 format
= SND_PCM_FORMAT_S32
;
684 format
= SND_PCM_FORMAT_U32
;
687 format
= SND_PCM_FORMAT_FLOAT
;
691 bool allowmmap
{!!GetConfigValueBool(mDevice
->DeviceName
.c_str(), "alsa", "mmap", 1)};
692 uint periodLen
{static_cast<uint
>(mDevice
->UpdateSize
* 1000000_u64
/ mDevice
->Frequency
)};
693 uint bufferLen
{static_cast<uint
>(mDevice
->BufferSize
* 1000000_u64
/ mDevice
->Frequency
)};
694 uint rate
{mDevice
->Frequency
};
697 HwParamsPtr hp
{CreateHwParams()};
698 #define CHECK(x) do { \
700 throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \
701 snd_strerror(err)}; \
703 CHECK(snd_pcm_hw_params_any(mPcmHandle
, hp
.get()));
704 /* set interleaved access */
706 || snd_pcm_hw_params_set_access(mPcmHandle
, hp
.get(), SND_PCM_ACCESS_MMAP_INTERLEAVED
) < 0)
709 CHECK(snd_pcm_hw_params_set_access(mPcmHandle
, hp
.get(), SND_PCM_ACCESS_RW_INTERLEAVED
));
711 /* test and set format (implicitly sets sample bits) */
712 if(snd_pcm_hw_params_test_format(mPcmHandle
, hp
.get(), format
) < 0)
714 static const struct {
715 snd_pcm_format_t format
;
718 { SND_PCM_FORMAT_FLOAT
, DevFmtFloat
},
719 { SND_PCM_FORMAT_S32
, DevFmtInt
},
720 { SND_PCM_FORMAT_U32
, DevFmtUInt
},
721 { SND_PCM_FORMAT_S16
, DevFmtShort
},
722 { SND_PCM_FORMAT_U16
, DevFmtUShort
},
723 { SND_PCM_FORMAT_S8
, DevFmtByte
},
724 { SND_PCM_FORMAT_U8
, DevFmtUByte
},
727 for(const auto &fmt
: formatlist
)
730 if(snd_pcm_hw_params_test_format(mPcmHandle
, hp
.get(), format
) >= 0)
732 mDevice
->FmtType
= fmt
.fmttype
;
737 CHECK(snd_pcm_hw_params_set_format(mPcmHandle
, hp
.get(), format
));
738 /* set channels (implicitly sets frame bits) */
739 if(snd_pcm_hw_params_set_channels(mPcmHandle
, hp
.get(), mDevice
->channelsFromFmt()) < 0)
742 CHECK(snd_pcm_hw_params_set_channels_near(mPcmHandle
, hp
.get(), &numchans
));
744 throw al::backend_exception
{al::backend_error::DeviceError
, "Got 0 device channels"};
745 if(numchans
== 1) mDevice
->FmtChans
= DevFmtMono
;
746 else mDevice
->FmtChans
= DevFmtStereo
;
748 /* set rate (implicitly constrains period/buffer parameters) */
749 if(!GetConfigValueBool(mDevice
->DeviceName
.c_str(), "alsa", "allow-resampler", 0)
750 || !mDevice
->Flags
.test(FrequencyRequest
))
752 if(snd_pcm_hw_params_set_rate_resample(mPcmHandle
, hp
.get(), 0) < 0)
753 WARN("Failed to disable ALSA resampler\n");
755 else if(snd_pcm_hw_params_set_rate_resample(mPcmHandle
, hp
.get(), 1) < 0)
756 WARN("Failed to enable ALSA resampler\n");
757 CHECK(snd_pcm_hw_params_set_rate_near(mPcmHandle
, hp
.get(), &rate
, nullptr));
758 /* set period time (implicitly constrains period/buffer parameters) */
759 if((err
=snd_pcm_hw_params_set_period_time_near(mPcmHandle
, hp
.get(), &periodLen
, nullptr)) < 0)
760 ERR("snd_pcm_hw_params_set_period_time_near failed: %s\n", snd_strerror(err
));
761 /* set buffer time (implicitly sets buffer size/bytes/time and period size/bytes) */
762 if((err
=snd_pcm_hw_params_set_buffer_time_near(mPcmHandle
, hp
.get(), &bufferLen
, nullptr)) < 0)
763 ERR("snd_pcm_hw_params_set_buffer_time_near failed: %s\n", snd_strerror(err
));
764 /* install and prepare hardware configuration */
765 CHECK(snd_pcm_hw_params(mPcmHandle
, hp
.get()));
767 /* retrieve configuration info */
768 snd_pcm_uframes_t periodSizeInFrames
{};
769 snd_pcm_uframes_t bufferSizeInFrames
{};
770 snd_pcm_access_t access
{};
772 CHECK(snd_pcm_hw_params_get_access(hp
.get(), &access
));
773 CHECK(snd_pcm_hw_params_get_period_size(hp
.get(), &periodSizeInFrames
, nullptr));
774 CHECK(snd_pcm_hw_params_get_buffer_size(hp
.get(), &bufferSizeInFrames
));
775 CHECK(snd_pcm_hw_params_get_channels(hp
.get(), &mFrameStep
));
778 SwParamsPtr sp
{CreateSwParams()};
779 CHECK(snd_pcm_sw_params_current(mPcmHandle
, sp
.get()));
780 CHECK(snd_pcm_sw_params_set_avail_min(mPcmHandle
, sp
.get(), periodSizeInFrames
));
781 CHECK(snd_pcm_sw_params_set_stop_threshold(mPcmHandle
, sp
.get(), bufferSizeInFrames
));
782 CHECK(snd_pcm_sw_params(mPcmHandle
, sp
.get()));
786 mDevice
->BufferSize
= static_cast<uint
>(bufferSizeInFrames
);
787 mDevice
->UpdateSize
= static_cast<uint
>(periodSizeInFrames
);
788 mDevice
->Frequency
= rate
;
790 setDefaultChannelOrder();
795 void AlsaPlayback::start()
798 snd_pcm_access_t access
{};
799 HwParamsPtr hp
{CreateHwParams()};
800 #define CHECK(x) do { \
802 throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \
803 snd_strerror(err)}; \
805 CHECK(snd_pcm_hw_params_current(mPcmHandle
, hp
.get()));
806 /* retrieve configuration info */
807 CHECK(snd_pcm_hw_params_get_access(hp
.get(), &access
));
810 int (AlsaPlayback::*thread_func
)(){};
811 if(access
== SND_PCM_ACCESS_RW_INTERLEAVED
)
813 auto datalen
= snd_pcm_frames_to_bytes(mPcmHandle
, mDevice
->UpdateSize
);
814 mBuffer
.resize(static_cast<size_t>(datalen
));
815 thread_func
= &AlsaPlayback::mixerNoMMapProc
;
819 CHECK(snd_pcm_prepare(mPcmHandle
));
820 thread_func
= &AlsaPlayback::mixerProc
;
825 mKillNow
.store(false, std::memory_order_release
);
826 mThread
= std::thread
{std::mem_fn(thread_func
), this};
828 catch(std::exception
& e
) {
829 throw al::backend_exception
{al::backend_error::DeviceError
,
830 "Failed to start mixing thread: %s", e
.what()};
834 void AlsaPlayback::stop()
836 if(mKillNow
.exchange(true, std::memory_order_acq_rel
) || !mThread
.joinable())
841 int err
{snd_pcm_drop(mPcmHandle
)};
843 ERR("snd_pcm_drop failed: %s\n", snd_strerror(err
));
846 ClockLatency
AlsaPlayback::getClockLatency()
850 std::lock_guard
<std::mutex
> _
{mMutex
};
851 ret
.ClockTime
= GetDeviceClockTime(mDevice
);
852 snd_pcm_sframes_t delay
{};
853 int err
{snd_pcm_delay(mPcmHandle
, &delay
)};
856 ERR("Failed to get pcm delay: %s\n", snd_strerror(err
));
859 ret
.Latency
= std::chrono::seconds
{std::max
<snd_pcm_sframes_t
>(0, delay
)};
860 ret
.Latency
/= mDevice
->Frequency
;
866 struct AlsaCapture final
: public BackendBase
{
867 AlsaCapture(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
868 ~AlsaCapture() override
;
870 void open(const char *name
) override
;
871 void start() override
;
872 void stop() override
;
873 void captureSamples(al::byte
*buffer
, uint samples
) override
;
874 uint
availableSamples() override
;
875 ClockLatency
getClockLatency() override
;
877 snd_pcm_t
*mPcmHandle
{nullptr};
879 al::vector
<al::byte
> mBuffer
;
881 bool mDoCapture
{false};
882 RingBufferPtr mRing
{nullptr};
884 snd_pcm_sframes_t mLastAvail
{0};
886 DEF_NEWDEL(AlsaCapture
)
889 AlsaCapture::~AlsaCapture()
892 snd_pcm_close(mPcmHandle
);
893 mPcmHandle
= nullptr;
897 void AlsaCapture::open(const char *name
)
899 al::optional
<std::string
> driveropt
;
900 const char *driver
{"default"};
903 if(CaptureDevices
.empty())
904 CaptureDevices
= probe_devices(SND_PCM_STREAM_CAPTURE
);
906 auto iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
907 [name
](const DevMap
&entry
) -> bool { return entry
.name
== name
; });
908 if(iter
== CaptureDevices
.cend())
909 throw al::backend_exception
{al::backend_error::NoDevice
,
910 "Device name \"%s\" not found", name
};
911 driver
= iter
->device_name
.c_str();
916 if(bool{driveropt
= ConfigValueStr(nullptr, "alsa", "capture")})
917 driver
= driveropt
->c_str();
920 TRACE("Opening device \"%s\"\n", driver
);
921 int err
{snd_pcm_open(&mPcmHandle
, driver
, SND_PCM_STREAM_CAPTURE
, SND_PCM_NONBLOCK
)};
923 throw al::backend_exception
{al::backend_error::NoDevice
,
924 "Could not open ALSA device \"%s\"", driver
};
926 /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */
927 snd_config_update_free_global();
929 snd_pcm_format_t format
{SND_PCM_FORMAT_UNKNOWN
};
930 switch(mDevice
->FmtType
)
933 format
= SND_PCM_FORMAT_S8
;
936 format
= SND_PCM_FORMAT_U8
;
939 format
= SND_PCM_FORMAT_S16
;
942 format
= SND_PCM_FORMAT_U16
;
945 format
= SND_PCM_FORMAT_S32
;
948 format
= SND_PCM_FORMAT_U32
;
951 format
= SND_PCM_FORMAT_FLOAT
;
955 snd_pcm_uframes_t bufferSizeInFrames
{maxu(mDevice
->BufferSize
, 100*mDevice
->Frequency
/1000)};
956 snd_pcm_uframes_t periodSizeInFrames
{minu(mDevice
->BufferSize
, 25*mDevice
->Frequency
/1000)};
958 bool needring
{false};
959 HwParamsPtr hp
{CreateHwParams()};
960 #define CHECK(x) do { \
962 throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \
963 snd_strerror(err)}; \
965 CHECK(snd_pcm_hw_params_any(mPcmHandle
, hp
.get()));
966 /* set interleaved access */
967 CHECK(snd_pcm_hw_params_set_access(mPcmHandle
, hp
.get(), SND_PCM_ACCESS_RW_INTERLEAVED
));
968 /* set format (implicitly sets sample bits) */
969 CHECK(snd_pcm_hw_params_set_format(mPcmHandle
, hp
.get(), format
));
970 /* set channels (implicitly sets frame bits) */
971 CHECK(snd_pcm_hw_params_set_channels(mPcmHandle
, hp
.get(), mDevice
->channelsFromFmt()));
972 /* set rate (implicitly constrains period/buffer parameters) */
973 CHECK(snd_pcm_hw_params_set_rate(mPcmHandle
, hp
.get(), mDevice
->Frequency
, 0));
974 /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */
975 if(snd_pcm_hw_params_set_buffer_size_min(mPcmHandle
, hp
.get(), &bufferSizeInFrames
) < 0)
977 TRACE("Buffer too large, using intermediate ring buffer\n");
979 CHECK(snd_pcm_hw_params_set_buffer_size_near(mPcmHandle
, hp
.get(), &bufferSizeInFrames
));
981 /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */
982 CHECK(snd_pcm_hw_params_set_period_size_near(mPcmHandle
, hp
.get(), &periodSizeInFrames
, nullptr));
983 /* install and prepare hardware configuration */
984 CHECK(snd_pcm_hw_params(mPcmHandle
, hp
.get()));
985 /* retrieve configuration info */
986 CHECK(snd_pcm_hw_params_get_period_size(hp
.get(), &periodSizeInFrames
, nullptr));
991 mRing
= RingBuffer::Create(mDevice
->BufferSize
, mDevice
->frameSizeFromFmt(), false);
993 mDevice
->DeviceName
= name
;
997 void AlsaCapture::start()
999 int err
{snd_pcm_prepare(mPcmHandle
)};
1001 throw al::backend_exception
{al::backend_error::DeviceError
, "snd_pcm_prepare failed: %s",
1004 err
= snd_pcm_start(mPcmHandle
);
1006 throw al::backend_exception
{al::backend_error::DeviceError
, "snd_pcm_start failed: %s",
1012 void AlsaCapture::stop()
1014 /* OpenAL requires access to unread audio after stopping, but ALSA's
1015 * snd_pcm_drain is unreliable and snd_pcm_drop drops it. Capture what's
1016 * available now so it'll be available later after the drop.
1018 uint avail
{availableSamples()};
1019 if(!mRing
&& avail
> 0)
1021 /* The ring buffer implicitly captures when checking availability.
1022 * Direct access needs to explicitly capture it into temp storage.
1024 auto temp
= al::vector
<al::byte
>(
1025 static_cast<size_t>(snd_pcm_frames_to_bytes(mPcmHandle
, avail
)));
1026 captureSamples(temp
.data(), avail
);
1027 mBuffer
= std::move(temp
);
1029 int err
{snd_pcm_drop(mPcmHandle
)};
1031 ERR("drop failed: %s\n", snd_strerror(err
));
1035 void AlsaCapture::captureSamples(al::byte
*buffer
, uint samples
)
1039 mRing
->read(buffer
, samples
);
1043 mLastAvail
-= samples
;
1044 while(mDevice
->Connected
.load(std::memory_order_acquire
) && samples
> 0)
1046 snd_pcm_sframes_t amt
{0};
1048 if(!mBuffer
.empty())
1050 /* First get any data stored from the last stop */
1051 amt
= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
1052 if(static_cast<snd_pcm_uframes_t
>(amt
) > samples
) amt
= samples
;
1054 amt
= snd_pcm_frames_to_bytes(mPcmHandle
, amt
);
1055 std::copy_n(mBuffer
.begin(), amt
, buffer
);
1057 mBuffer
.erase(mBuffer
.begin(), mBuffer
.begin()+amt
);
1058 amt
= snd_pcm_bytes_to_frames(mPcmHandle
, amt
);
1061 amt
= snd_pcm_readi(mPcmHandle
, buffer
, samples
);
1064 ERR("read error: %s\n", snd_strerror(static_cast<int>(amt
)));
1068 if((amt
=snd_pcm_recover(mPcmHandle
, static_cast<int>(amt
), 1)) >= 0)
1070 amt
= snd_pcm_start(mPcmHandle
);
1072 amt
= snd_pcm_avail_update(mPcmHandle
);
1076 const char *err
{snd_strerror(static_cast<int>(amt
))};
1077 ERR("restore error: %s\n", err
);
1078 mDevice
->handleDisconnect("Capture recovery failure: %s", err
);
1081 /* If the amount available is less than what's asked, we lost it
1082 * during recovery. So just give silence instead. */
1083 if(static_cast<snd_pcm_uframes_t
>(amt
) < samples
)
1088 buffer
= buffer
+ amt
;
1089 samples
-= static_cast<uint
>(amt
);
1092 std::fill_n(buffer
, snd_pcm_frames_to_bytes(mPcmHandle
, samples
),
1093 al::byte((mDevice
->FmtType
== DevFmtUByte
) ? 0x80 : 0));
1096 uint
AlsaCapture::availableSamples()
1098 snd_pcm_sframes_t avail
{0};
1099 if(mDevice
->Connected
.load(std::memory_order_acquire
) && mDoCapture
)
1100 avail
= snd_pcm_avail_update(mPcmHandle
);
1103 ERR("avail update failed: %s\n", snd_strerror(static_cast<int>(avail
)));
1105 if((avail
=snd_pcm_recover(mPcmHandle
, static_cast<int>(avail
), 1)) >= 0)
1108 avail
= snd_pcm_start(mPcmHandle
);
1110 avail
= snd_pcm_avail_update(mPcmHandle
);
1114 const char *err
{snd_strerror(static_cast<int>(avail
))};
1115 ERR("restore error: %s\n", err
);
1116 mDevice
->handleDisconnect("Capture recovery failure: %s", err
);
1122 if(avail
< 0) avail
= 0;
1123 avail
+= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
1124 if(avail
> mLastAvail
) mLastAvail
= avail
;
1125 return static_cast<uint
>(mLastAvail
);
1130 auto vec
= mRing
->getWriteVector();
1131 if(vec
.first
.len
== 0) break;
1133 snd_pcm_sframes_t amt
{std::min(static_cast<snd_pcm_sframes_t
>(vec
.first
.len
), avail
)};
1134 amt
= snd_pcm_readi(mPcmHandle
, vec
.first
.buf
, static_cast<snd_pcm_uframes_t
>(amt
));
1137 ERR("read error: %s\n", snd_strerror(static_cast<int>(amt
)));
1141 if((amt
=snd_pcm_recover(mPcmHandle
, static_cast<int>(amt
), 1)) >= 0)
1144 amt
= snd_pcm_start(mPcmHandle
);
1146 amt
= snd_pcm_avail_update(mPcmHandle
);
1150 const char *err
{snd_strerror(static_cast<int>(amt
))};
1151 ERR("restore error: %s\n", err
);
1152 mDevice
->handleDisconnect("Capture recovery failure: %s", err
);
1159 mRing
->writeAdvance(static_cast<snd_pcm_uframes_t
>(amt
));
1163 return static_cast<uint
>(mRing
->readSpace());
1166 ClockLatency
AlsaCapture::getClockLatency()
1170 ret
.ClockTime
= GetDeviceClockTime(mDevice
);
1171 snd_pcm_sframes_t delay
{};
1172 int err
{snd_pcm_delay(mPcmHandle
, &delay
)};
1175 ERR("Failed to get pcm delay: %s\n", snd_strerror(err
));
1178 ret
.Latency
= std::chrono::seconds
{std::max
<snd_pcm_sframes_t
>(0, delay
)};
1179 ret
.Latency
/= mDevice
->Frequency
;
1187 bool AlsaBackendFactory::init()
1194 std::string missing_funcs
;
1196 alsa_handle
= LoadLib("libasound.so.2");
1199 WARN("Failed to load %s\n", "libasound.so.2");
1204 #define LOAD_FUNC(f) do { \
1205 p##f = reinterpret_cast<decltype(p##f)>(GetSymbol(alsa_handle, #f)); \
1206 if(p##f == nullptr) { \
1208 missing_funcs += "\n" #f; \
1211 ALSA_FUNCS(LOAD_FUNC
);
1216 WARN("Missing expected functions:%s\n", missing_funcs
.c_str());
1217 CloseLib(alsa_handle
);
1218 alsa_handle
= nullptr;
1226 bool AlsaBackendFactory::querySupport(BackendType type
)
1227 { return (type
== BackendType::Playback
|| type
== BackendType::Capture
); }
1229 std::string
AlsaBackendFactory::probe(BackendType type
)
1231 std::string outnames
;
1233 auto add_device
= [&outnames
](const DevMap
&entry
) -> void
1235 /* +1 to also append the null char (to ensure a null-separated list and
1236 * double-null terminated list).
1238 outnames
.append(entry
.name
.c_str(), entry
.name
.length()+1);
1242 case BackendType::Playback
:
1243 PlaybackDevices
= probe_devices(SND_PCM_STREAM_PLAYBACK
);
1244 std::for_each(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), add_device
);
1247 case BackendType::Capture
:
1248 CaptureDevices
= probe_devices(SND_PCM_STREAM_CAPTURE
);
1249 std::for_each(CaptureDevices
.cbegin(), CaptureDevices
.cend(), add_device
);
1256 BackendPtr
AlsaBackendFactory::createBackend(DeviceBase
*device
, BackendType type
)
1258 if(type
== BackendType::Playback
)
1259 return BackendPtr
{new AlsaPlayback
{device
}};
1260 if(type
== BackendType::Capture
)
1261 return BackendPtr
{new AlsaCapture
{device
}};
1265 BackendFactory
&AlsaBackendFactory::getFactory()
1267 static AlsaBackendFactory factory
{};