]> git.sesse.net Git - nageru/blob - alsa_input.cpp
If a dead device comes back, put it into the right slot.
[nageru] / alsa_input.cpp
1 #include "alsa_input.h"
2 #include "audio_mixer.h"
3 #include "defs.h"
4
5 #include <sys/inotify.h>
6
7 #include <functional>
8 #include <unordered_map>
9
10 using namespace std;
11 using namespace std::placeholders;
12
13 namespace {
14
15 bool set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate)
16 {
17         int err;
18         err = snd_pcm_hw_params_any(pcm_handle, hw_params);
19         if (err < 0) {
20                 fprintf(stderr, "[%s] snd_pcm_hw_params_any(): %s\n", device_name, snd_strerror(err));
21                 return false;
22         }
23         err = snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
24         if (err < 0) {
25                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_access(): %s\n", device_name, snd_strerror(err));
26                 return false;
27         }
28         snd_pcm_format_mask_t *format_mask;
29         snd_pcm_format_mask_alloca(&format_mask);
30         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S16_LE);
31         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S24_LE);
32         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S32_LE);
33         err = snd_pcm_hw_params_set_format_mask(pcm_handle, hw_params, format_mask);
34         if (err < 0) {
35                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_format_mask(): %s\n", device_name, snd_strerror(err));
36                 return false;
37         }
38         err = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, sample_rate, 0);
39         if (err < 0) {
40                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_rate_near(): %s\n", device_name, snd_strerror(err));
41                 return false;
42         }
43         return true;
44 }
45
46 }  // namespace
47
48 #define RETURN_ON_ERROR(msg, expr) do {                                                    \
49         int err = (expr);                                                                  \
50         if (err < 0) {                                                                     \
51                 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err));  \
52                 if (err == -ENODEV) return CaptureEndReason::DEVICE_GONE;                  \
53                 return CaptureEndReason::OTHER_ERROR;                                      \
54         }                                                                                  \
55 } while (false)
56
57 #define RETURN_FALSE_ON_ERROR(msg, expr) do {                                              \
58         int err = (expr);                                                                  \
59         if (err < 0) {                                                                     \
60                 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err));  \
61                 return false;                                                              \
62         }                                                                                  \
63 } while (false)
64
65 #define WARN_ON_ERROR(msg, expr) do {                                                      \
66         int err = (expr);                                                                  \
67         if (err < 0) {                                                                     \
68                 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err));  \
69         }                                                                                  \
70 } while (false)
71
72 ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index)
73         : device(device),
74           sample_rate(sample_rate),
75           num_channels(num_channels),
76           audio_callback(audio_callback),
77           parent_pool(parent_pool),
78           internal_dev_index(internal_dev_index)
79 {
80 }
81
82 bool ALSAInput::open_device()
83 {
84         RETURN_FALSE_ON_ERROR("snd_pcm_open()", snd_pcm_open(&pcm_handle, device.c_str(), SND_PCM_STREAM_CAPTURE, 0));
85
86         // Set format.
87         snd_pcm_hw_params_t *hw_params;
88         snd_pcm_hw_params_alloca(&hw_params);
89         if (!set_base_params(device.c_str(), pcm_handle, hw_params, &sample_rate)) {
90                 return false;
91         }
92
93         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_channels()", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
94
95         // Fragment size of 64 samples (about 1 ms at 48 kHz; a frame at 60
96         // fps/48 kHz is 800 samples.) We ask for 64 such periods in our buffer
97         // (~85 ms buffer); more than that, and our jitter is probably so high
98         // that the resampling queue can't keep up anyway.
99         // The entire thing with periods and such is a bit mysterious to me;
100         // seemingly I can get 96 frames at a time with no problems even if
101         // the period size is 64 frames. And if I set num_periods to e.g. 1,
102         // I can't have a big buffer.
103         num_periods = 16;
104         int dir = 0;
105         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_periods_near()", snd_pcm_hw_params_set_periods_near(pcm_handle, hw_params, &num_periods, &dir));
106         period_size = 64;
107         dir = 0;
108         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_period_size_near()", snd_pcm_hw_params_set_period_size_near(pcm_handle, hw_params, &period_size, &dir));
109         buffer_frames = 64 * 64;
110         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_buffer_size_near()", snd_pcm_hw_params_set_buffer_size_near(pcm_handle, hw_params, &buffer_frames));
111         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params()", snd_pcm_hw_params(pcm_handle, hw_params));
112         //snd_pcm_hw_params_free(hw_params);
113
114         // Figure out which format the card actually chose.
115         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_current()", snd_pcm_hw_params_current(pcm_handle, hw_params));
116         snd_pcm_format_t chosen_format;
117         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_get_format()", snd_pcm_hw_params_get_format(hw_params, &chosen_format));
118
119         audio_format.num_channels = num_channels;
120         audio_format.bits_per_sample = 0;
121         switch (chosen_format) {
122         case SND_PCM_FORMAT_S16_LE:
123                 audio_format.bits_per_sample = 16;
124                 break;
125         case SND_PCM_FORMAT_S24_LE:
126                 audio_format.bits_per_sample = 24;
127                 break;
128         case SND_PCM_FORMAT_S32_LE:
129                 audio_format.bits_per_sample = 32;
130                 break;
131         default:
132                 assert(false);
133         }
134         //printf("num_periods=%u period_size=%u buffer_frames=%u sample_rate=%u bits_per_sample=%d\n",
135         //      num_periods, unsigned(period_size), unsigned(buffer_frames), sample_rate, audio_format.bits_per_sample);
136
137         buffer.reset(new uint8_t[buffer_frames * num_channels * audio_format.bits_per_sample / 8]);
138
139         snd_pcm_sw_params_t *sw_params;
140         snd_pcm_sw_params_alloca(&sw_params);
141         RETURN_FALSE_ON_ERROR("snd_pcm_sw_params_current()", snd_pcm_sw_params_current(pcm_handle, sw_params));
142         RETURN_FALSE_ON_ERROR("snd_pcm_sw_params_set_start_threshold", snd_pcm_sw_params_set_start_threshold(pcm_handle, sw_params, num_periods * period_size / 2));
143         RETURN_FALSE_ON_ERROR("snd_pcm_sw_params()", snd_pcm_sw_params(pcm_handle, sw_params));
144
145         RETURN_FALSE_ON_ERROR("snd_pcm_nonblock()", snd_pcm_nonblock(pcm_handle, 1));
146         RETURN_FALSE_ON_ERROR("snd_pcm_prepare()", snd_pcm_prepare(pcm_handle));
147         return true;
148 }
149
150 ALSAInput::~ALSAInput()
151 {
152         if (pcm_handle) {
153                 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
154         }
155 }
156
157 void ALSAInput::start_capture_thread()
158 {
159         should_quit = false;
160         capture_thread = thread(&ALSAInput::capture_thread_func, this);
161 }
162
163 void ALSAInput::stop_capture_thread()
164 {
165         should_quit = true;
166         capture_thread.join();
167 }
168
169 void ALSAInput::capture_thread_func()
170 {
171         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
172
173         // If the device hasn't been opened already, we need to do so
174         // before we can capture.
175         while (!should_quit && pcm_handle == nullptr) {
176                 if (!open_device()) {
177                         fprintf(stderr, "[%s] Waiting one second and trying again...\n",
178                                 device.c_str());
179                         sleep(1);
180                 }
181         }
182
183         if (should_quit) {
184                 // Don't call free_card(); that would be a deadlock.
185                 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
186                 pcm_handle = nullptr;
187                 return;
188         }
189
190         // Do the actual capture. (Termination condition within loop.)
191         for ( ;; ) {
192                 switch (do_capture()) {
193                 case CaptureEndReason::REQUESTED_QUIT:
194                         // Don't call free_card(); that would be a deadlock.
195                         WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
196                         pcm_handle = nullptr;
197                         return;
198                 case CaptureEndReason::DEVICE_GONE:
199                         parent_pool->free_card(internal_dev_index);
200                         WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
201                         pcm_handle = nullptr;
202                         return;
203                 case CaptureEndReason::OTHER_ERROR:
204                         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
205                         fprintf(stderr, "[%s] Sleeping one second and restarting capture...\n",
206                                 device.c_str());
207                         sleep(1);
208                         break;
209                 }
210         }
211 }
212
213 ALSAInput::CaptureEndReason ALSAInput::do_capture()
214 {
215         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
216         RETURN_ON_ERROR("snd_pcm_start()", snd_pcm_start(pcm_handle));
217         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::RUNNING);
218
219         uint64_t num_frames_output = 0;
220         while (!should_quit) {
221                 int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
222                 if (ret == 0) continue;  // Timeout.
223                 if (ret == -EPIPE) {
224                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
225                         snd_pcm_prepare(pcm_handle);
226                         snd_pcm_start(pcm_handle);
227                         continue;
228                 }
229                 RETURN_ON_ERROR("snd_pcm_wait()", ret);
230
231                 snd_pcm_sframes_t frames = snd_pcm_readi(pcm_handle, buffer.get(), buffer_frames);
232                 if (frames == -EPIPE) {
233                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
234                         snd_pcm_prepare(pcm_handle);
235                         snd_pcm_start(pcm_handle);
236                         continue;
237                 }
238                 if (frames == 0) {
239                         fprintf(stderr, "snd_pcm_readi() returned 0\n");
240                         break;
241                 }
242                 RETURN_ON_ERROR("snd_pcm_readi()", frames);
243
244                 const int64_t prev_pts = frames_to_pts(num_frames_output);
245                 const int64_t pts = frames_to_pts(num_frames_output + frames);
246                 bool success;
247                 do {
248                         if (should_quit) return CaptureEndReason::REQUESTED_QUIT;
249                         success = audio_callback(buffer.get(), frames, audio_format, pts - prev_pts);
250                 } while (!success);
251                 num_frames_output += frames;
252         }
253         return CaptureEndReason::REQUESTED_QUIT;
254 }
255
256 int64_t ALSAInput::frames_to_pts(uint64_t n) const
257 {
258         return (n * TIMEBASE) / sample_rate;
259 }
260
261 ALSAPool::~ALSAPool()
262 {
263         for (Device &device : devices) {
264                 if (device.input != nullptr) {
265                         device.input->stop_capture_thread();
266                 }
267         }
268 }
269
270 std::vector<ALSAPool::Device> ALSAPool::get_devices()
271 {
272         lock_guard<mutex> lock(mu);
273         for (Device &device : devices) {
274                 device.held = true;
275         }
276         return devices;
277 }
278
279 void ALSAPool::hold_device(unsigned index)
280 {
281         lock_guard<mutex> lock(mu);
282         assert(index < devices.size());
283         devices[index].held = true;
284 }
285
286 void ALSAPool::release_device(unsigned index)
287 {
288         lock_guard<mutex> lock(mu);
289         if (index < devices.size()) {
290                 devices[index].held = false;
291         }
292 }
293
294 void ALSAPool::enumerate_devices()
295 {
296         // Enumerate all cards.
297         for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
298                 char address[256];
299                 snprintf(address, sizeof(address), "hw:%d", card_index);
300
301                 snd_ctl_t *ctl;
302                 int err = snd_ctl_open(&ctl, address, 0);
303                 if (err < 0) {
304                         printf("%s: %s\n", address, snd_strerror(err));
305                         continue;
306                 }
307                 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
308
309                 // Enumerate all devices on this card.
310                 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
311                         probe_device_with_retry(card_index, dev_index);
312                 }
313         }
314 }
315
316 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
317 {
318         char address[256];
319         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
320
321         lock_guard<mutex> lock(add_device_mutex);
322         if (add_device_tries_left.count(address)) {
323                 // Some thread is already busy retrying this,
324                 // so just reset its count.
325                 add_device_tries_left[address] = num_retries;
326                 return;
327         }
328
329         // Try (while still holding the lock) to add the device synchronously.
330         ProbeResult result = probe_device_once(card_index, dev_index);
331         if (result == ProbeResult::SUCCESS) {
332                 return;
333         } else if (result == ProbeResult::FAILURE) {
334                 return;
335         }
336         assert(result == ProbeResult::DEFER);
337
338         // Add failed for whatever reason (probably just that the device
339         // isn't up yet. Set up a count so that nobody else starts a thread,
340         // then start it ourselves.
341         fprintf(stderr, "Trying %s again in one second...\n", address);
342         add_device_tries_left[address] = num_retries;
343         thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
344 }
345
346 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
347 {
348         char address[256];
349         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
350
351         for ( ;; ) {  // Termination condition within the loop.
352                 sleep(1);
353
354                 // See if there are any retries left.
355                 lock_guard<mutex> lock(add_device_mutex);
356                 if (!add_device_tries_left.count(address) ||
357                     add_device_tries_left[address] == 0) {
358                         add_device_tries_left.erase(address);
359                         fprintf(stderr, "Giving up probe of %s.\n", address);
360                         return;
361                 }
362
363                 // Seemingly there were. Give it a try (we still hold the mutex).
364                 ProbeResult result = probe_device_once(card_index, dev_index);
365                 if (result == ProbeResult::SUCCESS) {
366                         add_device_tries_left.erase(address);
367                         fprintf(stderr, "Probe of %s succeeded.\n", address);
368                         return;
369                 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
370                         add_device_tries_left.erase(address);
371                         fprintf(stderr, "Giving up probe of %s.\n", address);
372                         return;
373                 }
374
375                 // Failed again.
376                 assert(result == ProbeResult::DEFER);
377                 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
378                         address, add_device_tries_left[address]);
379         }
380 }
381
382 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
383 {
384         char address[256];
385         snprintf(address, sizeof(address), "hw:%d", card_index);
386         snd_ctl_t *ctl;
387         int err = snd_ctl_open(&ctl, address, 0);
388         if (err < 0) {
389                 printf("%s: %s\n", address, snd_strerror(err));
390                 return ALSAPool::ProbeResult::DEFER;
391         }
392         unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
393
394         snd_pcm_info_t *pcm_info;
395         snd_pcm_info_alloca(&pcm_info);
396         snd_pcm_info_set_device(pcm_info, dev_index);
397         snd_pcm_info_set_subdevice(pcm_info, 0);
398         snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
399         if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
400                 // Not available for capture.
401                 printf("%s: Not available for capture.\n", address);
402                 return ALSAPool::ProbeResult::DEFER;
403         }
404
405         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
406
407         unsigned num_channels = 0;
408
409         // Find all channel maps for this device, and pick out the one
410         // with the most channels.
411         snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
412         if (cmaps != nullptr) {
413                 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
414                         num_channels = max(num_channels, (*ptr)->map.channels);
415                 }
416                 snd_pcm_free_chmaps(cmaps);
417         }
418         if (num_channels == 0) {
419                 // Device had no channel maps. We need to open it to query.
420                 // TODO: Do this asynchronously.
421                 snd_pcm_t *pcm_handle;
422                 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
423                 if (err < 0) {
424                         printf("%s: %s\n", address, snd_strerror(err));
425                         return ALSAPool::ProbeResult::DEFER;
426                 }
427                 snd_pcm_hw_params_t *hw_params;
428                 snd_pcm_hw_params_alloca(&hw_params);
429                 unsigned sample_rate;
430                 if (!set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
431                         snd_pcm_close(pcm_handle);
432                         return ALSAPool::ProbeResult::DEFER;
433                 }
434                 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
435                 if (err < 0) {
436                         fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
437                                 address, snd_strerror(err));
438                         snd_pcm_close(pcm_handle);
439                         return ALSAPool::ProbeResult::DEFER;
440                 }
441                 snd_pcm_close(pcm_handle);
442         }
443
444         if (num_channels == 0) {
445                 printf("%s: No channel maps with channels\n", address);
446                 return ALSAPool::ProbeResult::FAILURE;
447         }
448
449         snd_ctl_card_info_t *card_info;
450         snd_ctl_card_info_alloca(&card_info);
451         snd_ctl_card_info(ctl, card_info);
452
453         string name = snd_ctl_card_info_get_name(card_info);
454         string info = snd_pcm_info_get_name(pcm_info);
455
456         unsigned internal_dev_index;
457         {
458                 lock_guard<mutex> lock(mu);
459                 internal_dev_index = find_free_device_index(name, info, num_channels, address);
460                 devices[internal_dev_index].address = address;
461                 devices[internal_dev_index].name = name;
462                 devices[internal_dev_index].info = info;
463                 devices[internal_dev_index].num_channels = num_channels;
464                 // Note: Purposefully does not overwrite held.
465         }
466
467         fprintf(stderr, "%s: Probed successfully.\n", address);
468
469         reset_device(internal_dev_index);  // Restarts it if it is held (ie., we just replaced a dead card).
470
471         return ALSAPool::ProbeResult::SUCCESS;
472 }
473
474 void ALSAPool::init()
475 {
476         thread(&ALSAPool::inotify_thread_func, this).detach();
477         enumerate_devices();
478 }
479
480 void ALSAPool::inotify_thread_func()
481 {
482         int inotify_fd = inotify_init();
483         if (inotify_fd == -1) {
484                 perror("inotify_init()");
485                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
486                 return;
487         }
488
489         int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
490         if (watch_fd == -1) {
491                 perror("inotify_add_watch()");
492                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
493                 close(inotify_fd);
494                 return;
495         }
496
497         int size = sizeof(inotify_event) + NAME_MAX + 1;
498         unique_ptr<char[]> buf(new char[size]);
499         for ( ;; ) {
500                 int ret = read(inotify_fd, buf.get(), size);
501                 if (ret < int(sizeof(inotify_event))) {
502                         fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
503                                 int(ret));
504                         close(watch_fd);
505                         close(inotify_fd);
506                         return;
507                 }
508
509                 for (int i = 0; i < ret; ) {
510                         const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
511                         i += sizeof(inotify_event) + event->len;
512
513                         if (event->mask & IN_Q_OVERFLOW) {
514                                 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
515                                 continue;
516                         }
517                         unsigned card, device;
518                         char type;
519                         if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
520                                 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
521                                         printf("Deleted capture device: Card %u, device %u\n", card, device);
522                                         // TODO: Unplug.
523                                 }
524                                 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
525                                         printf("Adding capture device: Card %u, device %u\n", card, device);
526                                         probe_device_with_retry(card, device);
527                                 }
528                         }
529                 }
530         }
531 }
532
533 void ALSAPool::reset_device(unsigned index)
534 {
535         lock_guard<mutex> lock(mu);
536         Device *device = &devices[index];
537         if (inputs[index] != nullptr) {
538                 inputs[index]->stop_capture_thread();
539         }
540         if (!device->held) {
541                 inputs[index].reset();
542         } else {
543                 // TODO: Put on a background thread instead of locking?
544                 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
545                 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
546                 inputs[index]->start_capture_thread();
547         }
548         device->input = inputs[index].get();
549 }
550
551 unsigned ALSAPool::get_capture_frequency(unsigned index)
552 {
553         lock_guard<mutex> lock(mu);
554         assert(devices[index].held);
555         if (devices[index].input)
556                 return devices[index].input->get_sample_rate();
557         else
558                 return OUTPUT_FREQUENCY;
559 }
560
561 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
562 {
563         lock_guard<mutex> lock(mu);
564         assert(devices[index].held);
565         return devices[index].state;
566 }
567
568 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
569 {
570         {
571                 lock_guard<mutex> lock(mu);
572                 devices[index].state = state;
573         }
574
575         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
576         bool silence = (state != ALSAPool::Device::State::RUNNING);
577         while (!global_audio_mixer->silence_card(spec, silence))
578                 ;
579 }
580
581 unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
582 {
583         // First try to find an exact match on a dead card.
584         for (unsigned i = 0; i < devices.size(); ++i) {
585                 if (devices[i].state == Device::State::DEAD &&
586                     devices[i].address == address &&
587                     devices[i].name == name &&
588                     devices[i].info == info &&
589                     devices[i].num_channels == num_channels) {
590                         devices[i].state = Device::State::READY;
591                         return i;
592                 }
593         }
594
595         // Then try to find a match on everything but the address
596         // (probably that devices were plugged back in a different order).
597         // If we have two cards that are equal, this might get them mixed up,
598         // but we don't have anything better.
599         for (unsigned i = 0; i < devices.size(); ++i) {
600                 if (devices[i].state == Device::State::DEAD &&
601                     devices[i].name == name &&
602                     devices[i].info == info &&
603                     devices[i].num_channels == num_channels) {
604                         devices[i].state = Device::State::READY;
605                         return i;
606                 }
607         }
608
609         // OK, so we didn't find a match; see if there are any empty slots.
610         for (unsigned i = 0; i < devices.size(); ++i) {
611                 if (devices[i].state == Device::State::EMPTY) {
612                         devices[i].state = Device::State::READY;
613                         devices[i].held = false;
614                         return i;
615                 }
616         }
617
618         // Failing that, we just insert the new device at the end.
619         Device new_dev;
620         new_dev.state = Device::State::READY;
621         new_dev.held = false;
622         devices.push_back(new_dev);
623         inputs.emplace_back(nullptr);
624         return devices.size() - 1;
625 }
626
627 void ALSAPool::free_card(unsigned index)
628 {
629         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
630         while (!global_audio_mixer->silence_card(spec, true))
631                 ;
632
633         lock_guard<mutex> lock(mu);
634         if (devices[index].held) {
635                 devices[index].state = Device::State::DEAD;
636         } else {
637                 devices[index].state = Device::State::EMPTY;
638                 inputs[index].reset();
639         }
640         while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
641                 devices.pop_back();
642                 inputs.pop_back();
643         }
644 }