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();
34 std::vector<ALSAPool::Device> ALSAPool::get_devices()
36 lock_guard<mutex> lock(mu);
37 for (Device &device : devices) {
43 void ALSAPool::hold_device(unsigned index)
45 lock_guard<mutex> lock(mu);
46 assert(index < devices.size());
47 devices[index].held = true;
50 void ALSAPool::release_device(unsigned index)
52 lock_guard<mutex> lock(mu);
53 if (index < devices.size()) {
54 devices[index].held = false;
58 void ALSAPool::enumerate_devices()
60 // Enumerate all cards.
61 for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
63 snprintf(address, sizeof(address), "hw:%d", card_index);
66 int err = snd_ctl_open(&ctl, address, 0);
68 printf("%s: %s\n", address, snd_strerror(err));
71 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
73 // Enumerate all devices on this card.
74 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
75 probe_device_with_retry(card_index, dev_index);
80 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
83 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
85 lock_guard<mutex> lock(add_device_mutex);
86 if (add_device_tries_left.count(address)) {
87 // Some thread is already busy retrying this,
88 // so just reset its count.
89 add_device_tries_left[address] = num_retries;
93 // Try (while still holding the lock) to add the device synchronously.
94 ProbeResult result = probe_device_once(card_index, dev_index);
95 if (result == ProbeResult::SUCCESS) {
97 } else if (result == ProbeResult::FAILURE) {
100 assert(result == ProbeResult::DEFER);
102 // Add failed for whatever reason (probably just that the device
103 // isn't up yet. Set up a count so that nobody else starts a thread,
104 // then start it ourselves.
105 fprintf(stderr, "Trying %s again in one second...\n", address);
106 add_device_tries_left[address] = num_retries;
107 thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
110 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
113 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
115 for ( ;; ) { // Termination condition within the loop.
118 // See if there are any retries left.
119 lock_guard<mutex> lock(add_device_mutex);
120 if (!add_device_tries_left.count(address) ||
121 add_device_tries_left[address] == 0) {
122 add_device_tries_left.erase(address);
123 fprintf(stderr, "Giving up probe of %s.\n", address);
127 // Seemingly there were. Give it a try (we still hold the mutex).
128 ProbeResult result = probe_device_once(card_index, dev_index);
129 if (result == ProbeResult::SUCCESS) {
130 add_device_tries_left.erase(address);
131 fprintf(stderr, "Probe of %s succeeded.\n", address);
133 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
134 add_device_tries_left.erase(address);
135 fprintf(stderr, "Giving up probe of %s.\n", address);
140 assert(result == ProbeResult::DEFER);
141 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
142 address, add_device_tries_left[address]);
146 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
149 snprintf(address, sizeof(address), "hw:%d", card_index);
151 int err = snd_ctl_open(&ctl, address, 0);
153 printf("%s: %s\n", address, snd_strerror(err));
154 return ALSAPool::ProbeResult::DEFER;
156 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
158 snd_pcm_info_t *pcm_info;
159 snd_pcm_info_alloca(&pcm_info);
160 snd_pcm_info_set_device(pcm_info, dev_index);
161 snd_pcm_info_set_subdevice(pcm_info, 0);
162 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
163 if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
164 // Not available for capture.
165 printf("%s: Not available for capture.\n", address);
166 return ALSAPool::ProbeResult::DEFER;
169 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
171 unsigned num_channels = 0;
173 // Find all channel maps for this device, and pick out the one
174 // with the most channels.
175 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
176 if (cmaps != nullptr) {
177 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
178 num_channels = max(num_channels, (*ptr)->map.channels);
180 snd_pcm_free_chmaps(cmaps);
182 if (num_channels == 0) {
183 // Device had no channel maps. We need to open it to query.
184 // TODO: Do this asynchronously.
185 snd_pcm_t *pcm_handle;
186 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
188 printf("%s: %s\n", address, snd_strerror(err));
189 return ALSAPool::ProbeResult::DEFER;
191 snd_pcm_hw_params_t *hw_params;
192 snd_pcm_hw_params_alloca(&hw_params);
193 unsigned sample_rate;
194 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
195 snd_pcm_close(pcm_handle);
196 return ALSAPool::ProbeResult::DEFER;
198 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
200 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
201 address, snd_strerror(err));
202 snd_pcm_close(pcm_handle);
203 return ALSAPool::ProbeResult::DEFER;
205 snd_pcm_close(pcm_handle);
208 if (num_channels == 0) {
209 printf("%s: No channel maps with channels\n", address);
210 return ALSAPool::ProbeResult::FAILURE;
213 snd_ctl_card_info_t *card_info;
214 snd_ctl_card_info_alloca(&card_info);
215 snd_ctl_card_info(ctl, card_info);
217 string name = snd_ctl_card_info_get_name(card_info);
218 string info = snd_pcm_info_get_name(pcm_info);
220 unsigned internal_dev_index;
223 lock_guard<mutex> lock(mu);
224 internal_dev_index = find_free_device_index(name, info, num_channels, address);
225 devices[internal_dev_index].address = address;
226 devices[internal_dev_index].name = name;
227 devices[internal_dev_index].info = info;
228 devices[internal_dev_index].num_channels = num_channels;
229 // Note: Purposefully does not overwrite held.
231 display_name = devices[internal_dev_index].display_name();
234 fprintf(stderr, "%s: Probed successfully.\n", address);
236 reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card).
238 DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
239 global_audio_mixer->set_display_name(spec, display_name);
240 global_audio_mixer->trigger_state_changed_callback();
242 return ALSAPool::ProbeResult::SUCCESS;
245 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
248 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
249 for (unsigned i = 0; i < devices.size(); ++i) {
250 if (devices[i].state != Device::State::EMPTY &&
251 devices[i].state != Device::State::DEAD &&
252 devices[i].address == address) {
258 void ALSAPool::init()
260 inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
264 void ALSAPool::inotify_thread_func()
266 int inotify_fd = inotify_init();
267 if (inotify_fd == -1) {
268 perror("inotify_init()");
269 fprintf(stderr, "No hotplug of ALSA devices available.\n");
273 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
274 if (watch_fd == -1) {
275 perror("inotify_add_watch()");
276 fprintf(stderr, "No hotplug of ALSA devices available.\n");
281 int size = sizeof(inotify_event) + NAME_MAX + 1;
282 unique_ptr<char[]> buf(new char[size]);
283 while (!should_quit) {
289 int ret = poll(&fds, 1, 100);
291 if (errno == EINTR) {
294 perror("poll(inotify_fd)");
302 ret = read(inotify_fd, buf.get(), size);
304 if (errno == EINTR) {
307 perror("read(inotify_fd)");
313 if (ret < int(sizeof(inotify_event))) {
314 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
321 for (int i = 0; i < ret; ) {
322 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
323 i += sizeof(inotify_event) + event->len;
325 if (event->mask & IN_Q_OVERFLOW) {
326 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
329 unsigned card, device;
331 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
332 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
333 printf("Deleted capture device: Card %u, device %u\n", card, device);
334 unplug_device(card, device);
336 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
337 printf("Adding capture device: Card %u, device %u\n", card, device);
338 probe_device_with_retry(card, device);
347 void ALSAPool::reset_device(unsigned index)
349 lock_guard<mutex> lock(mu);
350 Device *device = &devices[index];
351 if (inputs[index] != nullptr) {
352 inputs[index]->stop_capture_thread();
355 inputs[index].reset();
357 // TODO: Put on a background thread instead of locking?
358 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
359 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
360 inputs[index]->start_capture_thread();
362 device->input = inputs[index].get();
365 unsigned ALSAPool::get_capture_frequency(unsigned index)
367 lock_guard<mutex> lock(mu);
368 assert(devices[index].held);
369 if (devices[index].input)
370 return devices[index].input->get_sample_rate();
372 return OUTPUT_FREQUENCY;
375 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
377 lock_guard<mutex> lock(mu);
378 assert(devices[index].held);
379 return devices[index].state;
382 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
385 lock_guard<mutex> lock(mu);
386 devices[index].state = state;
389 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
390 bool silence = (state != ALSAPool::Device::State::RUNNING);
391 while (!global_audio_mixer->silence_card(spec, silence))
393 global_audio_mixer->trigger_state_changed_callback();
396 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
398 // First try to find an exact match on a dead card.
399 for (unsigned i = 0; i < devices.size(); ++i) {
400 if (devices[i].state == Device::State::DEAD &&
401 devices[i].address == address &&
402 devices[i].name == name &&
403 devices[i].info == info &&
404 devices[i].num_channels == num_channels) {
405 devices[i].state = Device::State::READY;
410 // Then try to find a match on everything but the address
411 // (probably that devices were plugged back in a different order).
412 // If we have two cards that are equal, this might get them mixed up,
413 // but we don't have anything better.
414 for (unsigned i = 0; i < devices.size(); ++i) {
415 if (devices[i].state == Device::State::DEAD &&
416 devices[i].name == name &&
417 devices[i].info == info &&
418 devices[i].num_channels == num_channels) {
419 devices[i].state = Device::State::READY;
424 // OK, so we didn't find a match; see if there are any empty slots.
425 for (unsigned i = 0; i < devices.size(); ++i) {
426 if (devices[i].state == Device::State::EMPTY) {
427 devices[i].state = Device::State::READY;
428 devices[i].held = false;
433 // Failing that, we just insert the new device at the end.
435 new_dev.state = Device::State::READY;
436 new_dev.held = false;
437 devices.push_back(new_dev);
438 inputs.emplace_back(nullptr);
439 return devices.size() - 1;
442 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
444 lock_guard<mutex> lock(mu);
446 // See if there are any empty slots. If not, insert one at the end.
447 vector<Device>::iterator free_device =
448 find_if(devices.begin(), devices.end(),
449 [](const Device &device) { return device.state == Device::State::EMPTY; });
450 if (free_device == devices.end()) {
451 devices.push_back(Device());
452 inputs.emplace_back(nullptr);
453 free_device = devices.end() - 1;
456 free_device->state = Device::State::DEAD;
457 free_device->name = name;
458 free_device->info = info;
459 free_device->num_channels = num_channels;
460 free_device->held = true;
462 return distance(devices.begin(), free_device);
465 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
467 lock_guard<mutex> lock(mu);
468 assert(index < devices.size());
469 assert(devices[index].held);
470 serialized->set_type(DeviceSpecProto::ALSA_INPUT);
471 serialized->set_index(index);
472 serialized->set_display_name(devices[index].display_name());
473 serialized->set_alsa_name(devices[index].name);
474 serialized->set_alsa_info(devices[index].info);
475 serialized->set_num_channels(devices[index].num_channels);
476 serialized->set_address(devices[index].address);
479 void ALSAPool::free_card(unsigned index)
481 DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
482 while (!global_audio_mixer->silence_card(spec, true))
486 lock_guard<mutex> lock(mu);
487 if (devices[index].held) {
488 devices[index].state = Device::State::DEAD;
490 devices[index].state = Device::State::EMPTY;
491 inputs[index].reset();
493 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
499 global_audio_mixer->trigger_state_changed_callback();