3 #include <alsa/control.h>
4 #include <alsa/error.h>
9 #include <sys/inotify.h>
14 #include "alsa_input.h"
15 #include "audio_mixer.h"
17 #include "input_mapping.h"
21 using namespace std::placeholders;
25 for (Device &device : devices) {
26 if (device.input != nullptr) {
27 device.input->stop_capture_thread();
31 inotify_thread.join();
33 while (retry_threads_running > 0) {
34 this_thread::sleep_for(std::chrono::milliseconds(100));
38 std::vector<ALSAPool::Device> ALSAPool::get_devices()
40 lock_guard<mutex> lock(mu);
41 for (Device &device : devices) {
47 void ALSAPool::hold_device(unsigned index)
49 lock_guard<mutex> lock(mu);
50 assert(index < devices.size());
51 devices[index].held = true;
54 void ALSAPool::release_device(unsigned index)
56 lock_guard<mutex> lock(mu);
57 if (index < devices.size()) {
58 devices[index].held = false;
62 void ALSAPool::enumerate_devices()
64 // Enumerate all cards.
65 for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
67 snprintf(address, sizeof(address), "hw:%d", card_index);
70 int err = snd_ctl_open(&ctl, address, 0);
72 printf("%s: %s\n", address, snd_strerror(err));
75 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
77 // Enumerate all devices on this card.
78 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
79 probe_device_with_retry(card_index, dev_index);
84 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
87 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
89 lock_guard<mutex> lock(add_device_mutex);
90 if (add_device_tries_left.count(address)) {
91 // Some thread is already busy retrying this,
92 // so just reset its count.
93 add_device_tries_left[address] = num_retries;
97 // Try (while still holding the lock) to add the device synchronously.
98 ProbeResult result = probe_device_once(card_index, dev_index);
99 if (result == ProbeResult::SUCCESS) {
101 } else if (result == ProbeResult::FAILURE) {
104 assert(result == ProbeResult::DEFER);
106 // Add failed for whatever reason (probably just that the device
107 // isn't up yet. Set up a count so that nobody else starts a thread,
108 // then start it ourselves.
109 fprintf(stderr, "Trying %s again in one second...\n", address);
110 add_device_tries_left[address] = num_retries;
111 ++retry_threads_running;
112 thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
115 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
118 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
120 for ( ;; ) { // Termination condition within the loop.
123 // See if there are any retries left.
124 lock_guard<mutex> lock(add_device_mutex);
126 !add_device_tries_left.count(address) ||
127 add_device_tries_left[address] == 0) {
128 add_device_tries_left.erase(address);
129 fprintf(stderr, "Giving up probe of %s.\n", address);
133 // Seemingly there were. Give it a try (we still hold the mutex).
134 ProbeResult result = probe_device_once(card_index, dev_index);
135 if (result == ProbeResult::SUCCESS) {
136 add_device_tries_left.erase(address);
137 fprintf(stderr, "Probe of %s succeeded.\n", address);
139 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
140 add_device_tries_left.erase(address);
141 fprintf(stderr, "Giving up probe of %s.\n", address);
146 assert(result == ProbeResult::DEFER);
147 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
148 address, add_device_tries_left[address]);
151 --retry_threads_running;
154 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
157 snprintf(address, sizeof(address), "hw:%d", card_index);
159 int err = snd_ctl_open(&ctl, address, 0);
161 printf("%s: %s\n", address, snd_strerror(err));
162 return ALSAPool::ProbeResult::DEFER;
164 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
166 snd_pcm_info_t *pcm_info;
167 snd_pcm_info_alloca(&pcm_info);
168 snd_pcm_info_set_device(pcm_info, dev_index);
169 snd_pcm_info_set_subdevice(pcm_info, 0);
170 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
171 if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
172 // Not available for capture.
173 printf("%s: Not available for capture.\n", address);
174 return ALSAPool::ProbeResult::DEFER;
177 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
179 unsigned num_channels = 0;
181 // Find all channel maps for this device, and pick out the one
182 // with the most channels.
183 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
184 if (cmaps != nullptr) {
185 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
186 num_channels = max(num_channels, (*ptr)->map.channels);
188 snd_pcm_free_chmaps(cmaps);
190 if (num_channels == 0) {
191 // Device had no channel maps. We need to open it to query.
192 // TODO: Do this asynchronously.
193 snd_pcm_t *pcm_handle;
194 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
196 printf("%s: %s\n", address, snd_strerror(err));
197 return ALSAPool::ProbeResult::DEFER;
199 snd_pcm_hw_params_t *hw_params;
200 snd_pcm_hw_params_alloca(&hw_params);
201 unsigned sample_rate;
202 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
203 snd_pcm_close(pcm_handle);
204 return ALSAPool::ProbeResult::DEFER;
206 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
208 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
209 address, snd_strerror(err));
210 snd_pcm_close(pcm_handle);
211 return ALSAPool::ProbeResult::DEFER;
213 snd_pcm_close(pcm_handle);
216 if (num_channels == 0) {
217 printf("%s: No channel maps with channels\n", address);
218 return ALSAPool::ProbeResult::FAILURE;
221 snd_ctl_card_info_t *card_info;
222 snd_ctl_card_info_alloca(&card_info);
223 snd_ctl_card_info(ctl, card_info);
225 string name = snd_ctl_card_info_get_name(card_info);
226 string info = snd_pcm_info_get_name(pcm_info);
228 unsigned internal_dev_index;
231 lock_guard<mutex> lock(mu);
232 internal_dev_index = find_free_device_index(name, info, num_channels, address);
233 devices[internal_dev_index].address = address;
234 devices[internal_dev_index].name = name;
235 devices[internal_dev_index].info = info;
236 devices[internal_dev_index].num_channels = num_channels;
237 // Note: Purposefully does not overwrite held.
239 display_name = devices[internal_dev_index].display_name();
242 fprintf(stderr, "%s: Probed successfully.\n", address);
244 reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card).
246 DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
247 global_audio_mixer->set_display_name(spec, display_name);
248 global_audio_mixer->trigger_state_changed_callback();
250 return ALSAPool::ProbeResult::SUCCESS;
253 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
256 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
257 for (unsigned i = 0; i < devices.size(); ++i) {
258 if (devices[i].state != Device::State::EMPTY &&
259 devices[i].state != Device::State::DEAD &&
260 devices[i].address == address) {
266 void ALSAPool::init()
268 inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
272 void ALSAPool::inotify_thread_func()
274 int inotify_fd = inotify_init();
275 if (inotify_fd == -1) {
276 perror("inotify_init()");
277 fprintf(stderr, "No hotplug of ALSA devices available.\n");
281 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
282 if (watch_fd == -1) {
283 perror("inotify_add_watch()");
284 fprintf(stderr, "No hotplug of ALSA devices available.\n");
289 int size = sizeof(inotify_event) + NAME_MAX + 1;
290 unique_ptr<char[]> buf(new char[size]);
291 while (!should_quit) {
297 int ret = poll(&fds, 1, 100);
299 if (errno == EINTR) {
302 perror("poll(inotify_fd)");
310 ret = read(inotify_fd, buf.get(), size);
312 if (errno == EINTR) {
315 perror("read(inotify_fd)");
321 if (ret < int(sizeof(inotify_event))) {
322 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
329 for (int i = 0; i < ret; ) {
330 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
331 i += sizeof(inotify_event) + event->len;
333 if (event->mask & IN_Q_OVERFLOW) {
334 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
337 unsigned card, device;
339 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
340 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
341 printf("Deleted capture device: Card %u, device %u\n", card, device);
342 unplug_device(card, device);
344 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
345 printf("Adding capture device: Card %u, device %u\n", card, device);
346 probe_device_with_retry(card, device);
355 void ALSAPool::reset_device(unsigned index)
357 lock_guard<mutex> lock(mu);
358 Device *device = &devices[index];
359 if (inputs[index] != nullptr) {
360 inputs[index]->stop_capture_thread();
363 inputs[index].reset();
365 // TODO: Put on a background thread instead of locking?
366 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
367 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
368 inputs[index]->start_capture_thread();
370 device->input = inputs[index].get();
373 unsigned ALSAPool::get_capture_frequency(unsigned index)
375 lock_guard<mutex> lock(mu);
376 assert(devices[index].held);
377 if (devices[index].input)
378 return devices[index].input->get_sample_rate();
380 return OUTPUT_FREQUENCY;
383 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
385 lock_guard<mutex> lock(mu);
386 assert(devices[index].held);
387 return devices[index].state;
390 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
393 lock_guard<mutex> lock(mu);
394 devices[index].state = state;
397 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
398 bool silence = (state != ALSAPool::Device::State::RUNNING);
399 while (!global_audio_mixer->silence_card(spec, silence))
401 global_audio_mixer->trigger_state_changed_callback();
404 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
406 // First try to find an exact match on a dead card.
407 for (unsigned i = 0; i < devices.size(); ++i) {
408 if (devices[i].state == Device::State::DEAD &&
409 devices[i].address == address &&
410 devices[i].name == name &&
411 devices[i].info == info &&
412 devices[i].num_channels == num_channels) {
413 devices[i].state = Device::State::READY;
418 // Then try to find a match on everything but the address
419 // (probably that devices were plugged back in a different order).
420 // If we have two cards that are equal, this might get them mixed up,
421 // but we don't have anything better.
422 for (unsigned i = 0; i < devices.size(); ++i) {
423 if (devices[i].state == Device::State::DEAD &&
424 devices[i].name == name &&
425 devices[i].info == info &&
426 devices[i].num_channels == num_channels) {
427 devices[i].state = Device::State::READY;
432 // OK, so we didn't find a match; see if there are any empty slots.
433 for (unsigned i = 0; i < devices.size(); ++i) {
434 if (devices[i].state == Device::State::EMPTY) {
435 devices[i].state = Device::State::READY;
436 devices[i].held = false;
441 // Failing that, we just insert the new device at the end.
443 new_dev.state = Device::State::READY;
444 new_dev.held = false;
445 devices.push_back(new_dev);
446 inputs.emplace_back(nullptr);
447 return devices.size() - 1;
450 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
452 lock_guard<mutex> lock(mu);
454 // See if there are any empty slots. If not, insert one at the end.
455 vector<Device>::iterator free_device =
456 find_if(devices.begin(), devices.end(),
457 [](const Device &device) { return device.state == Device::State::EMPTY; });
458 if (free_device == devices.end()) {
459 devices.push_back(Device());
460 inputs.emplace_back(nullptr);
461 free_device = devices.end() - 1;
464 free_device->state = Device::State::DEAD;
465 free_device->name = name;
466 free_device->info = info;
467 free_device->num_channels = num_channels;
468 free_device->held = true;
470 return distance(devices.begin(), free_device);
473 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
475 lock_guard<mutex> lock(mu);
476 assert(index < devices.size());
477 assert(devices[index].held);
478 serialized->set_type(DeviceSpecProto::ALSA_INPUT);
479 serialized->set_index(index);
480 serialized->set_display_name(devices[index].display_name());
481 serialized->set_alsa_name(devices[index].name);
482 serialized->set_alsa_info(devices[index].info);
483 serialized->set_num_channels(devices[index].num_channels);
484 serialized->set_address(devices[index].address);
487 void ALSAPool::free_card(unsigned index)
489 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
490 while (!global_audio_mixer->silence_card(spec, true))
494 lock_guard<mutex> lock(mu);
495 if (devices[index].held) {
496 devices[index].state = Device::State::DEAD;
498 devices[index].state = Device::State::EMPTY;
499 inputs[index].reset();
501 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
507 global_audio_mixer->trigger_state_changed_callback();