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
23 #include "backends/alsa.h"
44 #include "alnumeric.h"
45 #include "aloptional.h"
49 #include "ringbuffer.h"
53 #include <alsa/asoundlib.h>
58 constexpr ALCchar alsaDevice
[] = "ALSA Default";
62 #define ALSA_FUNCS(MAGIC) \
63 MAGIC(snd_strerror); \
64 MAGIC(snd_pcm_open); \
65 MAGIC(snd_pcm_close); \
66 MAGIC(snd_pcm_nonblock); \
67 MAGIC(snd_pcm_frames_to_bytes); \
68 MAGIC(snd_pcm_bytes_to_frames); \
69 MAGIC(snd_pcm_hw_params_malloc); \
70 MAGIC(snd_pcm_hw_params_free); \
71 MAGIC(snd_pcm_hw_params_any); \
72 MAGIC(snd_pcm_hw_params_current); \
73 MAGIC(snd_pcm_hw_params_set_access); \
74 MAGIC(snd_pcm_hw_params_set_format); \
75 MAGIC(snd_pcm_hw_params_set_channels); \
76 MAGIC(snd_pcm_hw_params_set_periods_near); \
77 MAGIC(snd_pcm_hw_params_set_rate_near); \
78 MAGIC(snd_pcm_hw_params_set_rate); \
79 MAGIC(snd_pcm_hw_params_set_rate_resample); \
80 MAGIC(snd_pcm_hw_params_set_buffer_time_near); \
81 MAGIC(snd_pcm_hw_params_set_period_time_near); \
82 MAGIC(snd_pcm_hw_params_set_buffer_size_near); \
83 MAGIC(snd_pcm_hw_params_set_period_size_near); \
84 MAGIC(snd_pcm_hw_params_set_buffer_size_min); \
85 MAGIC(snd_pcm_hw_params_get_buffer_time_min); \
86 MAGIC(snd_pcm_hw_params_get_buffer_time_max); \
87 MAGIC(snd_pcm_hw_params_get_period_time_min); \
88 MAGIC(snd_pcm_hw_params_get_period_time_max); \
89 MAGIC(snd_pcm_hw_params_get_buffer_size); \
90 MAGIC(snd_pcm_hw_params_get_period_size); \
91 MAGIC(snd_pcm_hw_params_get_access); \
92 MAGIC(snd_pcm_hw_params_get_periods); \
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_malloc); \
97 MAGIC(snd_pcm_sw_params_current); \
98 MAGIC(snd_pcm_sw_params_set_avail_min); \
99 MAGIC(snd_pcm_sw_params_set_stop_threshold); \
100 MAGIC(snd_pcm_sw_params); \
101 MAGIC(snd_pcm_sw_params_free); \
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_areas_silence); \
111 MAGIC(snd_pcm_mmap_begin); \
112 MAGIC(snd_pcm_mmap_commit); \
113 MAGIC(snd_pcm_readi); \
114 MAGIC(snd_pcm_writei); \
115 MAGIC(snd_pcm_drain); \
116 MAGIC(snd_pcm_drop); \
117 MAGIC(snd_pcm_recover); \
118 MAGIC(snd_pcm_info_malloc); \
119 MAGIC(snd_pcm_info_free); \
120 MAGIC(snd_pcm_info_set_device); \
121 MAGIC(snd_pcm_info_set_subdevice); \
122 MAGIC(snd_pcm_info_set_stream); \
123 MAGIC(snd_pcm_info_get_name); \
124 MAGIC(snd_ctl_pcm_next_device); \
125 MAGIC(snd_ctl_pcm_info); \
126 MAGIC(snd_ctl_open); \
127 MAGIC(snd_ctl_close); \
128 MAGIC(snd_ctl_card_info_malloc); \
129 MAGIC(snd_ctl_card_info_free); \
130 MAGIC(snd_ctl_card_info); \
131 MAGIC(snd_ctl_card_info_get_name); \
132 MAGIC(snd_ctl_card_info_get_id); \
133 MAGIC(snd_card_next); \
134 MAGIC(snd_config_update_free_global)
136 static void *alsa_handle
;
137 #define MAKE_FUNC(f) decltype(f) * p##f
138 ALSA_FUNCS(MAKE_FUNC
);
141 #ifndef IN_IDE_PARSER
142 #define snd_strerror psnd_strerror
143 #define snd_pcm_open psnd_pcm_open
144 #define snd_pcm_close psnd_pcm_close
145 #define snd_pcm_nonblock psnd_pcm_nonblock
146 #define snd_pcm_frames_to_bytes psnd_pcm_frames_to_bytes
147 #define snd_pcm_bytes_to_frames psnd_pcm_bytes_to_frames
148 #define snd_pcm_hw_params_malloc psnd_pcm_hw_params_malloc
149 #define snd_pcm_hw_params_free psnd_pcm_hw_params_free
150 #define snd_pcm_hw_params_any psnd_pcm_hw_params_any
151 #define snd_pcm_hw_params_current psnd_pcm_hw_params_current
152 #define snd_pcm_hw_params_set_access psnd_pcm_hw_params_set_access
153 #define snd_pcm_hw_params_set_format psnd_pcm_hw_params_set_format
154 #define snd_pcm_hw_params_set_channels psnd_pcm_hw_params_set_channels
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_test_format psnd_pcm_hw_params_test_format
173 #define snd_pcm_hw_params_test_channels psnd_pcm_hw_params_test_channels
174 #define snd_pcm_hw_params psnd_pcm_hw_params
175 #define snd_pcm_sw_params_malloc psnd_pcm_sw_params_malloc
176 #define snd_pcm_sw_params_current psnd_pcm_sw_params_current
177 #define snd_pcm_sw_params_set_avail_min psnd_pcm_sw_params_set_avail_min
178 #define snd_pcm_sw_params_set_stop_threshold psnd_pcm_sw_params_set_stop_threshold
179 #define snd_pcm_sw_params psnd_pcm_sw_params
180 #define snd_pcm_sw_params_free psnd_pcm_sw_params_free
181 #define snd_pcm_prepare psnd_pcm_prepare
182 #define snd_pcm_start psnd_pcm_start
183 #define snd_pcm_resume psnd_pcm_resume
184 #define snd_pcm_reset psnd_pcm_reset
185 #define snd_pcm_wait psnd_pcm_wait
186 #define snd_pcm_delay psnd_pcm_delay
187 #define snd_pcm_state psnd_pcm_state
188 #define snd_pcm_avail_update psnd_pcm_avail_update
189 #define snd_pcm_areas_silence psnd_pcm_areas_silence
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
220 std::string device_name
;
223 al::vector
<DevMap
> PlaybackDevices
;
224 al::vector
<DevMap
> CaptureDevices
;
227 const char *prefix_name(snd_pcm_stream_t stream
)
229 assert(stream
== SND_PCM_STREAM_PLAYBACK
|| stream
== SND_PCM_STREAM_CAPTURE
);
230 return (stream
==SND_PCM_STREAM_PLAYBACK
) ? "device-prefix" : "capture-prefix";
233 al::vector
<DevMap
> probe_devices(snd_pcm_stream_t stream
)
235 al::vector
<DevMap
> devlist
;
237 snd_ctl_card_info_t
*info
;
238 snd_ctl_card_info_malloc(&info
);
239 snd_pcm_info_t
*pcminfo
;
240 snd_pcm_info_malloc(&pcminfo
);
242 devlist
.emplace_back(DevMap
{alsaDevice
,
243 GetConfigValue(nullptr, "alsa", (stream
==SND_PCM_STREAM_PLAYBACK
) ? "device" : "capture",
246 if(stream
== SND_PCM_STREAM_PLAYBACK
)
248 const char *customdevs
;
249 const char *next
{GetConfigValue(nullptr, "alsa", "custom-devices", "")};
250 while((customdevs
=next
) != nullptr && customdevs
[0])
252 next
= strchr(customdevs
, ';');
253 const char *sep
{strchr(customdevs
, '=')};
256 std::string spec
{next
? std::string(customdevs
, next
++) : std::string(customdevs
)};
257 ERR("Invalid ALSA device specification \"%s\"\n", spec
.c_str());
261 const char *oldsep
{sep
++};
262 devlist
.emplace_back(DevMap
{std::string(customdevs
, oldsep
),
263 next
? std::string(sep
, next
++) : std::string(sep
)});
264 const auto &entry
= devlist
.back();
265 TRACE("Got device \"%s\", \"%s\"\n", entry
.name
.c_str(), entry
.device_name
.c_str());
269 const std::string main_prefix
{
270 ConfigValueStr(nullptr, "alsa", prefix_name(stream
)).value_or("plughw:")};
273 int err
{snd_card_next(&card
)};
274 for(;err
>= 0 && card
>= 0;err
= snd_card_next(&card
))
276 std::string name
{"hw:" + std::to_string(card
)};
279 if((err
=snd_ctl_open(&handle
, name
.c_str(), 0)) < 0)
281 ERR("control open (hw:%d): %s\n", card
, snd_strerror(err
));
284 if((err
=snd_ctl_card_info(handle
, info
)) < 0)
286 ERR("control hardware info (hw:%d): %s\n", card
, snd_strerror(err
));
287 snd_ctl_close(handle
);
291 const char *cardname
{snd_ctl_card_info_get_name(info
)};
292 const char *cardid
{snd_ctl_card_info_get_id(info
)};
293 name
= prefix_name(stream
);
296 const std::string card_prefix
{
297 ConfigValueStr(nullptr, "alsa", name
.c_str()).value_or(main_prefix
)};
302 if(snd_ctl_pcm_next_device(handle
, &dev
) < 0)
303 ERR("snd_ctl_pcm_next_device failed\n");
306 snd_pcm_info_set_device(pcminfo
, static_cast<ALuint
>(dev
));
307 snd_pcm_info_set_subdevice(pcminfo
, 0);
308 snd_pcm_info_set_stream(pcminfo
, stream
);
309 if((err
=snd_ctl_pcm_info(handle
, pcminfo
)) < 0)
312 ERR("control digital audio info (hw:%d): %s\n", card
, snd_strerror(err
));
316 /* "prefix-cardid-dev" */
317 name
= prefix_name(stream
);
321 name
+= std::to_string(dev
);
322 const std::string device_prefix
{
323 ConfigValueStr(nullptr, "alsa", name
.c_str()).value_or(card_prefix
)};
325 /* "CardName, PcmName (CARD=cardid,DEV=dev)" */
328 name
+= snd_pcm_info_get_name(pcminfo
);
332 name
+= std::to_string(dev
);
335 /* "devprefixCARD=cardid,DEV=dev" */
336 std::string device
{device_prefix
};
340 device
+= std::to_string(dev
);
342 devlist
.emplace_back(DevMap
{std::move(name
), std::move(device
)});
343 const auto &entry
= devlist
.back();
344 TRACE("Got device \"%s\", \"%s\"\n", entry
.name
.c_str(), entry
.device_name
.c_str());
346 snd_ctl_close(handle
);
349 ERR("snd_card_next failed: %s\n", snd_strerror(err
));
351 snd_pcm_info_free(pcminfo
);
352 snd_ctl_card_info_free(info
);
358 int verify_state(snd_pcm_t
*handle
)
360 snd_pcm_state_t state
{snd_pcm_state(handle
)};
365 case SND_PCM_STATE_OPEN
:
366 case SND_PCM_STATE_SETUP
:
367 case SND_PCM_STATE_PREPARED
:
368 case SND_PCM_STATE_RUNNING
:
369 case SND_PCM_STATE_DRAINING
:
370 case SND_PCM_STATE_PAUSED
:
374 case SND_PCM_STATE_XRUN
:
375 if((err
=snd_pcm_recover(handle
, -EPIPE
, 1)) < 0)
378 case SND_PCM_STATE_SUSPENDED
:
379 if((err
=snd_pcm_recover(handle
, -ESTRPIPE
, 1)) < 0)
382 case SND_PCM_STATE_DISCONNECTED
:
390 struct AlsaPlayback final
: public BackendBase
{
391 AlsaPlayback(ALCdevice
*device
) noexcept
: BackendBase
{device
} { }
392 ~AlsaPlayback() override
;
395 int mixerNoMMapProc();
397 ALCenum
open(const ALCchar
*name
) override
;
398 bool reset() override
;
399 bool start() override
;
400 void stop() override
;
402 ClockLatency
getClockLatency() override
;
404 snd_pcm_t
*mPcmHandle
{nullptr};
406 al::vector
<al::byte
> mBuffer
;
408 std::atomic
<bool> mKillNow
{true};
411 DEF_NEWDEL(AlsaPlayback
)
414 AlsaPlayback::~AlsaPlayback()
417 snd_pcm_close(mPcmHandle
);
418 mPcmHandle
= nullptr;
422 int AlsaPlayback::mixerProc()
425 althrd_setname(MIXER_THREAD_NAME
);
427 const snd_pcm_uframes_t update_size
{mDevice
->UpdateSize
};
428 const snd_pcm_uframes_t buffer_size
{mDevice
->BufferSize
};
429 while(!mKillNow
.load(std::memory_order_acquire
))
431 int state
{verify_state(mPcmHandle
)};
434 ERR("Invalid state detected: %s\n", snd_strerror(state
));
435 aluHandleDisconnect(mDevice
, "Bad state: %s", snd_strerror(state
));
439 snd_pcm_sframes_t avails
{snd_pcm_avail_update(mPcmHandle
)};
442 ERR("available update failed: %s\n", snd_strerror(static_cast<int>(avails
)));
445 snd_pcm_uframes_t avail
{static_cast<snd_pcm_uframes_t
>(avails
)};
447 if(avail
> buffer_size
)
449 WARN("available samples exceeds the buffer size\n");
450 snd_pcm_reset(mPcmHandle
);
454 // make sure there's frames to process
455 if(avail
< update_size
)
457 if(state
!= SND_PCM_STATE_RUNNING
)
459 int err
{snd_pcm_start(mPcmHandle
)};
462 ERR("start failed: %s\n", snd_strerror(err
));
466 if(snd_pcm_wait(mPcmHandle
, 1000) == 0)
467 ERR("Wait timeout... buffer size too low?\n");
470 avail
-= avail
%update_size
;
472 // it is possible that contiguous areas are smaller, thus we use a loop
476 snd_pcm_uframes_t frames
{avail
};
478 const snd_pcm_channel_area_t
*areas
{};
479 snd_pcm_uframes_t offset
{};
480 int err
{snd_pcm_mmap_begin(mPcmHandle
, &areas
, &offset
, &frames
)};
483 ERR("mmap begin error: %s\n", snd_strerror(err
));
487 char *WritePtr
{static_cast<char*>(areas
->addr
) + (offset
* areas
->step
/ 8)};
488 aluMixData(mDevice
, WritePtr
, static_cast<ALuint
>(frames
));
490 snd_pcm_sframes_t commitres
{snd_pcm_mmap_commit(mPcmHandle
, offset
, frames
)};
491 if(commitres
< 0 || (static_cast<snd_pcm_uframes_t
>(commitres
)-frames
) != 0)
493 ERR("mmap commit error: %s\n",
494 snd_strerror(commitres
>= 0 ? -EPIPE
: static_cast<int>(commitres
)));
506 int AlsaPlayback::mixerNoMMapProc()
509 althrd_setname(MIXER_THREAD_NAME
);
511 const snd_pcm_uframes_t update_size
{mDevice
->UpdateSize
};
512 const snd_pcm_uframes_t buffer_size
{mDevice
->BufferSize
};
513 while(!mKillNow
.load(std::memory_order_acquire
))
515 int state
{verify_state(mPcmHandle
)};
518 ERR("Invalid state detected: %s\n", snd_strerror(state
));
519 aluHandleDisconnect(mDevice
, "Bad state: %s", snd_strerror(state
));
523 snd_pcm_sframes_t avail
{snd_pcm_avail_update(mPcmHandle
)};
526 ERR("available update failed: %s\n", snd_strerror(static_cast<int>(avail
)));
530 if(static_cast<snd_pcm_uframes_t
>(avail
) > buffer_size
)
532 WARN("available samples exceeds the buffer size\n");
533 snd_pcm_reset(mPcmHandle
);
537 if(static_cast<snd_pcm_uframes_t
>(avail
) < update_size
)
539 if(state
!= SND_PCM_STATE_RUNNING
)
541 int err
{snd_pcm_start(mPcmHandle
)};
544 ERR("start failed: %s\n", snd_strerror(err
));
548 if(snd_pcm_wait(mPcmHandle
, 1000) == 0)
549 ERR("Wait timeout... buffer size too low?\n");
554 al::byte
*WritePtr
{mBuffer
.data()};
555 avail
= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
556 aluMixData(mDevice
, WritePtr
, static_cast<ALuint
>(avail
));
559 snd_pcm_sframes_t ret
{snd_pcm_writei(mPcmHandle
, WritePtr
,
560 static_cast<snd_pcm_uframes_t
>(avail
))};
565 #if ESTRPIPE != EPIPE
570 ret
= snd_pcm_recover(mPcmHandle
, static_cast<int>(ret
), 1);
577 WritePtr
+= snd_pcm_frames_to_bytes(mPcmHandle
, ret
);
584 ret
= snd_pcm_prepare(mPcmHandle
);
595 ALCenum
AlsaPlayback::open(const ALCchar
*name
)
597 const char *driver
{};
600 if(PlaybackDevices
.empty())
601 PlaybackDevices
= probe_devices(SND_PCM_STREAM_PLAYBACK
);
603 auto iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
604 [name
](const DevMap
&entry
) -> bool
605 { return entry
.name
== name
; }
607 if(iter
== PlaybackDevices
.cend())
608 return ALC_INVALID_VALUE
;
609 driver
= iter
->device_name
.c_str();
614 driver
= GetConfigValue(nullptr, "alsa", "device", "default");
617 TRACE("Opening device \"%s\"\n", driver
);
618 int err
{snd_pcm_open(&mPcmHandle
, driver
, SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)};
621 ERR("Could not open playback device '%s': %s\n", driver
, snd_strerror(err
));
622 return ALC_OUT_OF_MEMORY
;
625 /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */
626 snd_config_update_free_global();
628 mDevice
->DeviceName
= name
;
633 bool AlsaPlayback::reset()
635 snd_pcm_format_t format
{SND_PCM_FORMAT_UNKNOWN
};
636 switch(mDevice
->FmtType
)
639 format
= SND_PCM_FORMAT_S8
;
642 format
= SND_PCM_FORMAT_U8
;
645 format
= SND_PCM_FORMAT_S16
;
648 format
= SND_PCM_FORMAT_U16
;
651 format
= SND_PCM_FORMAT_S32
;
654 format
= SND_PCM_FORMAT_U32
;
657 format
= SND_PCM_FORMAT_FLOAT
;
661 bool allowmmap
{!!GetConfigValueBool(mDevice
->DeviceName
.c_str(), "alsa", "mmap", 1)};
662 ALuint periodLen
{static_cast<ALuint
>(mDevice
->UpdateSize
* 1000000_u64
/ mDevice
->Frequency
)};
663 ALuint bufferLen
{static_cast<ALuint
>(mDevice
->BufferSize
* 1000000_u64
/ mDevice
->Frequency
)};
664 ALuint rate
{mDevice
->Frequency
};
666 snd_pcm_uframes_t periodSizeInFrames
{};
667 snd_pcm_uframes_t bufferSizeInFrames
{};
668 snd_pcm_sw_params_t
*sp
{};
669 snd_pcm_hw_params_t
*hp
{};
670 snd_pcm_access_t access
{};
671 const char *funcerr
{};
674 snd_pcm_hw_params_malloc(&hp
);
675 #define CHECK(x) if((funcerr=#x),(err=(x)) < 0) goto error
676 CHECK(snd_pcm_hw_params_any(mPcmHandle
, hp
));
677 /* set interleaved access */
678 if(!allowmmap
|| snd_pcm_hw_params_set_access(mPcmHandle
, hp
, SND_PCM_ACCESS_MMAP_INTERLEAVED
) < 0)
681 CHECK(snd_pcm_hw_params_set_access(mPcmHandle
, hp
, SND_PCM_ACCESS_RW_INTERLEAVED
));
683 /* test and set format (implicitly sets sample bits) */
684 if(snd_pcm_hw_params_test_format(mPcmHandle
, hp
, format
) < 0)
686 static const struct {
687 snd_pcm_format_t format
;
690 { SND_PCM_FORMAT_FLOAT
, DevFmtFloat
},
691 { SND_PCM_FORMAT_S32
, DevFmtInt
},
692 { SND_PCM_FORMAT_U32
, DevFmtUInt
},
693 { SND_PCM_FORMAT_S16
, DevFmtShort
},
694 { SND_PCM_FORMAT_U16
, DevFmtUShort
},
695 { SND_PCM_FORMAT_S8
, DevFmtByte
},
696 { SND_PCM_FORMAT_U8
, DevFmtUByte
},
699 for(const auto &fmt
: formatlist
)
702 if(snd_pcm_hw_params_test_format(mPcmHandle
, hp
, format
) >= 0)
704 mDevice
->FmtType
= fmt
.fmttype
;
709 CHECK(snd_pcm_hw_params_set_format(mPcmHandle
, hp
, format
));
710 /* test and set channels (implicitly sets frame bits) */
711 if(snd_pcm_hw_params_test_channels(mPcmHandle
, hp
, mDevice
->channelsFromFmt()) < 0)
713 static const DevFmtChannels channellist
[] = {
721 for(const auto &chan
: channellist
)
723 if(snd_pcm_hw_params_test_channels(mPcmHandle
, hp
, ChannelsFromDevFmt(chan
, 0)) >= 0)
725 mDevice
->FmtChans
= chan
;
726 mDevice
->mAmbiOrder
= 0;
731 CHECK(snd_pcm_hw_params_set_channels(mPcmHandle
, hp
, mDevice
->channelsFromFmt()));
732 /* set rate (implicitly constrains period/buffer parameters) */
733 if(!GetConfigValueBool(mDevice
->DeviceName
.c_str(), "alsa", "allow-resampler", 0) ||
734 !mDevice
->Flags
.get
<FrequencyRequest
>())
736 if(snd_pcm_hw_params_set_rate_resample(mPcmHandle
, hp
, 0) < 0)
737 ERR("Failed to disable ALSA resampler\n");
739 else if(snd_pcm_hw_params_set_rate_resample(mPcmHandle
, hp
, 1) < 0)
740 ERR("Failed to enable ALSA resampler\n");
741 CHECK(snd_pcm_hw_params_set_rate_near(mPcmHandle
, hp
, &rate
, nullptr));
742 /* set period time (implicitly constrains period/buffer parameters) */
743 if((err
=snd_pcm_hw_params_set_period_time_near(mPcmHandle
, hp
, &periodLen
, nullptr)) < 0)
744 ERR("snd_pcm_hw_params_set_period_time_near failed: %s\n", snd_strerror(err
));
745 /* set buffer time (implicitly sets buffer size/bytes/time and period size/bytes) */
746 if((err
=snd_pcm_hw_params_set_buffer_time_near(mPcmHandle
, hp
, &bufferLen
, nullptr)) < 0)
747 ERR("snd_pcm_hw_params_set_buffer_time_near failed: %s\n", snd_strerror(err
));
748 /* install and prepare hardware configuration */
749 CHECK(snd_pcm_hw_params(mPcmHandle
, hp
));
751 /* retrieve configuration info */
752 CHECK(snd_pcm_hw_params_get_access(hp
, &access
));
753 CHECK(snd_pcm_hw_params_get_period_size(hp
, &periodSizeInFrames
, nullptr));
754 CHECK(snd_pcm_hw_params_get_buffer_size(hp
, &bufferSizeInFrames
));
755 snd_pcm_hw_params_free(hp
);
758 snd_pcm_sw_params_malloc(&sp
);
759 CHECK(snd_pcm_sw_params_current(mPcmHandle
, sp
));
760 CHECK(snd_pcm_sw_params_set_avail_min(mPcmHandle
, sp
, periodSizeInFrames
));
761 CHECK(snd_pcm_sw_params_set_stop_threshold(mPcmHandle
, sp
, bufferSizeInFrames
));
762 CHECK(snd_pcm_sw_params(mPcmHandle
, sp
));
764 snd_pcm_sw_params_free(sp
);
767 mDevice
->BufferSize
= static_cast<ALuint
>(bufferSizeInFrames
);
768 mDevice
->UpdateSize
= static_cast<ALuint
>(periodSizeInFrames
);
769 mDevice
->Frequency
= rate
;
771 SetDefaultChannelOrder(mDevice
);
776 ERR("%s failed: %s\n", funcerr
, snd_strerror(err
));
777 if(hp
) snd_pcm_hw_params_free(hp
);
778 if(sp
) snd_pcm_sw_params_free(sp
);
782 bool AlsaPlayback::start()
784 snd_pcm_hw_params_t
*hp
{};
785 snd_pcm_access_t access
;
789 snd_pcm_hw_params_malloc(&hp
);
790 #define CHECK(x) if((funcerr=#x),(err=(x)) < 0) goto error
791 CHECK(snd_pcm_hw_params_current(mPcmHandle
, hp
));
792 /* retrieve configuration info */
793 CHECK(snd_pcm_hw_params_get_access(hp
, &access
));
798 ERR("%s failed: %s\n", funcerr
, snd_strerror(err
));
799 if(hp
) snd_pcm_hw_params_free(hp
);
802 snd_pcm_hw_params_free(hp
);
805 int (AlsaPlayback::*thread_func
)(){};
806 if(access
== SND_PCM_ACCESS_RW_INTERLEAVED
)
809 static_cast<size_t>(snd_pcm_frames_to_bytes(mPcmHandle
, mDevice
->UpdateSize
)));
810 thread_func
= &AlsaPlayback::mixerNoMMapProc
;
814 err
= snd_pcm_prepare(mPcmHandle
);
817 ERR("snd_pcm_prepare(data->mPcmHandle) failed: %s\n", snd_strerror(err
));
820 thread_func
= &AlsaPlayback::mixerProc
;
824 mKillNow
.store(false, std::memory_order_release
);
825 mThread
= std::thread
{std::mem_fn(thread_func
), this};
828 catch(std::exception
& e
) {
829 ERR("Could not create playback thread: %s\n", e
.what());
837 void AlsaPlayback::stop()
839 if(mKillNow
.exchange(true, std::memory_order_acq_rel
) || !mThread
.joinable())
846 ClockLatency
AlsaPlayback::getClockLatency()
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
;
867 struct AlsaCapture final
: public BackendBase
{
868 AlsaCapture(ALCdevice
*device
) noexcept
: BackendBase
{device
} { }
869 ~AlsaCapture() override
;
871 ALCenum
open(const ALCchar
*name
) override
;
872 bool start() override
;
873 void stop() override
;
874 ALCenum
captureSamples(al::byte
*buffer
, ALCuint samples
) override
;
875 ALCuint
availableSamples() override
;
876 ClockLatency
getClockLatency() override
;
878 snd_pcm_t
*mPcmHandle
{nullptr};
880 al::vector
<al::byte
> mBuffer
;
882 bool mDoCapture
{false};
883 RingBufferPtr mRing
{nullptr};
885 snd_pcm_sframes_t mLastAvail
{0};
887 DEF_NEWDEL(AlsaCapture
)
890 AlsaCapture::~AlsaCapture()
893 snd_pcm_close(mPcmHandle
);
894 mPcmHandle
= nullptr;
898 ALCenum
AlsaCapture::open(const ALCchar
*name
)
900 const char *driver
{};
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
908 { return entry
.name
== name
; }
910 if(iter
== CaptureDevices
.cend())
911 return ALC_INVALID_VALUE
;
912 driver
= iter
->device_name
.c_str();
917 driver
= GetConfigValue(nullptr, "alsa", "capture", "default");
920 TRACE("Opening device \"%s\"\n", driver
);
921 int err
{snd_pcm_open(&mPcmHandle
, driver
, SND_PCM_STREAM_CAPTURE
, SND_PCM_NONBLOCK
)};
924 ERR("Could not open capture device '%s': %s\n", driver
, snd_strerror(err
));
925 return ALC_INVALID_VALUE
;
928 /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */
929 snd_config_update_free_global();
931 snd_pcm_format_t format
{SND_PCM_FORMAT_UNKNOWN
};
932 switch(mDevice
->FmtType
)
935 format
= SND_PCM_FORMAT_S8
;
938 format
= SND_PCM_FORMAT_U8
;
941 format
= SND_PCM_FORMAT_S16
;
944 format
= SND_PCM_FORMAT_U16
;
947 format
= SND_PCM_FORMAT_S32
;
950 format
= SND_PCM_FORMAT_U32
;
953 format
= SND_PCM_FORMAT_FLOAT
;
957 snd_pcm_uframes_t bufferSizeInFrames
{maxu(mDevice
->BufferSize
, 100*mDevice
->Frequency
/1000)};
958 snd_pcm_uframes_t periodSizeInFrames
{minu(mDevice
->BufferSize
, 25*mDevice
->Frequency
/1000)};
960 bool needring
{false};
961 const char *funcerr
{};
962 snd_pcm_hw_params_t
*hp
{};
963 snd_pcm_hw_params_malloc(&hp
);
964 #define CHECK(x) if((funcerr=#x),(err=(x)) < 0) goto error
965 CHECK(snd_pcm_hw_params_any(mPcmHandle
, hp
));
966 /* set interleaved access */
967 CHECK(snd_pcm_hw_params_set_access(mPcmHandle
, hp
, SND_PCM_ACCESS_RW_INTERLEAVED
));
968 /* set format (implicitly sets sample bits) */
969 CHECK(snd_pcm_hw_params_set_format(mPcmHandle
, hp
, format
));
970 /* set channels (implicitly sets frame bits) */
971 CHECK(snd_pcm_hw_params_set_channels(mPcmHandle
, hp
, mDevice
->channelsFromFmt()));
972 /* set rate (implicitly constrains period/buffer parameters) */
973 CHECK(snd_pcm_hw_params_set_rate(mPcmHandle
, hp
, 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
, &bufferSizeInFrames
) < 0)
977 TRACE("Buffer too large, using intermediate ring buffer\n");
979 CHECK(snd_pcm_hw_params_set_buffer_size_near(mPcmHandle
, hp
, &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
, &periodSizeInFrames
, nullptr));
983 /* install and prepare hardware configuration */
984 CHECK(snd_pcm_hw_params(mPcmHandle
, hp
));
985 /* retrieve configuration info */
986 CHECK(snd_pcm_hw_params_get_period_size(hp
, &periodSizeInFrames
, nullptr));
988 snd_pcm_hw_params_free(hp
);
993 mRing
= CreateRingBuffer(mDevice
->BufferSize
, mDevice
->frameSizeFromFmt(), false);
996 ERR("ring buffer create failed\n");
1001 mDevice
->DeviceName
= name
;
1003 return ALC_NO_ERROR
;
1006 ERR("%s failed: %s\n", funcerr
, snd_strerror(err
));
1007 if(hp
) snd_pcm_hw_params_free(hp
);
1011 snd_pcm_close(mPcmHandle
);
1012 mPcmHandle
= nullptr;
1014 return ALC_INVALID_VALUE
;
1018 bool AlsaCapture::start()
1020 int err
{snd_pcm_prepare(mPcmHandle
)};
1022 ERR("prepare failed: %s\n", snd_strerror(err
));
1025 err
= snd_pcm_start(mPcmHandle
);
1027 ERR("start failed: %s\n", snd_strerror(err
));
1031 aluHandleDisconnect(mDevice
, "Capture state failure: %s", snd_strerror(err
));
1039 void AlsaCapture::stop()
1041 /* OpenAL requires access to unread audio after stopping, but ALSA's
1042 * snd_pcm_drain is unreliable and snd_pcm_drop drops it. Capture what's
1043 * available now so it'll be available later after the drop.
1045 ALCuint avail
{availableSamples()};
1046 if(!mRing
&& avail
> 0)
1048 /* The ring buffer implicitly captures when checking availability.
1049 * Direct access needs to explicitly capture it into temp storage. */
1050 auto temp
= al::vector
<al::byte
>(
1051 static_cast<size_t>(snd_pcm_frames_to_bytes(mPcmHandle
, avail
)));
1052 captureSamples(temp
.data(), avail
);
1053 mBuffer
= std::move(temp
);
1055 int err
{snd_pcm_drop(mPcmHandle
)};
1057 ERR("drop failed: %s\n", snd_strerror(err
));
1061 ALCenum
AlsaCapture::captureSamples(al::byte
*buffer
, ALCuint samples
)
1065 mRing
->read(buffer
, samples
);
1066 return ALC_NO_ERROR
;
1069 mLastAvail
-= samples
;
1070 while(mDevice
->Connected
.load(std::memory_order_acquire
) && samples
> 0)
1072 snd_pcm_sframes_t amt
{0};
1074 if(!mBuffer
.empty())
1076 /* First get any data stored from the last stop */
1077 amt
= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
1078 if(static_cast<snd_pcm_uframes_t
>(amt
) > samples
) amt
= samples
;
1080 amt
= snd_pcm_frames_to_bytes(mPcmHandle
, amt
);
1081 std::copy_n(mBuffer
.begin(), amt
, buffer
);
1083 mBuffer
.erase(mBuffer
.begin(), mBuffer
.begin()+amt
);
1084 amt
= snd_pcm_bytes_to_frames(mPcmHandle
, amt
);
1087 amt
= snd_pcm_readi(mPcmHandle
, buffer
, samples
);
1090 ERR("read error: %s\n", snd_strerror(static_cast<int>(amt
)));
1094 if((amt
=snd_pcm_recover(mPcmHandle
, static_cast<int>(amt
), 1)) >= 0)
1096 amt
= snd_pcm_start(mPcmHandle
);
1098 amt
= snd_pcm_avail_update(mPcmHandle
);
1102 const char *err
{snd_strerror(static_cast<int>(amt
))};
1103 ERR("restore error: %s\n", err
);
1104 aluHandleDisconnect(mDevice
, "Capture recovery failure: %s", err
);
1107 /* If the amount available is less than what's asked, we lost it
1108 * during recovery. So just give silence instead. */
1109 if(static_cast<snd_pcm_uframes_t
>(amt
) < samples
)
1114 buffer
= buffer
+ amt
;
1115 samples
-= static_cast<ALCuint
>(amt
);
1118 std::fill_n(buffer
, snd_pcm_frames_to_bytes(mPcmHandle
, samples
),
1119 al::byte((mDevice
->FmtType
== DevFmtUByte
) ? 0x80 : 0));
1121 return ALC_NO_ERROR
;
1124 ALCuint
AlsaCapture::availableSamples()
1126 snd_pcm_sframes_t avail
{0};
1127 if(mDevice
->Connected
.load(std::memory_order_acquire
) && mDoCapture
)
1128 avail
= snd_pcm_avail_update(mPcmHandle
);
1131 ERR("avail update failed: %s\n", snd_strerror(static_cast<int>(avail
)));
1133 if((avail
=snd_pcm_recover(mPcmHandle
, static_cast<int>(avail
), 1)) >= 0)
1136 avail
= snd_pcm_start(mPcmHandle
);
1138 avail
= snd_pcm_avail_update(mPcmHandle
);
1142 const char *err
{snd_strerror(static_cast<int>(avail
))};
1143 ERR("restore error: %s\n", err
);
1144 aluHandleDisconnect(mDevice
, "Capture recovery failure: %s", err
);
1150 if(avail
< 0) avail
= 0;
1151 avail
+= snd_pcm_bytes_to_frames(mPcmHandle
, static_cast<ssize_t
>(mBuffer
.size()));
1152 if(avail
> mLastAvail
) mLastAvail
= avail
;
1153 return static_cast<ALCuint
>(mLastAvail
);
1158 auto vec
= mRing
->getWriteVector();
1159 if(vec
.first
.len
== 0) break;
1161 snd_pcm_sframes_t amt
{std::min(static_cast<snd_pcm_sframes_t
>(vec
.first
.len
), avail
)};
1162 amt
= snd_pcm_readi(mPcmHandle
, vec
.first
.buf
, static_cast<snd_pcm_uframes_t
>(amt
));
1165 ERR("read error: %s\n", snd_strerror(static_cast<int>(amt
)));
1169 if((amt
=snd_pcm_recover(mPcmHandle
, static_cast<int>(amt
), 1)) >= 0)
1172 amt
= snd_pcm_start(mPcmHandle
);
1174 amt
= snd_pcm_avail_update(mPcmHandle
);
1178 const char *err
{snd_strerror(static_cast<int>(amt
))};
1179 ERR("restore error: %s\n", err
);
1180 aluHandleDisconnect(mDevice
, "Capture recovery failure: %s", err
);
1187 mRing
->writeAdvance(static_cast<snd_pcm_uframes_t
>(amt
));
1191 return static_cast<ALCuint
>(mRing
->readSpace());
1194 ClockLatency
AlsaCapture::getClockLatency()
1199 ret
.ClockTime
= GetDeviceClockTime(mDevice
);
1200 snd_pcm_sframes_t delay
{};
1201 int err
{snd_pcm_delay(mPcmHandle
, &delay
)};
1204 ERR("Failed to get pcm delay: %s\n", snd_strerror(err
));
1207 ret
.Latency
= std::chrono::seconds
{std::max
<snd_pcm_sframes_t
>(0, delay
)};
1208 ret
.Latency
/= mDevice
->Frequency
;
1217 bool AlsaBackendFactory::init()
1224 std::string missing_funcs
;
1226 alsa_handle
= LoadLib("libasound.so.2");
1229 WARN("Failed to load %s\n", "libasound.so.2");
1234 #define LOAD_FUNC(f) do { \
1235 p##f = reinterpret_cast<decltype(p##f)>(GetSymbol(alsa_handle, #f)); \
1236 if(p##f == nullptr) { \
1238 missing_funcs += "\n" #f; \
1241 ALSA_FUNCS(LOAD_FUNC
);
1246 WARN("Missing expected functions:%s\n", missing_funcs
.c_str());
1247 CloseLib(alsa_handle
);
1248 alsa_handle
= nullptr;
1256 bool AlsaBackendFactory::querySupport(BackendType type
)
1257 { return (type
== BackendType::Playback
|| type
== BackendType::Capture
); }
1259 void AlsaBackendFactory::probe(DevProbe type
, 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 DevProbe::Playback
:
1271 PlaybackDevices
= probe_devices(SND_PCM_STREAM_PLAYBACK
);
1272 std::for_each(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), add_device
);
1275 case DevProbe::Capture
:
1276 CaptureDevices
= probe_devices(SND_PCM_STREAM_CAPTURE
);
1277 std::for_each(CaptureDevices
.cbegin(), CaptureDevices
.cend(), add_device
);
1282 BackendPtr
AlsaBackendFactory::createBackend(ALCdevice
*device
, BackendType type
)
1284 if(type
== BackendType::Playback
)
1285 return BackendPtr
{new AlsaPlayback
{device
}};
1286 if(type
== BackendType::Capture
)
1287 return BackendPtr
{new AlsaCapture
{device
}};
1291 BackendFactory
&AlsaBackendFactory::getFactory()
1293 static AlsaBackendFactory factory
{};