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