1 #include "alsa_input.h"
2 #include "audio_mixer.h"
5 #include <sys/inotify.h>
8 #include <unordered_map>
11 using namespace std::placeholders;
15 bool set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate)
18 err = snd_pcm_hw_params_any(pcm_handle, hw_params);
20 fprintf(stderr, "[%s] snd_pcm_hw_params_any(): %s\n", device_name, snd_strerror(err));
23 err = snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
25 fprintf(stderr, "[%s] snd_pcm_hw_params_set_access(): %s\n", device_name, snd_strerror(err));
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);
35 fprintf(stderr, "[%s] snd_pcm_hw_params_set_format_mask(): %s\n", device_name, snd_strerror(err));
38 err = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, sample_rate, 0);
40 fprintf(stderr, "[%s] snd_pcm_hw_params_set_rate_near(): %s\n", device_name, snd_strerror(err));
48 #define RETURN_ON_ERROR(msg, expr) do { \
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; \
57 #define RETURN_FALSE_ON_ERROR(msg, expr) do { \
60 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err)); \
65 #define WARN_ON_ERROR(msg, expr) do { \
68 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err)); \
72 ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index)
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)
82 bool ALSAInput::open_device()
84 RETURN_FALSE_ON_ERROR("snd_pcm_open()", snd_pcm_open(&pcm_handle, device.c_str(), SND_PCM_STREAM_CAPTURE, 0));
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)) {
93 RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_channels()", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
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.
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));
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);
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));
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;
125 case SND_PCM_FORMAT_S24_LE:
126 audio_format.bits_per_sample = 24;
128 case SND_PCM_FORMAT_S32_LE:
129 audio_format.bits_per_sample = 32;
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);
137 buffer.reset(new uint8_t[buffer_frames * num_channels * audio_format.bits_per_sample / 8]);
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));
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));
150 ALSAInput::~ALSAInput()
152 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
155 void ALSAInput::start_capture_thread()
158 capture_thread = thread(&ALSAInput::capture_thread_func, this);
161 void ALSAInput::stop_capture_thread()
164 capture_thread.join();
167 void ALSAInput::capture_thread_func()
169 // If the device hasn't been opened already, we need to do so
170 // before we can capture.
171 while (!should_quit && pcm_handle == nullptr) {
172 if (!open_device()) {
173 fprintf(stderr, "[%s] Waiting one second and trying again...\n",
180 // Don't call free_card(); that would be a deadlock.
184 // Do the actual capture. (Termination condition within loop.)
186 switch (do_capture()) {
187 case CaptureEndReason::REQUESTED_QUIT:
188 // Don't call free_card(); that would be a deadlock.
190 case CaptureEndReason::DEVICE_GONE:
191 parent_pool->free_card(internal_dev_index);
193 case CaptureEndReason::OTHER_ERROR:
194 parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
195 fprintf(stderr, "[%s] Sleeping one second and restarting capture...\n",
203 ALSAInput::CaptureEndReason ALSAInput::do_capture()
205 parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
206 RETURN_ON_ERROR("snd_pcm_start()", snd_pcm_start(pcm_handle));
207 parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::RUNNING);
209 uint64_t num_frames_output = 0;
210 while (!should_quit) {
211 int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
212 if (ret == 0) continue; // Timeout.
214 fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
215 snd_pcm_prepare(pcm_handle);
216 snd_pcm_start(pcm_handle);
219 RETURN_ON_ERROR("snd_pcm_wait()", ret);
221 snd_pcm_sframes_t frames = snd_pcm_readi(pcm_handle, buffer.get(), buffer_frames);
222 if (frames == -EPIPE) {
223 fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
224 snd_pcm_prepare(pcm_handle);
225 snd_pcm_start(pcm_handle);
229 fprintf(stderr, "snd_pcm_readi() returned 0\n");
232 RETURN_ON_ERROR("snd_pcm_readi()", frames);
234 const int64_t prev_pts = frames_to_pts(num_frames_output);
235 const int64_t pts = frames_to_pts(num_frames_output + frames);
238 if (should_quit) return CaptureEndReason::REQUESTED_QUIT;
239 success = audio_callback(buffer.get(), frames, audio_format, pts - prev_pts);
241 num_frames_output += frames;
243 return CaptureEndReason::REQUESTED_QUIT;
246 int64_t ALSAInput::frames_to_pts(uint64_t n) const
248 return (n * TIMEBASE) / sample_rate;
251 ALSAPool::~ALSAPool()
253 for (Device &device : devices) {
254 if (device.input != nullptr) {
255 device.input->stop_capture_thread();
260 std::vector<ALSAPool::Device> ALSAPool::get_devices()
262 lock_guard<mutex> lock(mu);
263 for (Device &device : devices) {
269 void ALSAPool::hold_device(unsigned index)
271 lock_guard<mutex> lock(mu);
272 assert(index < devices.size());
273 devices[index].held = true;
276 void ALSAPool::release_device(unsigned index)
278 lock_guard<mutex> lock(mu);
279 if (index < devices.size()) {
280 devices[index].held = false;
284 void ALSAPool::enumerate_devices()
286 // Enumerate all cards.
287 for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
289 snprintf(address, sizeof(address), "hw:%d", card_index);
292 int err = snd_ctl_open(&ctl, address, 0);
294 printf("%s: %s\n", address, snd_strerror(err));
297 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
299 // Enumerate all devices on this card.
300 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
301 probe_device_with_retry(card_index, dev_index);
306 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
309 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
311 lock_guard<mutex> lock(add_device_mutex);
312 if (add_device_tries_left.count(address)) {
313 // Some thread is already busy retrying this,
314 // so just reset its count.
315 add_device_tries_left[address] = num_retries;
319 // Try (while still holding the lock) to add the device synchronously.
320 ProbeResult result = probe_device_once(card_index, dev_index);
321 if (result == ProbeResult::SUCCESS) {
323 } else if (result == ProbeResult::FAILURE) {
326 assert(result == ProbeResult::DEFER);
328 // Add failed for whatever reason (probably just that the device
329 // isn't up yet. Set up a count so that nobody else starts a thread,
330 // then start it ourselves.
331 fprintf(stderr, "Trying %s again in one second...\n", address);
332 add_device_tries_left[address] = num_retries;
333 thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
336 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
339 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
341 for ( ;; ) { // Termination condition within the loop.
344 // See if there are any retries left.
345 lock_guard<mutex> lock(add_device_mutex);
346 if (!add_device_tries_left.count(address) ||
347 add_device_tries_left[address] == 0) {
348 add_device_tries_left.erase(address);
349 fprintf(stderr, "Giving up probe of %s.\n", address);
353 // Seemingly there were. Give it a try (we still hold the mutex).
354 ProbeResult result = probe_device_once(card_index, dev_index);
355 if (result == ProbeResult::SUCCESS) {
356 add_device_tries_left.erase(address);
357 fprintf(stderr, "Probe of %s succeeded.\n", address);
359 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
360 add_device_tries_left.erase(address);
361 fprintf(stderr, "Giving up probe of %s.\n", address);
366 assert(result == ProbeResult::DEFER);
367 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
368 address, add_device_tries_left[address]);
372 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
375 snprintf(address, sizeof(address), "hw:%d", card_index);
377 int err = snd_ctl_open(&ctl, address, 0);
379 printf("%s: %s\n", address, snd_strerror(err));
380 return ALSAPool::ProbeResult::DEFER;
382 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
384 snd_pcm_info_t *pcm_info;
385 snd_pcm_info_alloca(&pcm_info);
386 snd_pcm_info_set_device(pcm_info, dev_index);
387 snd_pcm_info_set_subdevice(pcm_info, 0);
388 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
389 if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
390 // Not available for capture.
391 printf("%s: Not available for capture.\n", address);
392 return ALSAPool::ProbeResult::DEFER;
395 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
397 unsigned num_channels = 0;
399 // Find all channel maps for this device, and pick out the one
400 // with the most channels.
401 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
402 if (cmaps != nullptr) {
403 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
404 num_channels = max(num_channels, (*ptr)->map.channels);
406 snd_pcm_free_chmaps(cmaps);
408 if (num_channels == 0) {
409 // Device had no channel maps. We need to open it to query.
410 // TODO: Do this asynchronously.
411 snd_pcm_t *pcm_handle;
412 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
414 printf("%s: %s\n", address, snd_strerror(err));
415 return ALSAPool::ProbeResult::DEFER;
417 snd_pcm_hw_params_t *hw_params;
418 snd_pcm_hw_params_alloca(&hw_params);
419 unsigned sample_rate;
420 if (!set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
421 snd_pcm_close(pcm_handle);
422 return ALSAPool::ProbeResult::DEFER;
424 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
426 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
427 address, snd_strerror(err));
428 snd_pcm_close(pcm_handle);
429 return ALSAPool::ProbeResult::DEFER;
431 snd_pcm_close(pcm_handle);
434 if (num_channels == 0) {
435 printf("%s: No channel maps with channels\n", address);
436 return ALSAPool::ProbeResult::FAILURE;
439 snd_ctl_card_info_t *card_info;
440 snd_ctl_card_info_alloca(&card_info);
441 snd_ctl_card_info(ctl, card_info);
443 lock_guard<mutex> lock(mu);
444 unsigned internal_dev_index = find_free_device_index();
445 devices[internal_dev_index].address = address;
446 devices[internal_dev_index].name = snd_ctl_card_info_get_name(card_info);
447 devices[internal_dev_index].info = snd_pcm_info_get_name(pcm_info);
448 devices[internal_dev_index].num_channels = num_channels;
449 devices[internal_dev_index].state = Device::State::READY;
451 fprintf(stderr, "%s: Probed successfully.\n", address);
453 return ALSAPool::ProbeResult::SUCCESS;
456 void ALSAPool::init()
458 thread(&ALSAPool::inotify_thread_func, this).detach();
462 void ALSAPool::inotify_thread_func()
464 int inotify_fd = inotify_init();
465 if (inotify_fd == -1) {
466 perror("inotify_init()");
467 fprintf(stderr, "No hotplug of ALSA devices available.\n");
471 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
472 if (watch_fd == -1) {
473 perror("inotify_add_watch()");
474 fprintf(stderr, "No hotplug of ALSA devices available.\n");
479 int size = sizeof(inotify_event) + NAME_MAX + 1;
480 unique_ptr<char[]> buf(new char[size]);
482 int ret = read(inotify_fd, buf.get(), size);
483 if (ret < int(sizeof(inotify_event))) {
484 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
491 for (int i = 0; i < ret; ) {
492 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
493 i += sizeof(inotify_event) + event->len;
495 if (event->mask & IN_Q_OVERFLOW) {
496 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
499 unsigned card, device;
501 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
502 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
503 printf("Deleted capture device: Card %u, device %u\n", card, device);
506 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
507 printf("Adding capture device: Card %u, device %u\n", card, device);
508 probe_device_with_retry(card, device);
515 void ALSAPool::reset_device(unsigned index)
517 lock_guard<mutex> lock(mu);
518 Device *device = &devices[index];
519 if (inputs[index] != nullptr) {
520 inputs[index]->stop_capture_thread();
523 inputs[index].reset();
525 // TODO: Put on a background thread instead of locking?
526 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
527 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
528 inputs[index]->start_capture_thread();
530 device->input = inputs[index].get();
533 unsigned ALSAPool::get_capture_frequency(unsigned index)
535 lock_guard<mutex> lock(mu);
536 assert(devices[index].held);
537 if (devices[index].input)
538 return devices[index].input->get_sample_rate();
540 return OUTPUT_FREQUENCY;
543 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
545 lock_guard<mutex> lock(mu);
546 assert(devices[index].held);
547 return devices[index].state;
550 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
552 lock_guard<mutex> lock(mu);
553 devices[index].state = state;
556 unsigned ALSAPool::find_free_device_index()
558 for (unsigned i = 0; i < devices.size(); ++i) {
559 if (devices[i].state == Device::State::EMPTY) {
560 devices[i].state = Device::State::READY;
565 new_dev.state = Device::State::READY;
566 devices.push_back(new_dev);
567 inputs.emplace_back(nullptr);
568 return devices.size() - 1;
571 void ALSAPool::free_card(unsigned index)
573 lock_guard<mutex> lock(mu);
574 if (devices[index].held) {
575 devices[index].state = Device::State::DEAD;
577 devices[index].state = Device::State::EMPTY;
578 inputs[index].reset();
580 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {