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 write(should_quit_fd, &one, sizeof(one));
45 inotify_thread.join();
47 while (retry_threads_running > 0) {
48 this_thread::sleep_for(std::chrono::milliseconds(100));
52 std::vector<ALSAPool::Device> ALSAPool::get_devices()
54 lock_guard<mutex> lock(mu);
55 for (Device &device : devices) {
61 void ALSAPool::hold_device(unsigned index)
63 lock_guard<mutex> lock(mu);
64 assert(index < devices.size());
65 devices[index].held = true;
68 void ALSAPool::release_device(unsigned index)
70 lock_guard<mutex> lock(mu);
71 if (index < devices.size()) {
72 devices[index].held = false;
76 void ALSAPool::enumerate_devices()
78 // Enumerate all cards.
79 for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
81 snprintf(address, sizeof(address), "hw:%d", card_index);
84 int err = snd_ctl_open(&ctl, address, 0);
86 printf("%s: %s\n", address, snd_strerror(err));
89 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
91 // Enumerate all devices on this card.
92 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
93 probe_device_with_retry(card_index, dev_index);
98 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
101 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
103 lock_guard<mutex> lock(add_device_mutex);
104 if (add_device_tries_left.count(address)) {
105 // Some thread is already busy retrying this,
106 // so just reset its count.
107 add_device_tries_left[address] = num_retries;
111 // Try (while still holding the lock) to add the device synchronously.
112 ProbeResult result = probe_device_once(card_index, dev_index);
113 if (result == ProbeResult::SUCCESS) {
115 } else if (result == ProbeResult::FAILURE) {
118 assert(result == ProbeResult::DEFER);
120 // Add failed for whatever reason (probably just that the device
121 // isn't up yet. Set up a count so that nobody else starts a thread,
122 // then start it ourselves.
123 fprintf(stderr, "Trying %s again in one second...\n", address);
124 add_device_tries_left[address] = num_retries;
125 ++retry_threads_running;
126 thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
129 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
132 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
134 for ( ;; ) { // Termination condition within the loop.
137 // See if there are any retries left.
138 lock_guard<mutex> lock(add_device_mutex);
140 !add_device_tries_left.count(address) ||
141 add_device_tries_left[address] == 0) {
142 add_device_tries_left.erase(address);
143 fprintf(stderr, "Giving up probe of %s.\n", address);
147 // Seemingly there were. Give it a try (we still hold the mutex).
148 ProbeResult result = probe_device_once(card_index, dev_index);
149 if (result == ProbeResult::SUCCESS) {
150 add_device_tries_left.erase(address);
151 fprintf(stderr, "Probe of %s succeeded.\n", address);
153 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
154 add_device_tries_left.erase(address);
155 fprintf(stderr, "Giving up probe of %s.\n", address);
160 assert(result == ProbeResult::DEFER);
161 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
162 address, add_device_tries_left[address]);
165 --retry_threads_running;
168 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
171 snprintf(address, sizeof(address), "hw:%d", card_index);
173 int err = snd_ctl_open(&ctl, address, 0);
175 printf("%s: %s\n", address, snd_strerror(err));
176 return ALSAPool::ProbeResult::DEFER;
178 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
180 snd_pcm_info_t *pcm_info;
181 snd_pcm_info_alloca(&pcm_info);
182 snd_pcm_info_set_device(pcm_info, dev_index);
183 snd_pcm_info_set_subdevice(pcm_info, 0);
184 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
185 if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
186 // Not available for capture.
187 printf("%s: Not available for capture.\n", address);
188 return ALSAPool::ProbeResult::DEFER;
191 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
193 unsigned num_channels = 0;
195 // Find all channel maps for this device, and pick out the one
196 // with the most channels.
197 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
198 if (cmaps != nullptr) {
199 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
200 num_channels = max(num_channels, (*ptr)->map.channels);
202 snd_pcm_free_chmaps(cmaps);
204 if (num_channels == 0) {
205 // Device had no channel maps. We need to open it to query.
206 // TODO: Do this asynchronously.
207 snd_pcm_t *pcm_handle;
208 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
210 printf("%s: %s\n", address, snd_strerror(err));
211 return ALSAPool::ProbeResult::DEFER;
213 snd_pcm_hw_params_t *hw_params;
214 snd_pcm_hw_params_alloca(&hw_params);
215 unsigned sample_rate;
216 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
217 snd_pcm_close(pcm_handle);
218 return ALSAPool::ProbeResult::DEFER;
220 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
222 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
223 address, snd_strerror(err));
224 snd_pcm_close(pcm_handle);
225 return ALSAPool::ProbeResult::DEFER;
227 snd_pcm_close(pcm_handle);
230 if (num_channels == 0) {
231 printf("%s: No channel maps with channels\n", address);
232 return ALSAPool::ProbeResult::FAILURE;
235 snd_ctl_card_info_t *card_info;
236 snd_ctl_card_info_alloca(&card_info);
237 snd_ctl_card_info(ctl, card_info);
239 string name = snd_ctl_card_info_get_name(card_info);
240 string info = snd_pcm_info_get_name(pcm_info);
242 unsigned internal_dev_index;
245 lock_guard<mutex> lock(mu);
246 internal_dev_index = find_free_device_index(name, info, num_channels, address);
247 devices[internal_dev_index].address = address;
248 devices[internal_dev_index].name = name;
249 devices[internal_dev_index].info = info;
250 devices[internal_dev_index].num_channels = num_channels;
251 // Note: Purposefully does not overwrite held.
253 display_name = devices[internal_dev_index].display_name();
256 fprintf(stderr, "%s: Probed successfully.\n", address);
258 reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card).
260 DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
261 global_audio_mixer->set_display_name(spec, display_name);
262 global_audio_mixer->trigger_state_changed_callback();
264 return ALSAPool::ProbeResult::SUCCESS;
267 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
270 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
271 for (unsigned i = 0; i < devices.size(); ++i) {
272 if (devices[i].state != Device::State::EMPTY &&
273 devices[i].state != Device::State::DEAD &&
274 devices[i].address == address) {
280 void ALSAPool::init()
282 inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
286 void ALSAPool::inotify_thread_func()
288 int inotify_fd = inotify_init();
289 if (inotify_fd == -1) {
290 perror("inotify_init()");
291 fprintf(stderr, "No hotplug of ALSA devices available.\n");
295 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
296 if (watch_fd == -1) {
297 perror("inotify_add_watch()");
298 fprintf(stderr, "No hotplug of ALSA devices available.\n");
303 int size = sizeof(inotify_event) + NAME_MAX + 1;
304 unique_ptr<char[]> buf(new char[size]);
305 while (!should_quit) {
307 fds[0].fd = inotify_fd;
308 fds[0].events = POLLIN;
310 fds[1].fd = should_quit_fd;
311 fds[1].events = POLLIN;
314 int ret = poll(fds, 2, -1);
316 if (errno == EINTR) {
319 perror("poll(inotify_fd)");
327 if (fds[1].revents) break; // should_quit_fd asserted.
329 ret = read(inotify_fd, buf.get(), size);
331 if (errno == EINTR) {
334 perror("read(inotify_fd)");
340 if (ret < int(sizeof(inotify_event))) {
341 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
348 for (int i = 0; i < ret; ) {
349 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
350 i += sizeof(inotify_event) + event->len;
352 if (event->mask & IN_Q_OVERFLOW) {
353 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
356 unsigned card, device;
358 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
359 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
360 printf("Deleted capture device: Card %u, device %u\n", card, device);
361 unplug_device(card, device);
363 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
364 printf("Adding capture device: Card %u, device %u\n", card, device);
365 probe_device_with_retry(card, device);
372 close(should_quit_fd);
375 void ALSAPool::reset_device(unsigned index)
377 lock_guard<mutex> lock(mu);
378 Device *device = &devices[index];
379 if (inputs[index] != nullptr) {
380 inputs[index]->stop_capture_thread();
383 inputs[index].reset();
385 // TODO: Put on a background thread instead of locking?
386 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
387 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
388 inputs[index]->start_capture_thread();
390 device->input = inputs[index].get();
393 unsigned ALSAPool::get_capture_frequency(unsigned index)
395 lock_guard<mutex> lock(mu);
396 assert(devices[index].held);
397 if (devices[index].input)
398 return devices[index].input->get_sample_rate();
400 return OUTPUT_FREQUENCY;
403 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
405 lock_guard<mutex> lock(mu);
406 assert(devices[index].held);
407 return devices[index].state;
410 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
413 lock_guard<mutex> lock(mu);
414 devices[index].state = state;
417 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
418 bool silence = (state != ALSAPool::Device::State::RUNNING);
419 while (!global_audio_mixer->silence_card(spec, silence))
421 global_audio_mixer->trigger_state_changed_callback();
424 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
426 // First try to find an exact match on a dead card.
427 for (unsigned i = 0; i < devices.size(); ++i) {
428 if (devices[i].state == Device::State::DEAD &&
429 devices[i].address == address &&
430 devices[i].name == name &&
431 devices[i].info == info &&
432 devices[i].num_channels == num_channels) {
433 devices[i].state = Device::State::READY;
438 // Then try to find a match on everything but the address
439 // (probably that devices were plugged back in a different order).
440 // If we have two cards that are equal, this might get them mixed up,
441 // but we don't have anything better.
442 for (unsigned i = 0; i < devices.size(); ++i) {
443 if (devices[i].state == Device::State::DEAD &&
444 devices[i].name == name &&
445 devices[i].info == info &&
446 devices[i].num_channels == num_channels) {
447 devices[i].state = Device::State::READY;
452 // OK, so we didn't find a match; see if there are any empty slots.
453 for (unsigned i = 0; i < devices.size(); ++i) {
454 if (devices[i].state == Device::State::EMPTY) {
455 devices[i].state = Device::State::READY;
456 devices[i].held = false;
461 // Failing that, we just insert the new device at the end.
463 new_dev.state = Device::State::READY;
464 new_dev.held = false;
465 devices.push_back(new_dev);
466 inputs.emplace_back(nullptr);
467 return devices.size() - 1;
470 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
472 lock_guard<mutex> lock(mu);
474 // See if there are any empty slots. If not, insert one at the end.
475 vector<Device>::iterator free_device =
476 find_if(devices.begin(), devices.end(),
477 [](const Device &device) { return device.state == Device::State::EMPTY; });
478 if (free_device == devices.end()) {
479 devices.push_back(Device());
480 inputs.emplace_back(nullptr);
481 free_device = devices.end() - 1;
484 free_device->state = Device::State::DEAD;
485 free_device->name = name;
486 free_device->info = info;
487 free_device->num_channels = num_channels;
488 free_device->held = true;
490 return distance(devices.begin(), free_device);
493 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
495 lock_guard<mutex> lock(mu);
496 assert(index < devices.size());
497 assert(devices[index].held);
498 serialized->set_type(DeviceSpecProto::ALSA_INPUT);
499 serialized->set_index(index);
500 serialized->set_display_name(devices[index].display_name());
501 serialized->set_alsa_name(devices[index].name);
502 serialized->set_alsa_info(devices[index].info);
503 serialized->set_num_channels(devices[index].num_channels);
504 serialized->set_address(devices[index].address);
507 void ALSAPool::free_card(unsigned index)
509 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
510 while (!global_audio_mixer->silence_card(spec, true))
514 lock_guard<mutex> lock(mu);
515 if (devices[index].held) {
516 devices[index].state = Device::State::DEAD;
518 devices[index].state = Device::State::EMPTY;
519 inputs[index].reset();
521 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
527 global_audio_mixer->trigger_state_changed_callback();