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