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