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 ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index)
50 sample_rate(sample_rate),
51 num_channels(num_channels),
52 audio_callback(audio_callback),
53 parent_pool(parent_pool),
54 internal_dev_index(internal_dev_index)
56 die_on_error(device, snd_pcm_open(&pcm_handle, device, SND_PCM_STREAM_CAPTURE, 0));
59 snd_pcm_hw_params_t *hw_params;
60 snd_pcm_hw_params_alloca(&hw_params);
61 if (!set_base_params(device, pcm_handle, hw_params, &sample_rate)) {
65 die_on_error("snd_pcm_hw_params_set_channels()", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
67 // Fragment size of 64 samples (about 1 ms at 48 kHz; a frame at 60
68 // fps/48 kHz is 800 samples.) We ask for 64 such periods in our buffer
69 // (~85 ms buffer); more than that, and our jitter is probably so high
70 // that the resampling queue can't keep up anyway.
71 // The entire thing with periods and such is a bit mysterious to me;
72 // seemingly I can get 96 frames at a time with no problems even if
73 // the period size is 64 frames. And if I set num_periods to e.g. 1,
74 // I can't have a big buffer.
77 die_on_error("snd_pcm_hw_params_set_periods_near()", snd_pcm_hw_params_set_periods_near(pcm_handle, hw_params, &num_periods, &dir));
80 die_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));
81 buffer_frames = 64 * 64;
82 die_on_error("snd_pcm_hw_params_set_buffer_size_near()", snd_pcm_hw_params_set_buffer_size_near(pcm_handle, hw_params, &buffer_frames));
83 die_on_error("snd_pcm_hw_params()", snd_pcm_hw_params(pcm_handle, hw_params));
84 //snd_pcm_hw_params_free(hw_params);
86 // Figure out which format the card actually chose.
87 die_on_error("snd_pcm_hw_params_current()", snd_pcm_hw_params_current(pcm_handle, hw_params));
88 snd_pcm_format_t chosen_format;
89 die_on_error("snd_pcm_hw_params_get_format()", snd_pcm_hw_params_get_format(hw_params, &chosen_format));
91 audio_format.num_channels = num_channels;
92 audio_format.bits_per_sample = 0;
93 switch (chosen_format) {
94 case SND_PCM_FORMAT_S16_LE:
95 audio_format.bits_per_sample = 16;
97 case SND_PCM_FORMAT_S24_LE:
98 audio_format.bits_per_sample = 24;
100 case SND_PCM_FORMAT_S32_LE:
101 audio_format.bits_per_sample = 32;
106 //printf("num_periods=%u period_size=%u buffer_frames=%u sample_rate=%u bits_per_sample=%d\n",
107 // num_periods, unsigned(period_size), unsigned(buffer_frames), sample_rate, audio_format.bits_per_sample);
109 buffer.reset(new uint8_t[buffer_frames * num_channels * audio_format.bits_per_sample / 8]);
111 snd_pcm_sw_params_t *sw_params;
112 snd_pcm_sw_params_alloca(&sw_params);
113 die_on_error("snd_pcm_sw_params_current()", snd_pcm_sw_params_current(pcm_handle, sw_params));
114 die_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));
115 die_on_error("snd_pcm_sw_params()", snd_pcm_sw_params(pcm_handle, sw_params));
117 die_on_error("snd_pcm_nonblock()", snd_pcm_nonblock(pcm_handle, 1));
118 die_on_error("snd_pcm_prepare()", snd_pcm_prepare(pcm_handle));
121 ALSAInput::~ALSAInput()
123 die_on_error("snd_pcm_close()", snd_pcm_close(pcm_handle));
126 void ALSAInput::start_capture_thread()
129 capture_thread = thread(&ALSAInput::capture_thread_func, this);
132 void ALSAInput::stop_capture_thread()
135 capture_thread.join();
138 void ALSAInput::capture_thread_func()
140 parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
141 die_on_error("snd_pcm_start()", snd_pcm_start(pcm_handle));
142 parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::RUNNING);
144 uint64_t num_frames_output = 0;
145 while (!should_quit) {
146 int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
147 if (ret == 0) continue; // Timeout.
149 fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
150 snd_pcm_prepare(pcm_handle);
151 snd_pcm_start(pcm_handle);
154 die_on_error("snd_pcm_wait()", ret);
156 snd_pcm_sframes_t frames = snd_pcm_readi(pcm_handle, buffer.get(), buffer_frames);
157 if (frames == -EPIPE) {
158 fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
159 snd_pcm_prepare(pcm_handle);
160 snd_pcm_start(pcm_handle);
164 fprintf(stderr, "snd_pcm_readi() returned 0\n");
167 die_on_error("snd_pcm_readi()", frames);
169 const int64_t prev_pts = frames_to_pts(num_frames_output);
170 const int64_t pts = frames_to_pts(num_frames_output + frames);
173 if (should_quit) return;
174 success = audio_callback(buffer.get(), frames, audio_format, pts - prev_pts);
176 num_frames_output += frames;
178 parent_pool->free_card(internal_dev_index);
181 int64_t ALSAInput::frames_to_pts(uint64_t n) const
183 return (n * TIMEBASE) / sample_rate;
186 void ALSAInput::die_on_error(const char *func_name, int err)
189 fprintf(stderr, "[%s] %s: %s\n", device.c_str(), func_name, snd_strerror(err));
194 ALSAPool::~ALSAPool()
196 for (Device &device : devices) {
197 if (device.input != nullptr) {
198 device.input->stop_capture_thread();
203 std::vector<ALSAPool::Device> ALSAPool::get_devices()
205 lock_guard<mutex> lock(mu);
206 for (Device &device : devices) {
212 void ALSAPool::hold_device(unsigned index)
214 lock_guard<mutex> lock(mu);
215 assert(index < devices.size());
216 devices[index].held = true;
219 void ALSAPool::release_device(unsigned index)
221 lock_guard<mutex> lock(mu);
222 if (index < devices.size()) {
223 devices[index].held = false;
227 void ALSAPool::enumerate_devices()
229 // Enumerate all cards.
230 for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
232 snprintf(address, sizeof(address), "hw:%d", card_index);
235 int err = snd_ctl_open(&ctl, address, 0);
237 printf("%s: %s\n", address, snd_strerror(err));
240 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
242 // Enumerate all devices on this card.
243 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
244 probe_device_with_retry(card_index, dev_index);
249 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
252 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
254 lock_guard<mutex> lock(add_device_mutex);
255 if (add_device_tries_left.count(address)) {
256 // Some thread is already busy retrying this,
257 // so just reset its count.
258 add_device_tries_left[address] = num_retries;
262 // Try (while still holding the lock) to add the device synchronously.
263 ProbeResult result = probe_device_once(card_index, dev_index);
264 if (result == ProbeResult::SUCCESS) {
266 } else if (result == ProbeResult::FAILURE) {
269 assert(result == ProbeResult::DEFER);
271 // Add failed for whatever reason (probably just that the device
272 // isn't up yet. Set up a count so that nobody else starts a thread,
273 // then start it ourselves.
274 fprintf(stderr, "Trying %s again in one second...\n", address);
275 add_device_tries_left[address] = num_retries;
276 thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
279 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
282 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
284 for ( ;; ) { // Termination condition within the loop.
287 // See if there are any retries left.
288 lock_guard<mutex> lock(add_device_mutex);
289 if (!add_device_tries_left.count(address) ||
290 add_device_tries_left[address] == 0) {
291 add_device_tries_left.erase(address);
292 fprintf(stderr, "Giving up probe of %s.\n", address);
296 // Seemingly there were. Give it a try (we still hold the mutex).
297 ProbeResult result = probe_device_once(card_index, dev_index);
298 if (result == ProbeResult::SUCCESS) {
299 add_device_tries_left.erase(address);
300 fprintf(stderr, "Probe of %s succeeded.\n", address);
302 } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
303 add_device_tries_left.erase(address);
304 fprintf(stderr, "Giving up probe of %s.\n", address);
309 assert(result == ProbeResult::DEFER);
310 fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
311 address, add_device_tries_left[address]);
315 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
318 snprintf(address, sizeof(address), "hw:%d", card_index);
320 int err = snd_ctl_open(&ctl, address, 0);
322 printf("%s: %s\n", address, snd_strerror(err));
323 return ALSAPool::ProbeResult::DEFER;
325 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
327 snd_pcm_info_t *pcm_info;
328 snd_pcm_info_alloca(&pcm_info);
329 snd_pcm_info_set_device(pcm_info, dev_index);
330 snd_pcm_info_set_subdevice(pcm_info, 0);
331 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
332 if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
333 // Not available for capture.
334 printf("%s: Not available for capture.\n", address);
335 return ALSAPool::ProbeResult::DEFER;
338 snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
340 unsigned num_channels = 0;
342 // Find all channel maps for this device, and pick out the one
343 // with the most channels.
344 snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
345 if (cmaps != nullptr) {
346 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
347 num_channels = max(num_channels, (*ptr)->map.channels);
349 snd_pcm_free_chmaps(cmaps);
351 if (num_channels == 0) {
352 // Device had no channel maps. We need to open it to query.
353 // TODO: Do this asynchronously.
354 snd_pcm_t *pcm_handle;
355 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
357 printf("%s: %s\n", address, snd_strerror(err));
358 return ALSAPool::ProbeResult::DEFER;
360 snd_pcm_hw_params_t *hw_params;
361 snd_pcm_hw_params_alloca(&hw_params);
362 unsigned sample_rate;
363 if (!set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
364 snd_pcm_close(pcm_handle);
365 return ALSAPool::ProbeResult::DEFER;
367 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
369 fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
370 address, snd_strerror(err));
371 snd_pcm_close(pcm_handle);
372 return ALSAPool::ProbeResult::DEFER;
374 snd_pcm_close(pcm_handle);
377 if (num_channels == 0) {
378 printf("%s: No channel maps with channels\n", address);
379 return ALSAPool::ProbeResult::FAILURE;
382 snd_ctl_card_info_t *card_info;
383 snd_ctl_card_info_alloca(&card_info);
384 snd_ctl_card_info(ctl, card_info);
386 lock_guard<mutex> lock(mu);
387 unsigned internal_dev_index = find_free_device_index();
388 devices[internal_dev_index].address = address;
389 devices[internal_dev_index].name = snd_ctl_card_info_get_name(card_info);
390 devices[internal_dev_index].info = snd_pcm_info_get_name(pcm_info);
391 devices[internal_dev_index].num_channels = num_channels;
392 devices[internal_dev_index].state = Device::State::READY;
394 fprintf(stderr, "%s: Probed successfully.\n", address);
396 return ALSAPool::ProbeResult::SUCCESS;
399 void ALSAPool::init()
401 thread(&ALSAPool::inotify_thread_func, this).detach();
405 void ALSAPool::inotify_thread_func()
407 int inotify_fd = inotify_init();
408 if (inotify_fd == -1) {
409 perror("inotify_init()");
410 fprintf(stderr, "No hotplug of ALSA devices available.\n");
414 int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
415 if (watch_fd == -1) {
416 perror("inotify_add_watch()");
417 fprintf(stderr, "No hotplug of ALSA devices available.\n");
422 int size = sizeof(inotify_event) + NAME_MAX + 1;
423 unique_ptr<char[]> buf(new char[size]);
425 int ret = read(inotify_fd, buf.get(), size);
426 if (ret < int(sizeof(inotify_event))) {
427 fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
434 for (int i = 0; i < ret; ) {
435 const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
436 i += sizeof(inotify_event) + event->len;
438 if (event->mask & IN_Q_OVERFLOW) {
439 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
442 unsigned card, device;
444 if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
445 if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
446 printf("Deleted capture device: Card %u, device %u\n", card, device);
449 if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
450 printf("Adding capture device: Card %u, device %u\n", card, device);
451 probe_device_with_retry(card, device);
458 void ALSAPool::reset_device(unsigned index)
460 lock_guard<mutex> lock(mu);
461 Device *device = &devices[index];
462 if (inputs[index] != nullptr) {
463 inputs[index]->stop_capture_thread();
466 inputs[index].reset();
468 // TODO: Put on a background thread instead of locking?
469 auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
470 inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
471 inputs[index]->start_capture_thread();
473 device->input = inputs[index].get();
476 unsigned ALSAPool::get_capture_frequency(unsigned index)
478 lock_guard<mutex> lock(mu);
479 assert(devices[index].held);
480 if (devices[index].input)
481 return devices[index].input->get_sample_rate();
483 return OUTPUT_FREQUENCY;
486 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
488 lock_guard<mutex> lock(mu);
489 assert(devices[index].held);
490 return devices[index].state;
493 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
495 lock_guard<mutex> lock(mu);
496 devices[index].state = state;
499 unsigned ALSAPool::find_free_device_index()
501 for (unsigned i = 0; i < devices.size(); ++i) {
502 if (devices[i].state == Device::State::EMPTY) {
503 devices[i].state = Device::State::READY;
508 new_dev.state = Device::State::READY;
509 devices.push_back(new_dev);
510 inputs.emplace_back(nullptr);
511 return devices.size() - 1;
514 void ALSAPool::free_card(unsigned index)
516 lock_guard<mutex> lock(mu);
517 if (devices[index].held) {
518 devices[index].state = Device::State::DEAD;
520 devices[index].state = Device::State::EMPTY;
521 inputs[index].reset();
523 while (!devices.empty() && devices.back().state == Device::State::EMPTY) {