3 #include <alsa/control.h>
4 #include <alsa/error.h>
9 #include <sys/eventfd.h>
10 #include <sys/inotify.h>
15 #include "alsa_input.h"
16 #include "audio_mixer.h"
18 #include "input_mapping.h"
22 using namespace std::placeholders;
26 should_quit_fd = eventfd(/*initval=*/0, /*flags=*/0);
27 assert(should_quit_fd != -1);
32 for (Device &device : devices) {
33 if (device.input != nullptr) {
34 device.input->stop_capture_thread();
38 const uint64_t one = 1;
39 write(should_quit_fd, &one, sizeof(one));
40 inotify_thread.join();
42 while (retry_threads_running > 0) {
43 this_thread::sleep_for(std::chrono::milliseconds(100));
47 std::vector<ALSAPool::Device> ALSAPool::get_devices()
49 lock_guard<mutex> lock(mu);
50 for (Device &device : devices) {
56 void ALSAPool::hold_device(unsigned index)
58 lock_guard<mutex> lock(mu);
59 assert(index < devices.size());
60 devices[index].held = true;
63 void ALSAPool::release_device(unsigned index)
65 lock_guard<mutex> lock(mu);
66 if (index < devices.size()) {
67 devices[index].held = false;
71 void ALSAPool::enumerate_devices()
73 // Enumerate all cards.
74 for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
76 snprintf(address, sizeof(address), "hw:%d", card_index);
79 int err = snd_ctl_open(&ctl, address, 0);
81 printf("%s: %s\n", address, snd_strerror(err));
84 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
86 // Enumerate all devices on this card.
87 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
88 probe_device_with_retry(card_index, dev_index);
93 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
96 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
98 lock_guard<mutex> lock(add_device_mutex);
99 if (add_device_tries_left.count(address)) {
100 // Some thread is already busy retrying this,
101 // so just reset its count.
102 add_device_tries_left[address] = num_retries;
106 // Try (while still holding the lock) to add the device synchronously.
107 ProbeResult result = probe_device_once(card_index, dev_index);
108 if (result == ProbeResult::SUCCESS) {
110 } else if (result == ProbeResult::FAILURE) {
113 assert(result == ProbeResult::DEFER);
115 // Add failed for whatever reason (probably just that the device
116 // isn't up yet. Set up a count so that nobody else starts a thread,
117 // then start it ourselves.
118 fprintf(stderr, "Trying %s again in one second...\n", address);
119 add_device_tries_left[address] = num_retries;
120 ++retry_threads_running;
121 thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
124 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
127 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
129 for ( ;; ) { // Termination condition within the loop.
132 // See if there are any retries left.
133 lock_guard<mutex> lock(add_device_mutex);
135 !add_device_tries_left.count(address) ||
136 add_device_tries_left[address] == 0) {
137 add_device_tries_left.erase(address);
138 fprintf(stderr, "Giving up probe of %s.\n", address);
142 // Seemingly there were. Give it a try (we still hold the mutex).
143 ProbeResult result = probe_device_once(card_index, dev_index);
144 if (result == ProbeResult::SUCCESS) {
145 add_device_tries_left.erase(address);
146 fprintf(stderr, "Probe of %s succeeded.\n", address);
148 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
149 add_device_tries_left.erase(address);
150 fprintf(stderr, "Giving up probe of %s.\n", address);
155 assert(result == ProbeResult::DEFER);
156 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
157 address, add_device_tries_left[address]);
160 --retry_threads_running;
163 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
166 snprintf(address, sizeof(address), "hw:%d", card_index);
168 int err = snd_ctl_open(&ctl, address, 0);
170 printf("%s: %s\n", address, snd_strerror(err));
171 return ALSAPool::ProbeResult::DEFER;
173 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
175 snd_pcm_info_t *pcm_info;
176 snd_pcm_info_alloca(&pcm_info);
177 snd_pcm_info_set_device(pcm_info, dev_index);
178 snd_pcm_info_set_subdevice(pcm_info, 0);
179 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
180 if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
181 // Not available for capture.
182 printf("%s: Not available for capture.\n", address);
183 return ALSAPool::ProbeResult::DEFER;
186 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
188 unsigned num_channels = 0;
190 // Find all channel maps for this device, and pick out the one
191 // with the most channels.
192 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
193 if (cmaps != nullptr) {
194 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
195 num_channels = max(num_channels, (*ptr)->map.channels);
197 snd_pcm_free_chmaps(cmaps);
199 if (num_channels == 0) {
200 // Device had no channel maps. We need to open it to query.
201 // TODO: Do this asynchronously.
202 snd_pcm_t *pcm_handle;
203 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
205 printf("%s: %s\n", address, snd_strerror(err));
206 return ALSAPool::ProbeResult::DEFER;
208 snd_pcm_hw_params_t *hw_params;
209 snd_pcm_hw_params_alloca(&hw_params);
210 unsigned sample_rate;
211 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
212 snd_pcm_close(pcm_handle);
213 return ALSAPool::ProbeResult::DEFER;
215 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
217 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
218 address, snd_strerror(err));
219 snd_pcm_close(pcm_handle);
220 return ALSAPool::ProbeResult::DEFER;
222 snd_pcm_close(pcm_handle);
225 if (num_channels == 0) {
226 printf("%s: No channel maps with channels\n", address);
227 return ALSAPool::ProbeResult::FAILURE;
230 snd_ctl_card_info_t *card_info;
231 snd_ctl_card_info_alloca(&card_info);
232 snd_ctl_card_info(ctl, card_info);
234 string name = snd_ctl_card_info_get_name(card_info);
235 string info = snd_pcm_info_get_name(pcm_info);
237 unsigned internal_dev_index;
240 lock_guard<mutex> lock(mu);
241 internal_dev_index = find_free_device_index(name, info, num_channels, address);
242 devices[internal_dev_index].address = address;
243 devices[internal_dev_index].name = name;
244 devices[internal_dev_index].info = info;
245 devices[internal_dev_index].num_channels = num_channels;
246 // Note: Purposefully does not overwrite held.
248 display_name = devices[internal_dev_index].display_name();
251 fprintf(stderr, "%s: Probed successfully.\n", address);
253 reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card).
255 DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
256 global_audio_mixer->set_display_name(spec, display_name);
257 global_audio_mixer->trigger_state_changed_callback();
259 return ALSAPool::ProbeResult::SUCCESS;
262 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
265 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
266 for (unsigned i = 0; i < devices.size(); ++i) {
267 if (devices[i].state != Device::State::EMPTY &&
268 devices[i].state != Device::State::DEAD &&
269 devices[i].address == address) {
275 void ALSAPool::init()
277 inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
281 void ALSAPool::inotify_thread_func()
283 int inotify_fd = inotify_init();
284 if (inotify_fd == -1) {
285 perror("inotify_init()");
286 fprintf(stderr, "No hotplug of ALSA devices available.\n");
290 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
291 if (watch_fd == -1) {
292 perror("inotify_add_watch()");
293 fprintf(stderr, "No hotplug of ALSA devices available.\n");
298 int size = sizeof(inotify_event) + NAME_MAX + 1;
299 unique_ptr<char[]> buf(new char[size]);
300 while (!should_quit) {
302 fds[0].fd = inotify_fd;
303 fds[0].events = POLLIN;
305 fds[1].fd = should_quit_fd;
306 fds[1].events = POLLIN;
309 int ret = poll(fds, 2, -1);
311 if (errno == EINTR) {
314 perror("poll(inotify_fd)");
322 if (fds[1].revents) break; // should_quit_fd asserted.
324 ret = read(inotify_fd, buf.get(), size);
326 if (errno == EINTR) {
329 perror("read(inotify_fd)");
335 if (ret < int(sizeof(inotify_event))) {
336 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
343 for (int i = 0; i < ret; ) {
344 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
345 i += sizeof(inotify_event) + event->len;
347 if (event->mask & IN_Q_OVERFLOW) {
348 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
351 unsigned card, device;
353 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
354 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
355 printf("Deleted capture device: Card %u, device %u\n", card, device);
356 unplug_device(card, device);
358 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
359 printf("Adding capture device: Card %u, device %u\n", card, device);
360 probe_device_with_retry(card, device);
367 close(should_quit_fd);
370 void ALSAPool::reset_device(unsigned index)
372 lock_guard<mutex> lock(mu);
373 Device *device = &devices[index];
374 if (inputs[index] != nullptr) {
375 inputs[index]->stop_capture_thread();
378 inputs[index].reset();
380 // TODO: Put on a background thread instead of locking?
381 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
382 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
383 inputs[index]->start_capture_thread();
385 device->input = inputs[index].get();
388 unsigned ALSAPool::get_capture_frequency(unsigned index)
390 lock_guard<mutex> lock(mu);
391 assert(devices[index].held);
392 if (devices[index].input)
393 return devices[index].input->get_sample_rate();
395 return OUTPUT_FREQUENCY;
398 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
400 lock_guard<mutex> lock(mu);
401 assert(devices[index].held);
402 return devices[index].state;
405 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
408 lock_guard<mutex> lock(mu);
409 devices[index].state = state;
412 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
413 bool silence = (state != ALSAPool::Device::State::RUNNING);
414 while (!global_audio_mixer->silence_card(spec, silence))
416 global_audio_mixer->trigger_state_changed_callback();
419 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
421 // First try to find an exact match on a dead card.
422 for (unsigned i = 0; i < devices.size(); ++i) {
423 if (devices[i].state == Device::State::DEAD &&
424 devices[i].address == address &&
425 devices[i].name == name &&
426 devices[i].info == info &&
427 devices[i].num_channels == num_channels) {
428 devices[i].state = Device::State::READY;
433 // Then try to find a match on everything but the address
434 // (probably that devices were plugged back in a different order).
435 // If we have two cards that are equal, this might get them mixed up,
436 // but we don't have anything better.
437 for (unsigned i = 0; i < devices.size(); ++i) {
438 if (devices[i].state == Device::State::DEAD &&
439 devices[i].name == name &&
440 devices[i].info == info &&
441 devices[i].num_channels == num_channels) {
442 devices[i].state = Device::State::READY;
447 // OK, so we didn't find a match; see if there are any empty slots.
448 for (unsigned i = 0; i < devices.size(); ++i) {
449 if (devices[i].state == Device::State::EMPTY) {
450 devices[i].state = Device::State::READY;
451 devices[i].held = false;
456 // Failing that, we just insert the new device at the end.
458 new_dev.state = Device::State::READY;
459 new_dev.held = false;
460 devices.push_back(new_dev);
461 inputs.emplace_back(nullptr);
462 return devices.size() - 1;
465 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
467 lock_guard<mutex> lock(mu);
469 // See if there are any empty slots. If not, insert one at the end.
470 vector<Device>::iterator free_device =
471 find_if(devices.begin(), devices.end(),
472 [](const Device &device) { return device.state == Device::State::EMPTY; });
473 if (free_device == devices.end()) {
474 devices.push_back(Device());
475 inputs.emplace_back(nullptr);
476 free_device = devices.end() - 1;
479 free_device->state = Device::State::DEAD;
480 free_device->name = name;
481 free_device->info = info;
482 free_device->num_channels = num_channels;
483 free_device->held = true;
485 return distance(devices.begin(), free_device);
488 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
490 lock_guard<mutex> lock(mu);
491 assert(index < devices.size());
492 assert(devices[index].held);
493 serialized->set_type(DeviceSpecProto::ALSA_INPUT);
494 serialized->set_index(index);
495 serialized->set_display_name(devices[index].display_name());
496 serialized->set_alsa_name(devices[index].name);
497 serialized->set_alsa_info(devices[index].info);
498 serialized->set_num_channels(devices[index].num_channels);
499 serialized->set_address(devices[index].address);
502 void ALSAPool::free_card(unsigned index)
504 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
505 while (!global_audio_mixer->silence_card(spec, true))
509 lock_guard<mutex> lock(mu);
510 if (devices[index].held) {
511 devices[index].state = Device::State::DEAD;
513 devices[index].state = Device::State::EMPTY;
514 inputs[index].reset();
516 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
522 global_audio_mixer->trigger_state_changed_callback();