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