]> git.sesse.net Git - nageru/blob - nageru/alsa_pool.cpp
Remove more not-so-useful output.
[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()
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         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
189
190         snd_pcm_info_t *pcm_info;
191         snd_pcm_info_alloca(&pcm_info);
192         snd_pcm_info_set_device(pcm_info, dev_index);
193         snd_pcm_info_set_subdevice(pcm_info, 0);
194         snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
195         err = snd_ctl_pcm_info(ctl, pcm_info);
196         if (err == -ENOENT) {
197                 // Not a capture card.
198                 return ALSAPool::ProbeResult::FAILURE;
199         }
200         if (err < 0) {
201                 // Not available for capture.
202                 printf("%s: Not available for capture.\n", address);
203                 return ALSAPool::ProbeResult::DEFER;
204         }
205
206         unsigned num_channels = 0;
207
208         // Find all channel maps for this device, and pick out the one
209         // with the most channels.
210         snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
211         if (cmaps != nullptr) {
212                 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
213                         num_channels = max(num_channels, (*ptr)->map.channels);
214                 }
215                 snd_pcm_free_chmaps(cmaps);
216         }
217         if (num_channels == 0) {
218                 // Device had no channel maps. We need to open it to query.
219                 // TODO: Do this asynchronously.
220                 snd_pcm_t *pcm_handle;
221                 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
222                 if (err < 0) {
223                         printf("%s: %s\n", address, snd_strerror(err));
224                         return ALSAPool::ProbeResult::DEFER;
225                 }
226                 snd_pcm_hw_params_t *hw_params;
227                 snd_pcm_hw_params_alloca(&hw_params);
228                 unsigned sample_rate;
229                 if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
230                         snd_pcm_close(pcm_handle);
231                         return ALSAPool::ProbeResult::DEFER;
232                 }
233                 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
234                 if (err < 0) {
235                         fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
236                                 address, snd_strerror(err));
237                         snd_pcm_close(pcm_handle);
238                         return ALSAPool::ProbeResult::DEFER;
239                 }
240                 snd_pcm_close(pcm_handle);
241         }
242
243         if (num_channels == 0) {
244                 printf("%s: No channel maps with channels\n", address);
245                 return ALSAPool::ProbeResult::FAILURE;
246         }
247
248         snd_ctl_card_info_t *card_info;
249         snd_ctl_card_info_alloca(&card_info);
250         snd_ctl_card_info(ctl, card_info);
251
252         string name = snd_ctl_card_info_get_name(card_info);
253         string info = snd_pcm_info_get_name(pcm_info);
254
255         unsigned internal_dev_index;
256         string display_name;
257         {
258                 lock_guard<mutex> lock(mu);
259                 internal_dev_index = find_free_device_index(name, info, num_channels, address);
260                 devices[internal_dev_index].address = address;
261                 devices[internal_dev_index].name = name;
262                 devices[internal_dev_index].info = info;
263                 devices[internal_dev_index].num_channels = num_channels;
264                 // Note: Purposefully does not overwrite held.
265
266                 display_name = devices[internal_dev_index].display_name();
267         }
268
269         reset_device(internal_dev_index);  // Restarts it if it is held (ie., we just replaced a dead card).
270
271         DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
272         global_audio_mixer->set_device_parameters(spec, display_name, CardType::LIVE_CARD, /*num_channels=*/0, /*active=*/true);  // Type and channels are ignored.
273         global_audio_mixer->trigger_state_changed_callback();
274
275         return ALSAPool::ProbeResult::SUCCESS;
276 }
277
278 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
279 {
280         char address[256];
281         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
282         for (unsigned i = 0; i < devices.size(); ++i) {
283                 if (devices[i].state != Device::State::EMPTY &&
284                     devices[i].state != Device::State::DEAD &&
285                     devices[i].address == address) {
286                         free_card(i);
287                 }
288         }
289 }
290
291 void ALSAPool::init()
292 {
293         inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
294         enumerate_devices();
295 }
296
297 void ALSAPool::inotify_thread_func()
298 {
299         pthread_setname_np(pthread_self(), "ALSA_Hotplug");
300
301         int inotify_fd = inotify_init();
302         if (inotify_fd == -1) {
303                 perror("inotify_init()");
304                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
305                 return;
306         }
307
308         int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
309         if (watch_fd == -1) {
310                 perror("inotify_add_watch()");
311                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
312                 close(inotify_fd);
313                 return;
314         }
315
316         int size = sizeof(inotify_event) + NAME_MAX + 1;
317         unique_ptr<char[]> buf(new char[size]);
318         while (!should_quit) {
319                 pollfd fds[2];
320                 fds[0].fd = inotify_fd;
321                 fds[0].events = POLLIN;
322                 fds[0].revents = 0;
323                 fds[1].fd = should_quit_fd;
324                 fds[1].events = POLLIN;
325                 fds[1].revents = 0;
326
327                 int ret = poll(fds, 2, -1);
328                 if (ret == -1) {
329                         if (errno == EINTR) {
330                                 continue;
331                         } else {
332                                 perror("poll(inotify_fd)");
333                                 return;
334                         }
335                 }
336                 if (ret == 0) {
337                         continue;
338                 }
339
340                 if (fds[1].revents) break;  // should_quit_fd asserted.
341
342                 ret = read(inotify_fd, buf.get(), size);
343                 if (ret == -1) {
344                         if (errno == EINTR) {
345                                 continue;
346                         } else {
347                                 perror("read(inotify_fd)");
348                                 close(watch_fd);
349                                 close(inotify_fd);
350                                 return;
351                         }
352                 }
353                 if (ret < int(sizeof(inotify_event))) {
354                         fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
355                                 int(ret));
356                         close(watch_fd);
357                         close(inotify_fd);
358                         return;
359                 }
360
361                 for (int i = 0; i < ret; ) {
362                         const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
363                         i += sizeof(inotify_event) + event->len;
364
365                         if (event->mask & IN_Q_OVERFLOW) {
366                                 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
367                                 continue;
368                         }
369                         unsigned card, device;
370                         char type;
371                         if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
372                                 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
373                                         printf("Deleted capture device: Card %u, device %u\n", card, device);
374                                         unplug_device(card, device);
375                                 }
376                                 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
377                                         printf("Adding capture device: Card %u, device %u\n", card, device);
378                                         probe_device_with_retry(card, device);
379                                 }
380                         }
381                 }
382         }
383         close(watch_fd);
384         close(inotify_fd);
385         close(should_quit_fd);
386 }
387
388 void ALSAPool::reset_device(unsigned index)
389 {
390         lock_guard<mutex> lock(mu);
391         Device *device = &devices[index];
392         if (device->state == Device::State::DEAD) {
393                 // Not running, and should not be started.
394                 return;
395         }
396         if (inputs[index] != nullptr) {
397                 inputs[index]->stop_capture_thread();
398         }
399         if (!device->held) {
400                 inputs[index].reset();
401         } else {
402                 // TODO: Put on a background thread instead of locking?
403                 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
404                 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
405                 inputs[index]->start_capture_thread();
406         }
407         device->input = inputs[index].get();
408 }
409
410 unsigned ALSAPool::get_capture_frequency(unsigned index)
411 {
412         lock_guard<mutex> lock(mu);
413         assert(devices[index].held);
414         if (devices[index].input)
415                 return devices[index].input->get_sample_rate();
416         else
417                 return OUTPUT_FREQUENCY;
418 }
419
420 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
421 {
422         lock_guard<mutex> lock(mu);
423         assert(devices[index].held);
424         return devices[index].state;
425 }
426
427 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
428 {
429         {
430                 lock_guard<mutex> lock(mu);
431                 devices[index].state = state;
432         }
433
434         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
435         bool silence = (state != ALSAPool::Device::State::RUNNING);
436         while (!global_audio_mixer->silence_card(spec, silence))
437                 ;
438         global_audio_mixer->trigger_state_changed_callback();
439 }
440
441 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
442 {
443         // First try to find an exact match on a dead card.
444         for (unsigned i = 0; i < devices.size(); ++i) {
445                 if (devices[i].state == Device::State::DEAD &&
446                     devices[i].address == address &&
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         // Then try to find a match on everything but the address
456         // (probably that devices were plugged back in a different order).
457         // If we have two cards that are equal, this might get them mixed up,
458         // but we don't have anything better.
459         for (unsigned i = 0; i < devices.size(); ++i) {
460                 if (devices[i].state == Device::State::DEAD &&
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         // OK, so we didn't find a match; see if there are any empty slots.
470         for (unsigned i = 0; i < devices.size(); ++i) {
471                 if (devices[i].state == Device::State::EMPTY) {
472                         devices[i].state = Device::State::READY;
473                         devices[i].held = false;
474                         return i;
475                 }
476         }
477
478         // Failing that, we just insert the new device at the end.
479         Device new_dev;
480         new_dev.state = Device::State::READY;
481         new_dev.held = false;
482         devices.push_back(new_dev);
483         inputs.emplace_back(nullptr);
484         return devices.size() - 1;
485 }
486
487 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
488 {
489         lock_guard<mutex> lock(mu);
490
491         // See if there are any empty slots. If not, insert one at the end.
492         vector<Device>::iterator free_device =
493                 find_if(devices.begin(), devices.end(),
494                         [](const Device &device) { return device.state == Device::State::EMPTY; });
495         if (free_device == devices.end()) {
496                 devices.push_back(Device());
497                 inputs.emplace_back(nullptr);
498                 free_device = devices.end() - 1;
499         }
500
501         free_device->state = Device::State::DEAD;
502         free_device->name = name;
503         free_device->info = info;
504         free_device->num_channels = num_channels;
505         free_device->held = true;
506
507         return distance(devices.begin(), free_device);
508 }
509
510 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
511 {
512         lock_guard<mutex> lock(mu);
513         assert(index < devices.size());
514         assert(devices[index].held);
515         serialized->set_type(DeviceSpecProto::ALSA_INPUT);
516         serialized->set_index(index);
517         serialized->set_display_name(devices[index].display_name());
518         serialized->set_alsa_name(devices[index].name);
519         serialized->set_alsa_info(devices[index].info);
520         serialized->set_num_channels(devices[index].num_channels);
521         serialized->set_address(devices[index].address);
522 }
523
524 void ALSAPool::free_card(unsigned index)
525 {
526         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
527         while (!global_audio_mixer->silence_card(spec, true))
528                 ;
529
530         {
531                 lock_guard<mutex> lock(mu);
532                 if (devices[index].held) {
533                         devices[index].state = Device::State::DEAD;
534                 } else {
535                         devices[index].state = Device::State::EMPTY;
536                         inputs[index].reset();
537                 }
538                 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
539                         devices.pop_back();
540                         inputs.pop_back();
541                 }
542         }
543
544         global_audio_mixer->trigger_state_changed_callback();
545 }