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 snd_pcm_info_t *pcm_info;
189 snd_pcm_info_alloca(&pcm_info);
190 snd_pcm_info_set_device(pcm_info, dev_index);
191 snd_pcm_info_set_subdevice(pcm_info, 0);
192 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
193 if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
194 // Not available for capture.
195 printf("%s: Not available for capture.\n", address);
196 return ALSAPool::ProbeResult::DEFER;
199 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
201 unsigned num_channels = 0;
203 // Find all channel maps for this device, and pick out the one
204 // with the most channels.
205 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
206 if (cmaps != nullptr) {
207 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
208 num_channels = max(num_channels, (*ptr)->map.channels);
210 snd_pcm_free_chmaps(cmaps);
212 if (num_channels == 0) {
213 // Device had no channel maps. We need to open it to query.
214 // TODO: Do this asynchronously.
215 snd_pcm_t *pcm_handle;
216 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
218 printf("%s: %s\n", address, snd_strerror(err));
219 return ALSAPool::ProbeResult::DEFER;
221 snd_pcm_hw_params_t *hw_params;
222 snd_pcm_hw_params_alloca(&hw_params);
223 unsigned sample_rate;
224 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
225 snd_pcm_close(pcm_handle);
226 return ALSAPool::ProbeResult::DEFER;
228 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
230 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
231 address, snd_strerror(err));
232 snd_pcm_close(pcm_handle);
233 return ALSAPool::ProbeResult::DEFER;
235 snd_pcm_close(pcm_handle);
238 if (num_channels == 0) {
239 printf("%s: No channel maps with channels\n", address);
240 return ALSAPool::ProbeResult::FAILURE;
243 snd_ctl_card_info_t *card_info;
244 snd_ctl_card_info_alloca(&card_info);
245 snd_ctl_card_info(ctl, card_info);
247 string name = snd_ctl_card_info_get_name(card_info);
248 string info = snd_pcm_info_get_name(pcm_info);
250 unsigned internal_dev_index;
253 lock_guard<mutex> lock(mu);
254 internal_dev_index = find_free_device_index(name, info, num_channels, address);
255 devices[internal_dev_index].address = address;
256 devices[internal_dev_index].name = name;
257 devices[internal_dev_index].info = info;
258 devices[internal_dev_index].num_channels = num_channels;
259 // Note: Purposefully does not overwrite held.
261 display_name = devices[internal_dev_index].display_name();
264 fprintf(stderr, "%s: Probed successfully.\n", address);
266 reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card).
268 DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
269 global_audio_mixer->set_display_name(spec, display_name);
270 global_audio_mixer->trigger_state_changed_callback();
272 return ALSAPool::ProbeResult::SUCCESS;
275 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
278 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
279 for (unsigned i = 0; i < devices.size(); ++i) {
280 if (devices[i].state != Device::State::EMPTY &&
281 devices[i].state != Device::State::DEAD &&
282 devices[i].address == address) {
288 void ALSAPool::init()
290 inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
294 void ALSAPool::inotify_thread_func()
296 pthread_setname_np(pthread_self(), "ALSA_Hotplug");
298 int inotify_fd = inotify_init();
299 if (inotify_fd == -1) {
300 perror("inotify_init()");
301 fprintf(stderr, "No hotplug of ALSA devices available.\n");
305 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
306 if (watch_fd == -1) {
307 perror("inotify_add_watch()");
308 fprintf(stderr, "No hotplug of ALSA devices available.\n");
313 int size = sizeof(inotify_event) + NAME_MAX + 1;
314 unique_ptr<char[]> buf(new char[size]);
315 while (!should_quit) {
317 fds[0].fd = inotify_fd;
318 fds[0].events = POLLIN;
320 fds[1].fd = should_quit_fd;
321 fds[1].events = POLLIN;
324 int ret = poll(fds, 2, -1);
326 if (errno == EINTR) {
329 perror("poll(inotify_fd)");
337 if (fds[1].revents) break; // should_quit_fd asserted.
339 ret = read(inotify_fd, buf.get(), size);
341 if (errno == EINTR) {
344 perror("read(inotify_fd)");
350 if (ret < int(sizeof(inotify_event))) {
351 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
358 for (int i = 0; i < ret; ) {
359 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
360 i += sizeof(inotify_event) + event->len;
362 if (event->mask & IN_Q_OVERFLOW) {
363 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
366 unsigned card, device;
368 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
369 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
370 printf("Deleted capture device: Card %u, device %u\n", card, device);
371 unplug_device(card, device);
373 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
374 printf("Adding capture device: Card %u, device %u\n", card, device);
375 probe_device_with_retry(card, device);
382 close(should_quit_fd);
385 void ALSAPool::reset_device(unsigned index)
387 lock_guard<mutex> lock(mu);
388 Device *device = &devices[index];
389 if (inputs[index] != nullptr) {
390 inputs[index]->stop_capture_thread();
393 inputs[index].reset();
395 // TODO: Put on a background thread instead of locking?
396 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4, _5);
397 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
398 inputs[index]->start_capture_thread();
400 device->input = inputs[index].get();
403 unsigned ALSAPool::get_capture_frequency(unsigned index)
405 lock_guard<mutex> lock(mu);
406 assert(devices[index].held);
407 if (devices[index].input)
408 return devices[index].input->get_sample_rate();
410 return OUTPUT_FREQUENCY;
413 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
415 lock_guard<mutex> lock(mu);
416 assert(devices[index].held);
417 return devices[index].state;
420 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
423 lock_guard<mutex> lock(mu);
424 devices[index].state = state;
427 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
428 bool silence = (state != ALSAPool::Device::State::RUNNING);
429 while (!global_audio_mixer->silence_card(spec, silence))
431 global_audio_mixer->trigger_state_changed_callback();
434 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
436 // First try to find an exact match on a dead card.
437 for (unsigned i = 0; i < devices.size(); ++i) {
438 if (devices[i].state == Device::State::DEAD &&
439 devices[i].address == address &&
440 devices[i].name == name &&
441 devices[i].info == info &&
442 devices[i].num_channels == num_channels) {
443 devices[i].state = Device::State::READY;
448 // Then try to find a match on everything but the address
449 // (probably that devices were plugged back in a different order).
450 // If we have two cards that are equal, this might get them mixed up,
451 // but we don't have anything better.
452 for (unsigned i = 0; i < devices.size(); ++i) {
453 if (devices[i].state == Device::State::DEAD &&
454 devices[i].name == name &&
455 devices[i].info == info &&
456 devices[i].num_channels == num_channels) {
457 devices[i].state = Device::State::READY;
462 // OK, so we didn't find a match; see if there are any empty slots.
463 for (unsigned i = 0; i < devices.size(); ++i) {
464 if (devices[i].state == Device::State::EMPTY) {
465 devices[i].state = Device::State::READY;
466 devices[i].held = false;
471 // Failing that, we just insert the new device at the end.
473 new_dev.state = Device::State::READY;
474 new_dev.held = false;
475 devices.push_back(new_dev);
476 inputs.emplace_back(nullptr);
477 return devices.size() - 1;
480 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
482 lock_guard<mutex> lock(mu);
484 // See if there are any empty slots. If not, insert one at the end.
485 vector<Device>::iterator free_device =
486 find_if(devices.begin(), devices.end(),
487 [](const Device &device) { return device.state == Device::State::EMPTY; });
488 if (free_device == devices.end()) {
489 devices.push_back(Device());
490 inputs.emplace_back(nullptr);
491 free_device = devices.end() - 1;
494 free_device->state = Device::State::DEAD;
495 free_device->name = name;
496 free_device->info = info;
497 free_device->num_channels = num_channels;
498 free_device->held = true;
500 return distance(devices.begin(), free_device);
503 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
505 lock_guard<mutex> lock(mu);
506 assert(index < devices.size());
507 assert(devices[index].held);
508 serialized->set_type(DeviceSpecProto::ALSA_INPUT);
509 serialized->set_index(index);
510 serialized->set_display_name(devices[index].display_name());
511 serialized->set_alsa_name(devices[index].name);
512 serialized->set_alsa_info(devices[index].info);
513 serialized->set_num_channels(devices[index].num_channels);
514 serialized->set_address(devices[index].address);
517 void ALSAPool::free_card(unsigned index)
519 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
520 while (!global_audio_mixer->silence_card(spec, true))
524 lock_guard<mutex> lock(mu);
525 if (devices[index].held) {
526 devices[index].state = Device::State::DEAD;
528 devices[index].state = Device::State::EMPTY;
529 inputs[index].reset();
531 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
537 global_audio_mixer->trigger_state_changed_callback();