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