3 #include <alsa/asoundlib.h>
11 #include <sys/eventfd.h>
12 #include <sys/inotify.h>
21 #include "alsa_input.h"
22 #include "audio_mixer.h"
24 #include "input_mapping.h"
28 using namespace std::placeholders;
32 should_quit_fd = eventfd(/*initval=*/0, /*flags=*/0);
33 assert(should_quit_fd != -1);
38 for (Device &device : devices) {
39 if (device.input != nullptr) {
40 device.input->stop_capture_thread();
44 const uint64_t one = 1;
45 if (write(should_quit_fd, &one, sizeof(one)) != sizeof(one)) {
46 perror("write(should_quit_fd)");
49 inotify_thread.join();
51 while (retry_threads_running > 0) {
52 this_thread::sleep_for(std::chrono::milliseconds(100));
56 std::vector<ALSAPool::Device> ALSAPool::get_devices(bool hold_devices)
58 lock_guard<mutex> lock(mu);
60 for (Device &device : devices) {
67 void ALSAPool::hold_device(unsigned index)
69 lock_guard<mutex> lock(mu);
70 assert(index < devices.size());
71 devices[index].held = true;
74 void ALSAPool::release_device(unsigned index)
76 lock_guard<mutex> lock(mu);
77 if (index < devices.size()) {
78 devices[index].held = false;
82 bool ALSAPool::device_is_held(unsigned index)
84 lock_guard<mutex> lock(mu);
85 if (index < devices.size()) {
86 return devices[index].held;
92 void ALSAPool::enumerate_devices()
94 // Enumerate all cards.
95 for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
97 snprintf(address, sizeof(address), "hw:%d", card_index);
100 int err = snd_ctl_open(&ctl, address, 0);
102 printf("%s: %s\n", address, snd_strerror(err));
105 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
107 // Enumerate all devices on this card.
108 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
109 probe_device_with_retry(card_index, dev_index);
114 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
117 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
119 lock_guard<mutex> lock(add_device_mutex);
120 if (add_device_tries_left.count(address)) {
121 // Some thread is already busy retrying this,
122 // so just reset its count.
123 add_device_tries_left[address] = num_retries;
127 // Try (while still holding the lock) to add the device synchronously.
128 ProbeResult result = probe_device_once(card_index, dev_index);
129 if (result == ProbeResult::SUCCESS) {
131 } else if (result == ProbeResult::FAILURE) {
134 assert(result == ProbeResult::DEFER);
136 // Add failed for whatever reason (probably just that the device
137 // isn't up yet. Set up a count so that nobody else starts a thread,
138 // then start it ourselves.
139 fprintf(stderr, "Trying %s again in one second...\n", address);
140 add_device_tries_left[address] = num_retries;
141 ++retry_threads_running;
142 thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
145 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
148 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
150 char thread_name[16];
151 snprintf(thread_name, sizeof(thread_name), "Reprobe_hw:%d,%d", card_index, dev_index);
152 pthread_setname_np(pthread_self(), thread_name);
154 for ( ;; ) { // Termination condition within the loop.
157 // See if there are any retries left.
158 lock_guard<mutex> lock(add_device_mutex);
160 !add_device_tries_left.count(address) ||
161 add_device_tries_left[address] == 0) {
162 add_device_tries_left.erase(address);
163 fprintf(stderr, "Giving up probe of %s.\n", address);
167 // Seemingly there were. Give it a try (we still hold the mutex).
168 ProbeResult result = probe_device_once(card_index, dev_index);
169 if (result == ProbeResult::SUCCESS) {
170 add_device_tries_left.erase(address);
171 fprintf(stderr, "Probe of %s succeeded.\n", address);
173 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
174 add_device_tries_left.erase(address);
175 fprintf(stderr, "Giving up probe of %s.\n", address);
180 assert(result == ProbeResult::DEFER);
181 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
182 address, add_device_tries_left[address]);
185 --retry_threads_running;
188 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
191 snprintf(address, sizeof(address), "hw:%d", card_index);
193 int err = snd_ctl_open(&ctl, address, 0);
195 printf("%s: %s\n", address, snd_strerror(err));
196 return ALSAPool::ProbeResult::DEFER;
198 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
200 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
202 snd_pcm_info_t *pcm_info;
203 snd_pcm_info_alloca(&pcm_info);
204 snd_pcm_info_set_device(pcm_info, dev_index);
205 snd_pcm_info_set_subdevice(pcm_info, 0);
206 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
207 err = snd_ctl_pcm_info(ctl, pcm_info);
208 if (err == -ENOENT) {
209 // Not a capture card.
210 return ALSAPool::ProbeResult::FAILURE;
213 // Not available for capture.
214 printf("%s: Not available for capture.\n", address);
215 return ALSAPool::ProbeResult::DEFER;
218 unsigned num_channels = 0;
220 // Find all channel maps for this device, and pick out the one
221 // with the most channels.
222 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
223 if (cmaps != nullptr) {
224 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
225 num_channels = max(num_channels, (*ptr)->map.channels);
227 snd_pcm_free_chmaps(cmaps);
229 if (num_channels == 0) {
230 // Device had no channel maps. We need to open it to query.
231 // TODO: Do this asynchronously.
232 snd_pcm_t *pcm_handle;
233 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
235 printf("%s: %s\n", address, snd_strerror(err));
236 return ALSAPool::ProbeResult::DEFER;
238 snd_pcm_hw_params_t *hw_params;
239 snd_pcm_hw_params_alloca(&hw_params);
240 unsigned sample_rate;
241 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
242 snd_pcm_close(pcm_handle);
243 return ALSAPool::ProbeResult::DEFER;
245 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
247 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
248 address, snd_strerror(err));
249 snd_pcm_close(pcm_handle);
250 return ALSAPool::ProbeResult::DEFER;
252 snd_pcm_close(pcm_handle);
255 if (num_channels == 0) {
256 printf("%s: No channel maps with channels\n", address);
257 return ALSAPool::ProbeResult::FAILURE;
260 snd_ctl_card_info_t *card_info;
261 snd_ctl_card_info_alloca(&card_info);
262 snd_ctl_card_info(ctl, card_info);
264 string name = snd_ctl_card_info_get_name(card_info);
265 string info = snd_pcm_info_get_name(pcm_info);
267 unsigned internal_dev_index;
270 lock_guard<mutex> lock(mu);
271 internal_dev_index = find_free_device_index(name, info, num_channels, address);
272 devices[internal_dev_index].address = address;
273 devices[internal_dev_index].name = name;
274 devices[internal_dev_index].info = info;
275 devices[internal_dev_index].num_channels = num_channels;
276 // Note: Purposefully does not overwrite held.
278 display_name = devices[internal_dev_index].display_name();
281 fprintf(stderr, "%s: Probed successfully.\n", address);
283 reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card).
285 DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
286 global_audio_mixer->set_display_name(spec, display_name);
287 global_audio_mixer->trigger_state_changed_callback();
289 return ALSAPool::ProbeResult::SUCCESS;
292 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
295 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
296 for (unsigned i = 0; i < devices.size(); ++i) {
297 if (devices[i].state != Device::State::EMPTY &&
298 devices[i].state != Device::State::DEAD &&
299 devices[i].address == address) {
305 void ALSAPool::init()
307 inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
311 void ALSAPool::inotify_thread_func()
313 pthread_setname_np(pthread_self(), "ALSA_Hotplug");
315 int inotify_fd = inotify_init();
316 if (inotify_fd == -1) {
317 perror("inotify_init()");
318 fprintf(stderr, "No hotplug of ALSA devices available.\n");
322 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
323 if (watch_fd == -1) {
324 perror("inotify_add_watch()");
325 fprintf(stderr, "No hotplug of ALSA devices available.\n");
330 int size = sizeof(inotify_event) + NAME_MAX + 1;
331 unique_ptr<char[]> buf(new char[size]);
332 while (!should_quit) {
334 fds[0].fd = inotify_fd;
335 fds[0].events = POLLIN;
337 fds[1].fd = should_quit_fd;
338 fds[1].events = POLLIN;
341 int ret = poll(fds, 2, -1);
343 if (errno == EINTR) {
346 perror("poll(inotify_fd)");
354 if (fds[1].revents) break; // should_quit_fd asserted.
356 ret = read(inotify_fd, buf.get(), size);
358 if (errno == EINTR) {
361 perror("read(inotify_fd)");
367 if (ret < int(sizeof(inotify_event))) {
368 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
375 for (int i = 0; i < ret; ) {
376 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
377 i += sizeof(inotify_event) + event->len;
379 if (event->mask & IN_Q_OVERFLOW) {
380 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
383 unsigned card, device;
385 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
386 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
387 printf("Deleted capture device: Card %u, device %u\n", card, device);
388 unplug_device(card, device);
390 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
391 printf("Adding capture device: Card %u, device %u\n", card, device);
392 probe_device_with_retry(card, device);
399 close(should_quit_fd);
402 void ALSAPool::reset_device(unsigned index)
404 lock_guard<mutex> lock(mu);
405 Device *device = &devices[index];
406 if (device->state == Device::State::DEAD) {
407 // Not running, and should not be started.
410 if (inputs[index] != nullptr) {
411 inputs[index]->stop_capture_thread();
414 inputs[index].reset();
416 // TODO: Put on a background thread instead of locking?
417 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
418 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
419 inputs[index]->start_capture_thread();
421 device->input = inputs[index].get();
424 unsigned ALSAPool::get_capture_frequency(unsigned index)
426 lock_guard<mutex> lock(mu);
427 assert(devices[index].held);
428 if (devices[index].input)
429 return devices[index].input->get_sample_rate();
431 return OUTPUT_FREQUENCY;
434 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
436 lock_guard<mutex> lock(mu);
437 assert(devices[index].held);
438 return devices[index].state;
441 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
444 lock_guard<mutex> lock(mu);
445 devices[index].state = state;
448 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
449 bool silence = (state != ALSAPool::Device::State::RUNNING);
450 while (!global_audio_mixer->silence_card(spec, silence))
452 global_audio_mixer->trigger_state_changed_callback();
455 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
457 // First try to find an exact match on a dead card.
458 for (unsigned i = 0; i < devices.size(); ++i) {
459 if (devices[i].state == Device::State::DEAD &&
460 devices[i].address == address &&
461 devices[i].name == name &&
462 devices[i].info == info &&
463 devices[i].num_channels == num_channels) {
464 devices[i].state = Device::State::READY;
469 // Then try to find a match on everything but the address
470 // (probably that devices were plugged back in a different order).
471 // If we have two cards that are equal, this might get them mixed up,
472 // but we don't have anything better.
473 for (unsigned i = 0; i < devices.size(); ++i) {
474 if (devices[i].state == Device::State::DEAD &&
475 devices[i].name == name &&
476 devices[i].info == info &&
477 devices[i].num_channels == num_channels) {
478 devices[i].state = Device::State::READY;
483 // OK, so we didn't find a match; see if there are any empty slots.
484 for (unsigned i = 0; i < devices.size(); ++i) {
485 if (devices[i].state == Device::State::EMPTY) {
486 devices[i].state = Device::State::READY;
487 devices[i].held = false;
492 // Failing that, we just insert the new device at the end.
494 new_dev.state = Device::State::READY;
495 new_dev.held = false;
496 devices.push_back(new_dev);
497 inputs.emplace_back(nullptr);
498 return devices.size() - 1;
501 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
503 lock_guard<mutex> lock(mu);
505 // See if there are any empty slots. If not, insert one at the end.
506 vector<Device>::iterator free_device =
507 find_if(devices.begin(), devices.end(),
508 [](const Device &device) { return device.state == Device::State::EMPTY; });
509 if (free_device == devices.end()) {
510 devices.push_back(Device());
511 inputs.emplace_back(nullptr);
512 free_device = devices.end() - 1;
515 free_device->state = Device::State::DEAD;
516 free_device->name = name;
517 free_device->info = info;
518 free_device->num_channels = num_channels;
519 free_device->held = true;
521 return distance(devices.begin(), free_device);
524 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
526 lock_guard<mutex> lock(mu);
527 assert(index < devices.size());
528 assert(devices[index].held);
529 serialized->set_type(DeviceSpecProto::ALSA_INPUT);
530 serialized->set_index(index);
531 serialized->set_display_name(devices[index].display_name());
532 serialized->set_alsa_name(devices[index].name);
533 serialized->set_alsa_info(devices[index].info);
534 serialized->set_num_channels(devices[index].num_channels);
535 serialized->set_address(devices[index].address);
538 void ALSAPool::free_card(unsigned index)
540 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
541 while (!global_audio_mixer->silence_card(spec, true))
545 lock_guard<mutex> lock(mu);
546 if (devices[index].held) {
547 devices[index].state = Device::State::DEAD;
549 devices[index].state = Device::State::EMPTY;
550 inputs[index].reset();
552 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
558 global_audio_mixer->trigger_state_changed_callback();