]> git.sesse.net Git - nageru/blob - alsa_input.cpp
When an ALSA input goes away, replace it by silence.
[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         WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
153 }
154
155 void ALSAInput::start_capture_thread()
156 {
157         should_quit = false;
158         capture_thread = thread(&ALSAInput::capture_thread_func, this);
159 }
160
161 void ALSAInput::stop_capture_thread()
162 {
163         should_quit = true;
164         capture_thread.join();
165 }
166
167 void ALSAInput::capture_thread_func()
168 {
169         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
170
171         // If the device hasn't been opened already, we need to do so
172         // before we can capture.
173         while (!should_quit && pcm_handle == nullptr) {
174                 if (!open_device()) {
175                         fprintf(stderr, "[%s] Waiting one second and trying again...\n",
176                                 device.c_str());
177                         sleep(1);
178                 }
179         }
180
181         if (should_quit) {
182                 // Don't call free_card(); that would be a deadlock.
183                 return;
184         }
185
186         // Do the actual capture. (Termination condition within loop.)
187         for ( ;; ) {
188                 switch (do_capture()) {
189                 case CaptureEndReason::REQUESTED_QUIT:
190                         // Don't call free_card(); that would be a deadlock.
191                         return;
192                 case CaptureEndReason::DEVICE_GONE:
193                         parent_pool->free_card(internal_dev_index);
194                         return;
195                 case CaptureEndReason::OTHER_ERROR:
196                         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
197                         fprintf(stderr, "[%s] Sleeping one second and restarting capture...\n",
198                                 device.c_str());
199                         sleep(1);
200                         break;
201                 }
202         }
203 }
204
205 ALSAInput::CaptureEndReason ALSAInput::do_capture()
206 {
207         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
208         RETURN_ON_ERROR("snd_pcm_start()", snd_pcm_start(pcm_handle));
209         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::RUNNING);
210
211         uint64_t num_frames_output = 0;
212         while (!should_quit) {
213                 int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
214                 if (ret == 0) continue;  // Timeout.
215                 if (ret == -EPIPE) {
216                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
217                         snd_pcm_prepare(pcm_handle);
218                         snd_pcm_start(pcm_handle);
219                         continue;
220                 }
221                 RETURN_ON_ERROR("snd_pcm_wait()", ret);
222
223                 snd_pcm_sframes_t frames = snd_pcm_readi(pcm_handle, buffer.get(), buffer_frames);
224                 if (frames == -EPIPE) {
225                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
226                         snd_pcm_prepare(pcm_handle);
227                         snd_pcm_start(pcm_handle);
228                         continue;
229                 }
230                 if (frames == 0) {
231                         fprintf(stderr, "snd_pcm_readi() returned 0\n");
232                         break;
233                 }
234                 RETURN_ON_ERROR("snd_pcm_readi()", frames);
235
236                 const int64_t prev_pts = frames_to_pts(num_frames_output);
237                 const int64_t pts = frames_to_pts(num_frames_output + frames);
238                 bool success;
239                 do {
240                         if (should_quit) return CaptureEndReason::REQUESTED_QUIT;
241                         success = audio_callback(buffer.get(), frames, audio_format, pts - prev_pts);
242                 } while (!success);
243                 num_frames_output += frames;
244         }
245         return CaptureEndReason::REQUESTED_QUIT;
246 }
247
248 int64_t ALSAInput::frames_to_pts(uint64_t n) const
249 {
250         return (n * TIMEBASE) / sample_rate;
251 }
252
253 ALSAPool::~ALSAPool()
254 {
255         for (Device &device : devices) {
256                 if (device.input != nullptr) {
257                         device.input->stop_capture_thread();
258                 }
259         }
260 }
261
262 std::vector<ALSAPool::Device> ALSAPool::get_devices()
263 {
264         lock_guard<mutex> lock(mu);
265         for (Device &device : devices) {
266                 device.held = true;
267         }
268         return devices;
269 }
270
271 void ALSAPool::hold_device(unsigned index)
272 {
273         lock_guard<mutex> lock(mu);
274         assert(index < devices.size());
275         devices[index].held = true;
276 }
277
278 void ALSAPool::release_device(unsigned index)
279 {
280         lock_guard<mutex> lock(mu);
281         if (index < devices.size()) {
282                 devices[index].held = false;
283         }
284 }
285
286 void ALSAPool::enumerate_devices()
287 {
288         // Enumerate all cards.
289         for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
290                 char address[256];
291                 snprintf(address, sizeof(address), "hw:%d", card_index);
292
293                 snd_ctl_t *ctl;
294                 int err = snd_ctl_open(&ctl, address, 0);
295                 if (err < 0) {
296                         printf("%s: %s\n", address, snd_strerror(err));
297                         continue;
298                 }
299                 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
300
301                 // Enumerate all devices on this card.
302                 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
303                         probe_device_with_retry(card_index, dev_index);
304                 }
305         }
306 }
307
308 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
309 {
310         char address[256];
311         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
312
313         lock_guard<mutex> lock(add_device_mutex);
314         if (add_device_tries_left.count(address)) {
315                 // Some thread is already busy retrying this,
316                 // so just reset its count.
317                 add_device_tries_left[address] = num_retries;
318                 return;
319         }
320
321         // Try (while still holding the lock) to add the device synchronously.
322         ProbeResult result = probe_device_once(card_index, dev_index);
323         if (result == ProbeResult::SUCCESS) {
324                 return;
325         } else if (result == ProbeResult::FAILURE) {
326                 return;
327         }
328         assert(result == ProbeResult::DEFER);
329
330         // Add failed for whatever reason (probably just that the device
331         // isn't up yet. Set up a count so that nobody else starts a thread,
332         // then start it ourselves.
333         fprintf(stderr, "Trying %s again in one second...\n", address);
334         add_device_tries_left[address] = num_retries;
335         thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
336 }
337
338 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
339 {
340         char address[256];
341         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
342
343         for ( ;; ) {  // Termination condition within the loop.
344                 sleep(1);
345
346                 // See if there are any retries left.
347                 lock_guard<mutex> lock(add_device_mutex);
348                 if (!add_device_tries_left.count(address) ||
349                     add_device_tries_left[address] == 0) {
350                         add_device_tries_left.erase(address);
351                         fprintf(stderr, "Giving up probe of %s.\n", address);
352                         return;
353                 }
354
355                 // Seemingly there were. Give it a try (we still hold the mutex).
356                 ProbeResult result = probe_device_once(card_index, dev_index);
357                 if (result == ProbeResult::SUCCESS) {
358                         add_device_tries_left.erase(address);
359                         fprintf(stderr, "Probe of %s succeeded.\n", address);
360                         return;
361                 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
362                         add_device_tries_left.erase(address);
363                         fprintf(stderr, "Giving up probe of %s.\n", address);
364                         return;
365                 }
366
367                 // Failed again.
368                 assert(result == ProbeResult::DEFER);
369                 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
370                         address, add_device_tries_left[address]);
371         }
372 }
373
374 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
375 {
376         char address[256];
377         snprintf(address, sizeof(address), "hw:%d", card_index);
378         snd_ctl_t *ctl;
379         int err = snd_ctl_open(&ctl, address, 0);
380         if (err < 0) {
381                 printf("%s: %s\n", address, snd_strerror(err));
382                 return ALSAPool::ProbeResult::DEFER;
383         }
384         unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
385
386         snd_pcm_info_t *pcm_info;
387         snd_pcm_info_alloca(&pcm_info);
388         snd_pcm_info_set_device(pcm_info, dev_index);
389         snd_pcm_info_set_subdevice(pcm_info, 0);
390         snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
391         if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
392                 // Not available for capture.
393                 printf("%s: Not available for capture.\n", address);
394                 return ALSAPool::ProbeResult::DEFER;
395         }
396
397         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
398
399         unsigned num_channels = 0;
400
401         // Find all channel maps for this device, and pick out the one
402         // with the most channels.
403         snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
404         if (cmaps != nullptr) {
405                 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
406                         num_channels = max(num_channels, (*ptr)->map.channels);
407                 }
408                 snd_pcm_free_chmaps(cmaps);
409         }
410         if (num_channels == 0) {
411                 // Device had no channel maps. We need to open it to query.
412                 // TODO: Do this asynchronously.
413                 snd_pcm_t *pcm_handle;
414                 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
415                 if (err < 0) {
416                         printf("%s: %s\n", address, snd_strerror(err));
417                         return ALSAPool::ProbeResult::DEFER;
418                 }
419                 snd_pcm_hw_params_t *hw_params;
420                 snd_pcm_hw_params_alloca(&hw_params);
421                 unsigned sample_rate;
422                 if (!set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
423                         snd_pcm_close(pcm_handle);
424                         return ALSAPool::ProbeResult::DEFER;
425                 }
426                 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
427                 if (err < 0) {
428                         fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
429                                 address, snd_strerror(err));
430                         snd_pcm_close(pcm_handle);
431                         return ALSAPool::ProbeResult::DEFER;
432                 }
433                 snd_pcm_close(pcm_handle);
434         }
435
436         if (num_channels == 0) {
437                 printf("%s: No channel maps with channels\n", address);
438                 return ALSAPool::ProbeResult::FAILURE;
439         }
440
441         snd_ctl_card_info_t *card_info;
442         snd_ctl_card_info_alloca(&card_info);
443         snd_ctl_card_info(ctl, card_info);
444
445         lock_guard<mutex> lock(mu);
446         unsigned internal_dev_index = find_free_device_index();
447         devices[internal_dev_index].address = address;
448         devices[internal_dev_index].name = snd_ctl_card_info_get_name(card_info);
449         devices[internal_dev_index].info = snd_pcm_info_get_name(pcm_info);
450         devices[internal_dev_index].num_channels = num_channels;
451         devices[internal_dev_index].state = Device::State::READY;
452
453         fprintf(stderr, "%s: Probed successfully.\n", address);
454
455         return ALSAPool::ProbeResult::SUCCESS;
456 }
457
458 void ALSAPool::init()
459 {
460         thread(&ALSAPool::inotify_thread_func, this).detach();
461         enumerate_devices();
462 }
463
464 void ALSAPool::inotify_thread_func()
465 {
466         int inotify_fd = inotify_init();
467         if (inotify_fd == -1) {
468                 perror("inotify_init()");
469                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
470                 return;
471         }
472
473         int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
474         if (watch_fd == -1) {
475                 perror("inotify_add_watch()");
476                 fprintf(stderr, "No hotplug of ALSA devices available.\n");
477                 close(inotify_fd);
478                 return;
479         }
480
481         int size = sizeof(inotify_event) + NAME_MAX + 1;
482         unique_ptr<char[]> buf(new char[size]);
483         for ( ;; ) {
484                 int ret = read(inotify_fd, buf.get(), size);
485                 if (ret < int(sizeof(inotify_event))) {
486                         fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
487                                 int(ret));
488                         close(watch_fd);
489                         close(inotify_fd);
490                         return;
491                 }
492
493                 for (int i = 0; i < ret; ) {
494                         const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
495                         i += sizeof(inotify_event) + event->len;
496
497                         if (event->mask & IN_Q_OVERFLOW) {
498                                 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
499                                 continue;
500                         }
501                         unsigned card, device;
502                         char type;
503                         if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
504                                 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
505                                         printf("Deleted capture device: Card %u, device %u\n", card, device);
506                                         // TODO: Unplug.
507                                 }
508                                 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
509                                         printf("Adding capture device: Card %u, device %u\n", card, device);
510                                         probe_device_with_retry(card, device);
511                                 }
512                         }
513                 }
514         }
515 }
516
517 void ALSAPool::reset_device(unsigned index)
518 {
519         lock_guard<mutex> lock(mu);
520         Device *device = &devices[index];
521         if (inputs[index] != nullptr) {
522                 inputs[index]->stop_capture_thread();
523         }
524         if (!device->held) {
525                 inputs[index].reset();
526         } else {
527                 // TODO: Put on a background thread instead of locking?
528                 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
529                 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
530                 inputs[index]->start_capture_thread();
531         }
532         device->input = inputs[index].get();
533 }
534
535 unsigned ALSAPool::get_capture_frequency(unsigned index)
536 {
537         lock_guard<mutex> lock(mu);
538         assert(devices[index].held);
539         if (devices[index].input)
540                 return devices[index].input->get_sample_rate();
541         else
542                 return OUTPUT_FREQUENCY;
543 }
544
545 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
546 {
547         lock_guard<mutex> lock(mu);
548         assert(devices[index].held);
549         return devices[index].state;
550 }
551
552 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
553 {
554         {
555                 lock_guard<mutex> lock(mu);
556                 devices[index].state = state;
557         }
558
559         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
560         bool silence = (state != ALSAPool::Device::State::RUNNING);
561         while (!global_audio_mixer->silence_card(spec, silence))
562                 ;
563 }
564
565 unsigned ALSAPool::find_free_device_index()
566 {
567         for (unsigned i = 0; i < devices.size(); ++i) {
568                 if (devices[i].state == Device::State::EMPTY) {
569                         devices[i].state = Device::State::READY;
570                         return i;
571                 }
572         }
573         Device new_dev;
574         new_dev.state = Device::State::READY;
575         devices.push_back(new_dev);
576         inputs.emplace_back(nullptr);
577         return devices.size() - 1;
578 }
579
580 void ALSAPool::free_card(unsigned index)
581 {
582         DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
583         while (!global_audio_mixer->silence_card(spec, true))
584                 ;
585
586         lock_guard<mutex> lock(mu);
587         if (devices[index].held) {
588                 devices[index].state = Device::State::DEAD;
589         } else {
590                 devices[index].state = Device::State::EMPTY;
591                 inputs[index].reset();
592         }
593         while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
594                 devices.pop_back();
595                 inputs.pop_back();
596         }
597 }