]> git.sesse.net Git - nageru/blob - nageru/alsa_pool.cpp
c74ed26613a5a31449d7e5c9938a38dea45ec86d
[nageru] / nageru / alsa_pool.cpp
1 #include "alsa_pool.h"
2
3 #include <alsa/asoundlib.h>
4 #include <assert.h>
5 #include <errno.h>
6 #include <limits.h>
7 #include <pthread.h>
8 #include <poll.h>
9 #include <stdint.h>
10 #include <stdio.h>
11 #include <sys/eventfd.h>
12 #include <sys/inotify.h>
13 #include <unistd.h>
14 #include <algorithm>
15 #include <chrono>
16 #include <functional>
17 #include <iterator>
18 #include <memory>
19 #include <ratio>
20
21 #include "alsa_input.h"
22 #include "audio_mixer.h"
23 #include "defs.h"
24 #include "input_mapping.h"
25 #include "state.pb.h"
26
27 using namespace std;
28 using namespace std::placeholders;
29
30 ALSAPool::ALSAPool()
31 {
32         should_quit_fd = eventfd(/*initval=*/0, /*flags=*/0);
33         assert(should_quit_fd != -1);
34 }
35
36 ALSAPool::~ALSAPool()
37 {
38         for (Device &device : devices) {
39                 if (device.input != nullptr) {
40                         device.input->stop_capture_thread();
41                 }
42         }
43         should_quit = true;
44         const uint64_t one = 1;
45         if (write(should_quit_fd, &one, sizeof(one)) != sizeof(one)) {
46                 perror("write(should_quit_fd)");
47                 abort();
48         }
49         inotify_thread.join();
50
51         while (retry_threads_running > 0) {
52                 this_thread::sleep_for(std::chrono::milliseconds(100));
53         }
54 }
55
56 std::vector<ALSAPool::Device> ALSAPool::get_devices(bool hold_devices)
57 {
58         lock_guard<mutex> lock(mu);
59         if (hold_devices) {
60                 for (Device &device : devices) {
61                         device.held = true;
62                 }
63         }
64         return devices;
65 }
66
67 void ALSAPool::hold_device(unsigned index)
68 {
69         lock_guard<mutex> lock(mu);
70         assert(index < devices.size());
71         devices[index].held = true;
72 }
73
74 void ALSAPool::release_device(unsigned index)
75 {
76         lock_guard<mutex> lock(mu);
77         if (index < devices.size()) {
78                 devices[index].held = false;
79         }
80 }
81
82 void ALSAPool::enumerate_devices()
83 {
84         // Enumerate all cards.
85         for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
86                 char address[256];
87                 snprintf(address, sizeof(address), "hw:%d", card_index);
88
89                 snd_ctl_t *ctl;
90                 int err = snd_ctl_open(&ctl, address, 0);
91                 if (err < 0) {
92                         printf("%s: %s\n", address, snd_strerror(err));
93                         continue;
94                 }
95                 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
96
97                 // Enumerate all devices on this card.
98                 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
99                         probe_device_with_retry(card_index, dev_index);
100                 }
101         }
102 }
103
104 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
105 {
106         char address[256];
107         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
108
109         lock_guard<mutex> lock(add_device_mutex);
110         if (add_device_tries_left.count(address)) {
111                 // Some thread is already busy retrying this,
112                 // so just reset its count.
113                 add_device_tries_left[address] = num_retries;
114                 return;
115         }
116
117         // Try (while still holding the lock) to add the device synchronously.
118         ProbeResult result = probe_device_once(card_index, dev_index);
119         if (result == ProbeResult::SUCCESS) {
120                 return;
121         } else if (result == ProbeResult::FAILURE) {
122                 return;
123         }
124         assert(result == ProbeResult::DEFER);
125
126         // Add failed for whatever reason (probably just that the device
127         // isn't up yet. Set up a count so that nobody else starts a thread,
128         // then start it ourselves.
129         fprintf(stderr, "Trying %s again in one second...\n", address);
130         add_device_tries_left[address] = num_retries;
131         ++retry_threads_running;
132         thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
133 }
134
135 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
136 {
137         char address[256];
138         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
139
140         char thread_name[16];
141         snprintf(thread_name, sizeof(thread_name), "Reprobe_hw:%d,%d", card_index, dev_index);
142         pthread_setname_np(pthread_self(), thread_name);
143
144         for ( ;; ) {  // Termination condition within the loop.
145                 sleep(1);
146
147                 // See if there are any retries left.
148                 lock_guard<mutex> lock(add_device_mutex);
149                 if (should_quit ||
150                     !add_device_tries_left.count(address) ||
151                     add_device_tries_left[address] == 0) {
152                         add_device_tries_left.erase(address);
153                         fprintf(stderr, "Giving up probe of %s.\n", address);
154                         break;
155                 }
156
157                 // Seemingly there were. Give it a try (we still hold the mutex).
158                 ProbeResult result = probe_device_once(card_index, dev_index);
159                 if (result == ProbeResult::SUCCESS) {
160                         add_device_tries_left.erase(address);
161                         fprintf(stderr, "Probe of %s succeeded.\n", address);
162                         break;
163                 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
164                         add_device_tries_left.erase(address);
165                         fprintf(stderr, "Giving up probe of %s.\n", address);
166                         break;
167                 }
168
169                 // Failed again.
170                 assert(result == ProbeResult::DEFER);
171                 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
172                         address, add_device_tries_left[address]);
173         }
174
175         --retry_threads_running;
176 }
177
178 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
179 {
180         char address[256];
181         snprintf(address, sizeof(address), "hw:%d", card_index);
182         snd_ctl_t *ctl;
183         int err = snd_ctl_open(&ctl, address, 0);
184         if (err < 0) {
185                 printf("%s: %s\n", address, snd_strerror(err));
186                 return ALSAPool::ProbeResult::DEFER;
187         }
188         unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
189
190         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
191
192         snd_pcm_info_t *pcm_info;
193         snd_pcm_info_alloca(&pcm_info);
194         snd_pcm_info_set_device(pcm_info, dev_index);
195         snd_pcm_info_set_subdevice(pcm_info, 0);
196         snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
197         err = snd_ctl_pcm_info(ctl, pcm_info);
198         if (err == -ENOENT) {
199                 // Not a capture card.
200                 return ALSAPool::ProbeResult::FAILURE;
201         }
202         if (err < 0) {
203                 // Not available for capture.
204                 printf("%s: Not available for capture.\n", address);
205                 return ALSAPool::ProbeResult::DEFER;
206         }
207
208         unsigned num_channels = 0;
209
210         // Find all channel maps for this device, and pick out the one
211         // with the most channels.
212         snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
213         if (cmaps != nullptr) {
214                 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
215                         num_channels = max(num_channels, (*ptr)->map.channels);
216                 }
217                 snd_pcm_free_chmaps(cmaps);
218         }
219         if (num_channels == 0) {
220                 // Device had no channel maps. We need to open it to query.
221                 // TODO: Do this asynchronously.
222                 snd_pcm_t *pcm_handle;
223                 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
224                 if (err < 0) {
225                         printf("%s: %s\n", address, snd_strerror(err));
226                         return ALSAPool::ProbeResult::DEFER;
227                 }
228                 snd_pcm_hw_params_t *hw_params;
229                 snd_pcm_hw_params_alloca(&hw_params);
230                 unsigned sample_rate;
231                 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
232                         snd_pcm_close(pcm_handle);
233                         return ALSAPool::ProbeResult::DEFER;
234                 }
235                 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
236                 if (err < 0) {
237                         fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
238                                 address, snd_strerror(err));
239                         snd_pcm_close(pcm_handle);
240                         return ALSAPool::ProbeResult::DEFER;
241                 }
242                 snd_pcm_close(pcm_handle);
243         }
244
245         if (num_channels == 0) {
246                 printf("%s: No channel maps with channels\n", address);
247                 return ALSAPool::ProbeResult::FAILURE;
248         }
249
250         snd_ctl_card_info_t *card_info;
251         snd_ctl_card_info_alloca(&card_info);
252         snd_ctl_card_info(ctl, card_info);
253
254         string name = snd_ctl_card_info_get_name(card_info);
255         string info = snd_pcm_info_get_name(pcm_info);
256
257         unsigned internal_dev_index;
258         string display_name;
259         {
260                 lock_guard<mutex> lock(mu);
261                 internal_dev_index = find_free_device_index(name, info, num_channels, address);
262                 devices[internal_dev_index].address = address;
263                 devices[internal_dev_index].name = name;
264                 devices[internal_dev_index].info = info;
265                 devices[internal_dev_index].num_channels = num_channels;
266                 // Note: Purposefully does not overwrite held.
267
268                 display_name = devices[internal_dev_index].display_name();
269         }
270
271         fprintf(stderr, "%s: Probed successfully.\n", address);
272
273         reset_device(internal_dev_index);  // Restarts it if it is held (ie., we just replaced a dead card).
274
275         DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
276         global_audio_mixer->set_display_name(spec, display_name);
277         global_audio_mixer->trigger_state_changed_callback();
278
279         return ALSAPool::ProbeResult::SUCCESS;
280 }
281
282 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
283 {
284         char address[256];
285         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
286         for (unsigned i = 0; i < devices.size(); ++i) {
287                 if (devices[i].state != Device::State::EMPTY &&
288                     devices[i].state != Device::State::DEAD &&
289                     devices[i].address == address) {
290                         free_card(i);
291                 }
292         }
293 }
294
295 void ALSAPool::init()
296 {
297         inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
298         enumerate_devices();
299 }
300
301 void ALSAPool::inotify_thread_func()
302 {
303         pthread_setname_np(pthread_self(), "ALSA_Hotplug");
304
305         int inotify_fd = inotify_init();
306         if (inotify_fd == -1) {
307                 perror("inotify_init()");
308                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
309                 return;
310         }
311
312         int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
313         if (watch_fd == -1) {
314                 perror("inotify_add_watch()");
315                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
316                 close(inotify_fd);
317                 return;
318         }
319
320         int size = sizeof(inotify_event) + NAME_MAX + 1;
321         unique_ptr<char[]> buf(new char[size]);
322         while (!should_quit) {
323                 pollfd fds[2];
324                 fds[0].fd = inotify_fd;
325                 fds[0].events = POLLIN;
326                 fds[0].revents = 0;
327                 fds[1].fd = should_quit_fd;
328                 fds[1].events = POLLIN;
329                 fds[1].revents = 0;
330
331                 int ret = poll(fds, 2, -1);
332                 if (ret == -1) {
333                         if (errno == EINTR) {
334                                 continue;
335                         } else {
336                                 perror("poll(inotify_fd)");
337                                 return;
338                         }
339                 }
340                 if (ret == 0) {
341                         continue;
342                 }
343
344                 if (fds[1].revents) break;  // should_quit_fd asserted.
345
346                 ret = read(inotify_fd, buf.get(), size);
347                 if (ret == -1) {
348                         if (errno == EINTR) {
349                                 continue;
350                         } else {
351                                 perror("read(inotify_fd)");
352                                 close(watch_fd);
353                                 close(inotify_fd);
354                                 return;
355                         }
356                 }
357                 if (ret < int(sizeof(inotify_event))) {
358                         fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
359                                 int(ret));
360                         close(watch_fd);
361                         close(inotify_fd);
362                         return;
363                 }
364
365                 for (int i = 0; i < ret; ) {
366                         const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
367                         i += sizeof(inotify_event) + event->len;
368
369                         if (event->mask & IN_Q_OVERFLOW) {
370                                 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
371                                 continue;
372                         }
373                         unsigned card, device;
374                         char type;
375                         if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
376                                 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
377                                         printf("Deleted capture device: Card %u, device %u\n", card, device);
378                                         unplug_device(card, device);
379                                 }
380                                 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
381                                         printf("Adding capture device: Card %u, device %u\n", card, device);
382                                         probe_device_with_retry(card, device);
383                                 }
384                         }
385                 }
386         }
387         close(watch_fd);
388         close(inotify_fd);
389         close(should_quit_fd);
390 }
391
392 void ALSAPool::reset_device(unsigned index)
393 {
394         lock_guard<mutex> lock(mu);
395         Device *device = &devices[index];
396         if (device->state == Device::State::DEAD) {
397                 // Not running, and should not be started.
398                 return;
399         }
400         if (inputs[index] != nullptr) {
401                 inputs[index]->stop_capture_thread();
402         }
403         if (!device->held) {
404                 inputs[index].reset();
405         } else {
406                 // TODO: Put on a background thread instead of locking?
407                 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
408                 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
409                 inputs[index]->start_capture_thread();
410         }
411         device->input = inputs[index].get();
412 }
413
414 unsigned ALSAPool::get_capture_frequency(unsigned index)
415 {
416         lock_guard<mutex> lock(mu);
417         assert(devices[index].held);
418         if (devices[index].input)
419                 return devices[index].input->get_sample_rate();
420         else
421                 return OUTPUT_FREQUENCY;
422 }
423
424 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
425 {
426         lock_guard<mutex> lock(mu);
427         assert(devices[index].held);
428         return devices[index].state;
429 }
430
431 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
432 {
433         {
434                 lock_guard<mutex> lock(mu);
435                 devices[index].state = state;
436         }
437
438         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
439         bool silence = (state != ALSAPool::Device::State::RUNNING);
440         while (!global_audio_mixer->silence_card(spec, silence))
441                 ;
442         global_audio_mixer->trigger_state_changed_callback();
443 }
444
445 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
446 {
447         // First try to find an exact match on a dead card.
448         for (unsigned i = 0; i < devices.size(); ++i) {
449                 if (devices[i].state == Device::State::DEAD &&
450                     devices[i].address == address &&
451                     devices[i].name == name &&
452                     devices[i].info == info &&
453                     devices[i].num_channels == num_channels) {
454                         devices[i].state = Device::State::READY;
455                         return i;
456                 }
457         }
458
459         // Then try to find a match on everything but the address
460         // (probably that devices were plugged back in a different order).
461         // If we have two cards that are equal, this might get them mixed up,
462         // but we don't have anything better.
463         for (unsigned i = 0; i < devices.size(); ++i) {
464                 if (devices[i].state == Device::State::DEAD &&
465                     devices[i].name == name &&
466                     devices[i].info == info &&
467                     devices[i].num_channels == num_channels) {
468                         devices[i].state = Device::State::READY;
469                         return i;
470                 }
471         }
472
473         // OK, so we didn't find a match; see if there are any empty slots.
474         for (unsigned i = 0; i < devices.size(); ++i) {
475                 if (devices[i].state == Device::State::EMPTY) {
476                         devices[i].state = Device::State::READY;
477                         devices[i].held = false;
478                         return i;
479                 }
480         }
481
482         // Failing that, we just insert the new device at the end.
483         Device new_dev;
484         new_dev.state = Device::State::READY;
485         new_dev.held = false;
486         devices.push_back(new_dev);
487         inputs.emplace_back(nullptr);
488         return devices.size() - 1;
489 }
490
491 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
492 {
493         lock_guard<mutex> lock(mu);
494
495         // See if there are any empty slots. If not, insert one at the end.
496         vector<Device>::iterator free_device =
497                 find_if(devices.begin(), devices.end(),
498                         [](const Device &device) { return device.state == Device::State::EMPTY; });
499         if (free_device == devices.end()) {
500                 devices.push_back(Device());
501                 inputs.emplace_back(nullptr);
502                 free_device = devices.end() - 1;
503         }
504
505         free_device->state = Device::State::DEAD;
506         free_device->name = name;
507         free_device->info = info;
508         free_device->num_channels = num_channels;
509         free_device->held = true;
510
511         return distance(devices.begin(), free_device);
512 }
513
514 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
515 {
516         lock_guard<mutex> lock(mu);
517         assert(index < devices.size());
518         assert(devices[index].held);
519         serialized->set_type(DeviceSpecProto::ALSA_INPUT);
520         serialized->set_index(index);
521         serialized->set_display_name(devices[index].display_name());
522         serialized->set_alsa_name(devices[index].name);
523         serialized->set_alsa_info(devices[index].info);
524         serialized->set_num_channels(devices[index].num_channels);
525         serialized->set_address(devices[index].address);
526 }
527
528 void ALSAPool::free_card(unsigned index)
529 {
530         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
531         while (!global_audio_mixer->silence_card(spec, true))
532                 ;
533
534         {
535                 lock_guard<mutex> lock(mu);
536                 if (devices[index].held) {
537                         devices[index].state = Device::State::DEAD;
538                 } else {
539                         devices[index].state = Device::State::EMPTY;
540                         inputs[index].reset();
541                 }
542                 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
543                         devices.pop_back();
544                         inputs.pop_back();
545                 }
546         }
547
548         global_audio_mixer->trigger_state_changed_callback();
549 }