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()
58 lock_guard<mutex> lock(mu);
59 for (Device &device : devices) {
65 void ALSAPool::hold_device(unsigned index)
67 lock_guard<mutex> lock(mu);
68 assert(index < devices.size());
69 devices[index].held = true;
72 void ALSAPool::release_device(unsigned index)
74 lock_guard<mutex> lock(mu);
75 if (index < devices.size()) {
76 devices[index].held = false;
80 void ALSAPool::enumerate_devices()
82 // Enumerate all cards.
83 for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
85 snprintf(address, sizeof(address), "hw:%d", card_index);
88 int err = snd_ctl_open(&ctl, address, 0);
90 printf("%s: %s\n", address, snd_strerror(err));
93 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
95 // Enumerate all devices on this card.
96 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
97 probe_device_with_retry(card_index, dev_index);
102 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
105 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
107 lock_guard<mutex> lock(add_device_mutex);
108 if (add_device_tries_left.count(address)) {
109 // Some thread is already busy retrying this,
110 // so just reset its count.
111 add_device_tries_left[address] = num_retries;
115 // Try (while still holding the lock) to add the device synchronously.
116 ProbeResult result = probe_device_once(card_index, dev_index);
117 if (result == ProbeResult::SUCCESS) {
119 } else if (result == ProbeResult::FAILURE) {
122 assert(result == ProbeResult::DEFER);
124 // Add failed for whatever reason (probably just that the device
125 // isn't up yet. Set up a count so that nobody else starts a thread,
126 // then start it ourselves.
127 fprintf(stderr, "Trying %s again in one second...\n", address);
128 add_device_tries_left[address] = num_retries;
129 ++retry_threads_running;
130 thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
133 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
136 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
138 char thread_name[16];
139 snprintf(thread_name, sizeof(thread_name), "Reprobe_hw:%d,%d", card_index, dev_index);
140 pthread_setname_np(pthread_self(), thread_name);
142 for ( ;; ) { // Termination condition within the loop.
145 // See if there are any retries left.
146 lock_guard<mutex> lock(add_device_mutex);
148 !add_device_tries_left.count(address) ||
149 add_device_tries_left[address] == 0) {
150 add_device_tries_left.erase(address);
151 fprintf(stderr, "Giving up probe of %s.\n", address);
155 // Seemingly there were. Give it a try (we still hold the mutex).
156 ProbeResult result = probe_device_once(card_index, dev_index);
157 if (result == ProbeResult::SUCCESS) {
158 add_device_tries_left.erase(address);
159 fprintf(stderr, "Probe of %s succeeded.\n", address);
161 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
162 add_device_tries_left.erase(address);
163 fprintf(stderr, "Giving up probe of %s.\n", address);
168 assert(result == ProbeResult::DEFER);
169 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
170 address, add_device_tries_left[address]);
173 --retry_threads_running;
176 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
179 snprintf(address, sizeof(address), "hw:%d", card_index);
181 int err = snd_ctl_open(&ctl, address, 0);
183 printf("%s: %s\n", address, snd_strerror(err));
184 return ALSAPool::ProbeResult::DEFER;
186 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
188 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
190 snd_pcm_info_t *pcm_info;
191 snd_pcm_info_alloca(&pcm_info);
192 snd_pcm_info_set_device(pcm_info, dev_index);
193 snd_pcm_info_set_subdevice(pcm_info, 0);
194 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
195 err = snd_ctl_pcm_info(ctl, pcm_info);
196 if (err == -ENOENT) {
197 // Not a capture card.
198 return ALSAPool::ProbeResult::FAILURE;
201 // Not available for capture.
202 printf("%s: Not available for capture.\n", address);
203 return ALSAPool::ProbeResult::DEFER;
206 unsigned num_channels = 0;
208 // Find all channel maps for this device, and pick out the one
209 // with the most channels.
210 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
211 if (cmaps != nullptr) {
212 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
213 num_channels = max(num_channels, (*ptr)->map.channels);
215 snd_pcm_free_chmaps(cmaps);
217 if (num_channels == 0) {
218 // Device had no channel maps. We need to open it to query.
219 // TODO: Do this asynchronously.
220 snd_pcm_t *pcm_handle;
221 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
223 printf("%s: %s\n", address, snd_strerror(err));
224 return ALSAPool::ProbeResult::DEFER;
226 snd_pcm_hw_params_t *hw_params;
227 snd_pcm_hw_params_alloca(&hw_params);
228 unsigned sample_rate;
229 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
230 snd_pcm_close(pcm_handle);
231 return ALSAPool::ProbeResult::DEFER;
233 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
235 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
236 address, snd_strerror(err));
237 snd_pcm_close(pcm_handle);
238 return ALSAPool::ProbeResult::DEFER;
240 snd_pcm_close(pcm_handle);
243 if (num_channels == 0) {
244 printf("%s: No channel maps with channels\n", address);
245 return ALSAPool::ProbeResult::FAILURE;
248 snd_ctl_card_info_t *card_info;
249 snd_ctl_card_info_alloca(&card_info);
250 snd_ctl_card_info(ctl, card_info);
252 string name = snd_ctl_card_info_get_name(card_info);
253 string info = snd_pcm_info_get_name(pcm_info);
255 unsigned internal_dev_index;
258 lock_guard<mutex> lock(mu);
259 internal_dev_index = find_free_device_index(name, info, num_channels, address);
260 devices[internal_dev_index].address = address;
261 devices[internal_dev_index].name = name;
262 devices[internal_dev_index].info = info;
263 devices[internal_dev_index].num_channels = num_channels;
264 // Note: Purposefully does not overwrite held.
266 display_name = devices[internal_dev_index].display_name();
269 fprintf(stderr, "%s: Probed successfully.\n", address);
271 reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card).
273 DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
274 global_audio_mixer->set_display_name(spec, display_name);
275 global_audio_mixer->trigger_state_changed_callback();
277 return ALSAPool::ProbeResult::SUCCESS;
280 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
283 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
284 for (unsigned i = 0; i < devices.size(); ++i) {
285 if (devices[i].state != Device::State::EMPTY &&
286 devices[i].state != Device::State::DEAD &&
287 devices[i].address == address) {
293 void ALSAPool::init()
295 inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
299 void ALSAPool::inotify_thread_func()
301 pthread_setname_np(pthread_self(), "ALSA_Hotplug");
303 int inotify_fd = inotify_init();
304 if (inotify_fd == -1) {
305 perror("inotify_init()");
306 fprintf(stderr, "No hotplug of ALSA devices available.\n");
310 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
311 if (watch_fd == -1) {
312 perror("inotify_add_watch()");
313 fprintf(stderr, "No hotplug of ALSA devices available.\n");
318 int size = sizeof(inotify_event) + NAME_MAX + 1;
319 unique_ptr<char[]> buf(new char[size]);
320 while (!should_quit) {
322 fds[0].fd = inotify_fd;
323 fds[0].events = POLLIN;
325 fds[1].fd = should_quit_fd;
326 fds[1].events = POLLIN;
329 int ret = poll(fds, 2, -1);
331 if (errno == EINTR) {
334 perror("poll(inotify_fd)");
342 if (fds[1].revents) break; // should_quit_fd asserted.
344 ret = read(inotify_fd, buf.get(), size);
346 if (errno == EINTR) {
349 perror("read(inotify_fd)");
355 if (ret < int(sizeof(inotify_event))) {
356 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
363 for (int i = 0; i < ret; ) {
364 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
365 i += sizeof(inotify_event) + event->len;
367 if (event->mask & IN_Q_OVERFLOW) {
368 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
371 unsigned card, device;
373 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
374 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
375 printf("Deleted capture device: Card %u, device %u\n", card, device);
376 unplug_device(card, device);
378 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
379 printf("Adding capture device: Card %u, device %u\n", card, device);
380 probe_device_with_retry(card, device);
387 close(should_quit_fd);
390 void ALSAPool::reset_device(unsigned index)
392 lock_guard<mutex> lock(mu);
393 Device *device = &devices[index];
394 if (device->state == Device::State::DEAD) {
395 // Not running, and should not be started.
398 if (inputs[index] != nullptr) {
399 inputs[index]->stop_capture_thread();
402 inputs[index].reset();
404 // TODO: Put on a background thread instead of locking?
405 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4, _5);
406 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
407 inputs[index]->start_capture_thread();
409 device->input = inputs[index].get();
412 unsigned ALSAPool::get_capture_frequency(unsigned index)
414 lock_guard<mutex> lock(mu);
415 assert(devices[index].held);
416 if (devices[index].input)
417 return devices[index].input->get_sample_rate();
419 return OUTPUT_FREQUENCY;
422 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
424 lock_guard<mutex> lock(mu);
425 assert(devices[index].held);
426 return devices[index].state;
429 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
432 lock_guard<mutex> lock(mu);
433 devices[index].state = state;
436 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
437 bool silence = (state != ALSAPool::Device::State::RUNNING);
438 while (!global_audio_mixer->silence_card(spec, silence))
440 global_audio_mixer->trigger_state_changed_callback();
443 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
445 // First try to find an exact match on a dead card.
446 for (unsigned i = 0; i < devices.size(); ++i) {
447 if (devices[i].state == Device::State::DEAD &&
448 devices[i].address == address &&
449 devices[i].name == name &&
450 devices[i].info == info &&
451 devices[i].num_channels == num_channels) {
452 devices[i].state = Device::State::READY;
457 // Then try to find a match on everything but the address
458 // (probably that devices were plugged back in a different order).
459 // If we have two cards that are equal, this might get them mixed up,
460 // but we don't have anything better.
461 for (unsigned i = 0; i < devices.size(); ++i) {
462 if (devices[i].state == Device::State::DEAD &&
463 devices[i].name == name &&
464 devices[i].info == info &&
465 devices[i].num_channels == num_channels) {
466 devices[i].state = Device::State::READY;
471 // OK, so we didn't find a match; see if there are any empty slots.
472 for (unsigned i = 0; i < devices.size(); ++i) {
473 if (devices[i].state == Device::State::EMPTY) {
474 devices[i].state = Device::State::READY;
475 devices[i].held = false;
480 // Failing that, we just insert the new device at the end.
482 new_dev.state = Device::State::READY;
483 new_dev.held = false;
484 devices.push_back(new_dev);
485 inputs.emplace_back(nullptr);
486 return devices.size() - 1;
489 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
491 lock_guard<mutex> lock(mu);
493 // See if there are any empty slots. If not, insert one at the end.
494 vector<Device>::iterator free_device =
495 find_if(devices.begin(), devices.end(),
496 [](const Device &device) { return device.state == Device::State::EMPTY; });
497 if (free_device == devices.end()) {
498 devices.push_back(Device());
499 inputs.emplace_back(nullptr);
500 free_device = devices.end() - 1;
503 free_device->state = Device::State::DEAD;
504 free_device->name = name;
505 free_device->info = info;
506 free_device->num_channels = num_channels;
507 free_device->held = true;
509 return distance(devices.begin(), free_device);
512 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
514 lock_guard<mutex> lock(mu);
515 assert(index < devices.size());
516 assert(devices[index].held);
517 serialized->set_type(DeviceSpecProto::ALSA_INPUT);
518 serialized->set_index(index);
519 serialized->set_display_name(devices[index].display_name());
520 serialized->set_alsa_name(devices[index].name);
521 serialized->set_alsa_info(devices[index].info);
522 serialized->set_num_channels(devices[index].num_channels);
523 serialized->set_address(devices[index].address);
526 void ALSAPool::free_card(unsigned index)
528 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
529 while (!global_audio_mixer->silence_card(spec, true))
533 lock_guard<mutex> lock(mu);
534 if (devices[index].held) {
535 devices[index].state = Device::State::DEAD;
537 devices[index].state = Device::State::EMPTY;
538 inputs[index].reset();
540 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
546 global_audio_mixer->trigger_state_changed_callback();