]> git.sesse.net Git - nageru/blob - nageru/alsa_pool.cpp
Move texture uploading out of a lambda.
[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         fprintf(stderr, "%s: Probed successfully.\n", address);
270
271         reset_device(internal_dev_index);  // Restarts it if it is held (ie., we just replaced a dead card).
272
273         DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
274         global_audio_mixer->set_display_name(spec, display_name);
275         global_audio_mixer->trigger_state_changed_callback();
276
277         return ALSAPool::ProbeResult::SUCCESS;
278 }
279
280 void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
281 {
282         char address[256];
283         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
284         for (unsigned i = 0; i < devices.size(); ++i) {
285                 if (devices[i].state != Device::State::EMPTY &&
286                     devices[i].state != Device::State::DEAD &&
287                     devices[i].address == address) {
288                         free_card(i);
289                 }
290         }
291 }
292
293 void ALSAPool::init()
294 {
295         inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
296         enumerate_devices();
297 }
298
299 void ALSAPool::inotify_thread_func()
300 {
301         pthread_setname_np(pthread_self(), "ALSA_Hotplug");
302
303         int inotify_fd = inotify_init();
304         if (inotify_fd == -1) {
305                 perror("inotify_init()");
306                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
307                 return;
308         }
309
310         int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
311         if (watch_fd == -1) {
312                 perror("inotify_add_watch()");
313                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
314                 close(inotify_fd);
315                 return;
316         }
317
318         int size = sizeof(inotify_event) + NAME_MAX + 1;
319         unique_ptr<char[]> buf(new char[size]);
320         while (!should_quit) {
321                 pollfd fds[2];
322                 fds[0].fd = inotify_fd;
323                 fds[0].events = POLLIN;
324                 fds[0].revents = 0;
325                 fds[1].fd = should_quit_fd;
326                 fds[1].events = POLLIN;
327                 fds[1].revents = 0;
328
329                 int ret = poll(fds, 2, -1);
330                 if (ret == -1) {
331                         if (errno == EINTR) {
332                                 continue;
333                         } else {
334                                 perror("poll(inotify_fd)");
335                                 return;
336                         }
337                 }
338                 if (ret == 0) {
339                         continue;
340                 }
341
342                 if (fds[1].revents) break;  // should_quit_fd asserted.
343
344                 ret = read(inotify_fd, buf.get(), size);
345                 if (ret == -1) {
346                         if (errno == EINTR) {
347                                 continue;
348                         } else {
349                                 perror("read(inotify_fd)");
350                                 close(watch_fd);
351                                 close(inotify_fd);
352                                 return;
353                         }
354                 }
355                 if (ret < int(sizeof(inotify_event))) {
356                         fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
357                                 int(ret));
358                         close(watch_fd);
359                         close(inotify_fd);
360                         return;
361                 }
362
363                 for (int i = 0; i < ret; ) {
364                         const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
365                         i += sizeof(inotify_event) + event->len;
366
367                         if (event->mask & IN_Q_OVERFLOW) {
368                                 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
369                                 continue;
370                         }
371                         unsigned card, device;
372                         char type;
373                         if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
374                                 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
375                                         printf("Deleted capture device: Card %u, device %u\n", card, device);
376                                         unplug_device(card, device);
377                                 }
378                                 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
379                                         printf("Adding capture device: Card %u, device %u\n", card, device);
380                                         probe_device_with_retry(card, device);
381                                 }
382                         }
383                 }
384         }
385         close(watch_fd);
386         close(inotify_fd);
387         close(should_quit_fd);
388 }
389
390 void ALSAPool::reset_device(unsigned index)
391 {
392         lock_guard<mutex> lock(mu);
393         Device *device = &devices[index];
394         if (device->state == Device::State::DEAD) {
395                 // Not running, and should not be started.
396                 return;
397         }
398         if (inputs[index] != nullptr) {
399                 inputs[index]->stop_capture_thread();
400         }
401         if (!device->held) {
402                 inputs[index].reset();
403         } else {
404                 // TODO: Put on a background thread instead of locking?
405                 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
406                 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
407                 inputs[index]->start_capture_thread();
408         }
409         device->input = inputs[index].get();
410 }
411
412 unsigned ALSAPool::get_capture_frequency(unsigned index)
413 {
414         lock_guard<mutex> lock(mu);
415         assert(devices[index].held);
416         if (devices[index].input)
417                 return devices[index].input->get_sample_rate();
418         else
419                 return OUTPUT_FREQUENCY;
420 }
421
422 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
423 {
424         lock_guard<mutex> lock(mu);
425         assert(devices[index].held);
426         return devices[index].state;
427 }
428
429 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
430 {
431         {
432                 lock_guard<mutex> lock(mu);
433                 devices[index].state = state;
434         }
435
436         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
437         bool silence = (state != ALSAPool::Device::State::RUNNING);
438         while (!global_audio_mixer->silence_card(spec, silence))
439                 ;
440         global_audio_mixer->trigger_state_changed_callback();
441 }
442
443 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
444 {
445         // First try to find an exact match on a dead card.
446         for (unsigned i = 0; i < devices.size(); ++i) {
447                 if (devices[i].state == Device::State::DEAD &&
448                     devices[i].address == address &&
449                     devices[i].name == name &&
450                     devices[i].info == info &&
451                     devices[i].num_channels == num_channels) {
452                         devices[i].state = Device::State::READY;
453                         return i;
454                 }
455         }
456
457         // Then try to find a match on everything but the address
458         // (probably that devices were plugged back in a different order).
459         // If we have two cards that are equal, this might get them mixed up,
460         // but we don't have anything better.
461         for (unsigned i = 0; i < devices.size(); ++i) {
462                 if (devices[i].state == Device::State::DEAD &&
463                     devices[i].name == name &&
464                     devices[i].info == info &&
465                     devices[i].num_channels == num_channels) {
466                         devices[i].state = Device::State::READY;
467                         return i;
468                 }
469         }
470
471         // OK, so we didn't find a match; see if there are any empty slots.
472         for (unsigned i = 0; i < devices.size(); ++i) {
473                 if (devices[i].state == Device::State::EMPTY) {
474                         devices[i].state = Device::State::READY;
475                         devices[i].held = false;
476                         return i;
477                 }
478         }
479
480         // Failing that, we just insert the new device at the end.
481         Device new_dev;
482         new_dev.state = Device::State::READY;
483         new_dev.held = false;
484         devices.push_back(new_dev);
485         inputs.emplace_back(nullptr);
486         return devices.size() - 1;
487 }
488
489 unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
490 {
491         lock_guard<mutex> lock(mu);
492
493         // See if there are any empty slots. If not, insert one at the end.
494         vector<Device>::iterator free_device =
495                 find_if(devices.begin(), devices.end(),
496                         [](const Device &device) { return device.state == Device::State::EMPTY; });
497         if (free_device == devices.end()) {
498                 devices.push_back(Device());
499                 inputs.emplace_back(nullptr);
500                 free_device = devices.end() - 1;
501         }
502
503         free_device->state = Device::State::DEAD;
504         free_device->name = name;
505         free_device->info = info;
506         free_device->num_channels = num_channels;
507         free_device->held = true;
508
509         return distance(devices.begin(), free_device);
510 }
511
512 void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
513 {
514         lock_guard<mutex> lock(mu);
515         assert(index < devices.size());
516         assert(devices[index].held);
517         serialized->set_type(DeviceSpecProto::ALSA_INPUT);
518         serialized->set_index(index);
519         serialized->set_display_name(devices[index].display_name());
520         serialized->set_alsa_name(devices[index].name);
521         serialized->set_alsa_info(devices[index].info);
522         serialized->set_num_channels(devices[index].num_channels);
523         serialized->set_address(devices[index].address);
524 }
525
526 void ALSAPool::free_card(unsigned index)
527 {
528         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
529         while (!global_audio_mixer->silence_card(spec, true))
530                 ;
531
532         {
533                 lock_guard<mutex> lock(mu);
534                 if (devices[index].held) {
535                         devices[index].state = Device::State::DEAD;
536                 } else {
537                         devices[index].state = Device::State::EMPTY;
538                         inputs[index].reset();
539                 }
540                 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
541                         devices.pop_back();
542                         inputs.pop_back();
543                 }
544         }
545
546         global_audio_mixer->trigger_state_changed_callback();
547 }