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