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