3 #include <alsa/asoundlib.h>
10 #include <sys/eventfd.h>
11 #include <sys/inotify.h>
20 #include "alsa_input.h"
21 #include "audio_mixer.h"
23 #include "input_mapping.h"
27 using namespace std::placeholders;
31 should_quit_fd = eventfd(/*initval=*/0, /*flags=*/0);
32 assert(should_quit_fd != -1);
37 for (Device &device : devices) {
38 if (device.input != nullptr) {
39 device.input->stop_capture_thread();
43 const uint64_t one = 1;
44 if (write(should_quit_fd, &one, sizeof(one)) != sizeof(one)) {
45 perror("write(should_quit_fd)");
48 inotify_thread.join();
50 while (retry_threads_running > 0) {
51 this_thread::sleep_for(std::chrono::milliseconds(100));
55 std::vector<ALSAPool::Device> ALSAPool::get_devices()
57 lock_guard<mutex> lock(mu);
58 for (Device &device : devices) {
64 void ALSAPool::hold_device(unsigned index)
66 lock_guard<mutex> lock(mu);
67 assert(index < devices.size());
68 devices[index].held = true;
71 void ALSAPool::release_device(unsigned index)
73 lock_guard<mutex> lock(mu);
74 if (index < devices.size()) {
75 devices[index].held = false;
79 void ALSAPool::enumerate_devices()
81 // Enumerate all cards.
82 for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
84 snprintf(address, sizeof(address), "hw:%d", card_index);
87 int err = snd_ctl_open(&ctl, address, 0);
89 printf("%s: %s\n", address, snd_strerror(err));
92 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
94 // Enumerate all devices on this card.
95 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
96 probe_device_with_retry(card_index, dev_index);
101 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
104 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
106 lock_guard<mutex> lock(add_device_mutex);
107 if (add_device_tries_left.count(address)) {
108 // Some thread is already busy retrying this,
109 // so just reset its count.
110 add_device_tries_left[address] = num_retries;
114 // Try (while still holding the lock) to add the device synchronously.
115 ProbeResult result = probe_device_once(card_index, dev_index);
116 if (result == ProbeResult::SUCCESS) {
118 } else if (result == ProbeResult::FAILURE) {
121 assert(result == ProbeResult::DEFER);
123 // Add failed for whatever reason (probably just that the device
124 // isn't up yet. Set up a count so that nobody else starts a thread,
125 // then start it ourselves.
126 fprintf(stderr, "Trying %s again in one second...\n", address);
127 add_device_tries_left[address] = num_retries;
128 ++retry_threads_running;
129 thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
132 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
135 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
137 for ( ;; ) { // Termination condition within the loop.
140 // See if there are any retries left.
141 lock_guard<mutex> lock(add_device_mutex);
143 !add_device_tries_left.count(address) ||
144 add_device_tries_left[address] == 0) {
145 add_device_tries_left.erase(address);
146 fprintf(stderr, "Giving up probe of %s.\n", address);
150 // Seemingly there were. Give it a try (we still hold the mutex).
151 ProbeResult result = probe_device_once(card_index, dev_index);
152 if (result == ProbeResult::SUCCESS) {
153 add_device_tries_left.erase(address);
154 fprintf(stderr, "Probe of %s succeeded.\n", address);
156 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
157 add_device_tries_left.erase(address);
158 fprintf(stderr, "Giving up probe of %s.\n", address);
163 assert(result == ProbeResult::DEFER);
164 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
165 address, add_device_tries_left[address]);
168 --retry_threads_running;
171 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
174 snprintf(address, sizeof(address), "hw:%d", card_index);
176 int err = snd_ctl_open(&ctl, address, 0);
178 printf("%s: %s\n", address, snd_strerror(err));
179 return ALSAPool::ProbeResult::DEFER;
181 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
183 snd_pcm_info_t *pcm_info;
184 snd_pcm_info_alloca(&pcm_info);
185 snd_pcm_info_set_device(pcm_info, dev_index);
186 snd_pcm_info_set_subdevice(pcm_info, 0);
187 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
188 if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
189 // Not available for capture.
190 printf("%s: Not available for capture.\n", address);
191 return ALSAPool::ProbeResult::DEFER;
194 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
196 unsigned num_channels = 0;
198 // Find all channel maps for this device, and pick out the one
199 // with the most channels.
200 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
201 if (cmaps != nullptr) {
202 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
203 num_channels = max(num_channels, (*ptr)->map.channels);
205 snd_pcm_free_chmaps(cmaps);
207 if (num_channels == 0) {
208 // Device had no channel maps. We need to open it to query.
209 // TODO: Do this asynchronously.
210 snd_pcm_t *pcm_handle;
211 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
213 printf("%s: %s\n", address, snd_strerror(err));
214 return ALSAPool::ProbeResult::DEFER;
216 snd_pcm_hw_params_t *hw_params;
217 snd_pcm_hw_params_alloca(&hw_params);
218 unsigned sample_rate;
219 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
220 snd_pcm_close(pcm_handle);
221 return ALSAPool::ProbeResult::DEFER;
223 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
225 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
226 address, snd_strerror(err));
227 snd_pcm_close(pcm_handle);
228 return ALSAPool::ProbeResult::DEFER;
230 snd_pcm_close(pcm_handle);
233 if (num_channels == 0) {
234 printf("%s: No channel maps with channels\n", address);
235 return ALSAPool::ProbeResult::FAILURE;
238 snd_ctl_card_info_t *card_info;
239 snd_ctl_card_info_alloca(&card_info);
240 snd_ctl_card_info(ctl, card_info);
242 string name = snd_ctl_card_info_get_name(card_info);
243 string info = snd_pcm_info_get_name(pcm_info);
245 unsigned internal_dev_index;
248 lock_guard<mutex> lock(mu);
249 internal_dev_index = find_free_device_index(name, info, num_channels, address);
250 devices[internal_dev_index].address = address;
251 devices[internal_dev_index].name = name;
252 devices[internal_dev_index].info = info;
253 devices[internal_dev_index].num_channels = num_channels;
254 // Note: Purposefully does not overwrite held.
256 display_name = devices[internal_dev_index].display_name();
259 fprintf(stderr, "%s: Probed successfully.\n", address);
261 reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card).
263 DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
264 global_audio_mixer->set_display_name(spec, display_name);
265 global_audio_mixer->trigger_state_changed_callback();
267 return ALSAPool::ProbeResult::SUCCESS;
270 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
273 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
274 for (unsigned i = 0; i < devices.size(); ++i) {
275 if (devices[i].state != Device::State::EMPTY &&
276 devices[i].state != Device::State::DEAD &&
277 devices[i].address == address) {
283 void ALSAPool::init()
285 inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
289 void ALSAPool::inotify_thread_func()
291 int inotify_fd = inotify_init();
292 if (inotify_fd == -1) {
293 perror("inotify_init()");
294 fprintf(stderr, "No hotplug of ALSA devices available.\n");
298 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
299 if (watch_fd == -1) {
300 perror("inotify_add_watch()");
301 fprintf(stderr, "No hotplug of ALSA devices available.\n");
306 int size = sizeof(inotify_event) + NAME_MAX + 1;
307 unique_ptr<char[]> buf(new char[size]);
308 while (!should_quit) {
310 fds[0].fd = inotify_fd;
311 fds[0].events = POLLIN;
313 fds[1].fd = should_quit_fd;
314 fds[1].events = POLLIN;
317 int ret = poll(fds, 2, -1);
319 if (errno == EINTR) {
322 perror("poll(inotify_fd)");
330 if (fds[1].revents) break; // should_quit_fd asserted.
332 ret = read(inotify_fd, buf.get(), size);
334 if (errno == EINTR) {
337 perror("read(inotify_fd)");
343 if (ret < int(sizeof(inotify_event))) {
344 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
351 for (int i = 0; i < ret; ) {
352 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
353 i += sizeof(inotify_event) + event->len;
355 if (event->mask & IN_Q_OVERFLOW) {
356 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
359 unsigned card, device;
361 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
362 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
363 printf("Deleted capture device: Card %u, device %u\n", card, device);
364 unplug_device(card, device);
366 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
367 printf("Adding capture device: Card %u, device %u\n", card, device);
368 probe_device_with_retry(card, device);
375 close(should_quit_fd);
378 void ALSAPool::reset_device(unsigned index)
380 lock_guard<mutex> lock(mu);
381 Device *device = &devices[index];
382 if (inputs[index] != nullptr) {
383 inputs[index]->stop_capture_thread();
386 inputs[index].reset();
388 // TODO: Put on a background thread instead of locking?
389 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
390 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
391 inputs[index]->start_capture_thread();
393 device->input = inputs[index].get();
396 unsigned ALSAPool::get_capture_frequency(unsigned index)
398 lock_guard<mutex> lock(mu);
399 assert(devices[index].held);
400 if (devices[index].input)
401 return devices[index].input->get_sample_rate();
403 return OUTPUT_FREQUENCY;
406 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
408 lock_guard<mutex> lock(mu);
409 assert(devices[index].held);
410 return devices[index].state;
413 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
416 lock_guard<mutex> lock(mu);
417 devices[index].state = state;
420 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
421 bool silence = (state != ALSAPool::Device::State::RUNNING);
422 while (!global_audio_mixer->silence_card(spec, silence))
424 global_audio_mixer->trigger_state_changed_callback();
427 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
429 // First try to find an exact match on a dead card.
430 for (unsigned i = 0; i < devices.size(); ++i) {
431 if (devices[i].state == Device::State::DEAD &&
432 devices[i].address == address &&
433 devices[i].name == name &&
434 devices[i].info == info &&
435 devices[i].num_channels == num_channels) {
436 devices[i].state = Device::State::READY;
441 // Then try to find a match on everything but the address
442 // (probably that devices were plugged back in a different order).
443 // If we have two cards that are equal, this might get them mixed up,
444 // but we don't have anything better.
445 for (unsigned i = 0; i < devices.size(); ++i) {
446 if (devices[i].state == Device::State::DEAD &&
447 devices[i].name == name &&
448 devices[i].info == info &&
449 devices[i].num_channels == num_channels) {
450 devices[i].state = Device::State::READY;
455 // OK, so we didn't find a match; see if there are any empty slots.
456 for (unsigned i = 0; i < devices.size(); ++i) {
457 if (devices[i].state == Device::State::EMPTY) {
458 devices[i].state = Device::State::READY;
459 devices[i].held = false;
464 // Failing that, we just insert the new device at the end.
466 new_dev.state = Device::State::READY;
467 new_dev.held = false;
468 devices.push_back(new_dev);
469 inputs.emplace_back(nullptr);
470 return devices.size() - 1;
473 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
475 lock_guard<mutex> lock(mu);
477 // See if there are any empty slots. If not, insert one at the end.
478 vector<Device>::iterator free_device =
479 find_if(devices.begin(), devices.end(),
480 [](const Device &device) { return device.state == Device::State::EMPTY; });
481 if (free_device == devices.end()) {
482 devices.push_back(Device());
483 inputs.emplace_back(nullptr);
484 free_device = devices.end() - 1;
487 free_device->state = Device::State::DEAD;
488 free_device->name = name;
489 free_device->info = info;
490 free_device->num_channels = num_channels;
491 free_device->held = true;
493 return distance(devices.begin(), free_device);
496 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
498 lock_guard<mutex> lock(mu);
499 assert(index < devices.size());
500 assert(devices[index].held);
501 serialized->set_type(DeviceSpecProto::ALSA_INPUT);
502 serialized->set_index(index);
503 serialized->set_display_name(devices[index].display_name());
504 serialized->set_alsa_name(devices[index].name);
505 serialized->set_alsa_info(devices[index].info);
506 serialized->set_num_channels(devices[index].num_channels);
507 serialized->set_address(devices[index].address);
510 void ALSAPool::free_card(unsigned index)
512 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
513 while (!global_audio_mixer->silence_card(spec, true))
517 lock_guard<mutex> lock(mu);
518 if (devices[index].held) {
519 devices[index].state = Device::State::DEAD;
521 devices[index].state = Device::State::EMPTY;
522 inputs[index].reset();
524 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
530 global_audio_mixer->trigger_state_changed_callback();