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