]> git.sesse.net Git - nageru/blob - alsa_input.cpp
Support limited ALSA hotplug.
[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 ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index)
49         : device(device),
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)
55 {
56         die_on_error(device, snd_pcm_open(&pcm_handle, device, SND_PCM_STREAM_CAPTURE, 0));
57
58         // Set format.
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)) {
62                 exit(1);
63         }
64
65         die_on_error("snd_pcm_hw_params_set_channels()", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
66
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.
75         num_periods = 16;
76         int dir = 0;
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));
78         period_size = 64;
79         dir = 0;
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);
85
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));
90
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;
96                 break;
97         case SND_PCM_FORMAT_S24_LE:
98                 audio_format.bits_per_sample = 24;
99                 break;
100         case SND_PCM_FORMAT_S32_LE:
101                 audio_format.bits_per_sample = 32;
102                 break;
103         default:
104                 assert(false);
105         }
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);
108
109         buffer.reset(new uint8_t[buffer_frames * num_channels * audio_format.bits_per_sample / 8]);
110
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));
116
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));
119 }
120
121 ALSAInput::~ALSAInput()
122 {
123         die_on_error("snd_pcm_close()", snd_pcm_close(pcm_handle));
124 }
125
126 void ALSAInput::start_capture_thread()
127 {
128         should_quit = false;
129         capture_thread = thread(&ALSAInput::capture_thread_func, this);
130 }
131
132 void ALSAInput::stop_capture_thread()
133 {
134         should_quit = true;
135         capture_thread.join();
136 }
137
138 void ALSAInput::capture_thread_func()
139 {
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);
143
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.
148                 if (ret == -EPIPE) {
149                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
150                         snd_pcm_prepare(pcm_handle);
151                         snd_pcm_start(pcm_handle);
152                         continue;
153                 }
154                 die_on_error("snd_pcm_wait()", ret);
155
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);
161                         continue;
162                 }
163                 if (frames == 0) {
164                         fprintf(stderr, "snd_pcm_readi() returned 0\n");
165                         break;
166                 }
167                 die_on_error("snd_pcm_readi()", frames);
168
169                 const int64_t prev_pts = frames_to_pts(num_frames_output);
170                 const int64_t pts = frames_to_pts(num_frames_output + frames);
171                 bool success;
172                 do {
173                         if (should_quit) return;
174                         success = audio_callback(buffer.get(), frames, audio_format, pts - prev_pts);
175                 } while (!success);
176                 num_frames_output += frames;
177         }
178         parent_pool->free_card(internal_dev_index);
179 }
180
181 int64_t ALSAInput::frames_to_pts(uint64_t n) const
182 {
183         return (n * TIMEBASE) / sample_rate;
184 }
185
186 void ALSAInput::die_on_error(const char *func_name, int err)
187 {
188         if (err < 0) {
189                 fprintf(stderr, "[%s] %s: %s\n", device.c_str(), func_name, snd_strerror(err));
190                 exit(1);
191         }
192 }
193
194 ALSAPool::~ALSAPool()
195 {
196         for (Device &device : devices) {
197                 if (device.input != nullptr) {
198                         device.input->stop_capture_thread();
199                 }
200         }
201 }
202
203 std::vector<ALSAPool::Device> ALSAPool::get_devices()
204 {
205         lock_guard<mutex> lock(mu);
206         for (Device &device : devices) {
207                 device.held = true;
208         }
209         return devices;
210 }
211
212 void ALSAPool::hold_device(unsigned index)
213 {
214         lock_guard<mutex> lock(mu);
215         assert(index < devices.size());
216         devices[index].held = true;
217 }
218
219 void ALSAPool::release_device(unsigned index)
220 {
221         lock_guard<mutex> lock(mu);
222         if (index < devices.size()) {
223                 devices[index].held = false;
224         }
225 }
226
227 void ALSAPool::enumerate_devices()
228 {
229         // Enumerate all cards.
230         for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
231                 char address[256];
232                 snprintf(address, sizeof(address), "hw:%d", card_index);
233
234                 snd_ctl_t *ctl;
235                 int err = snd_ctl_open(&ctl, address, 0);
236                 if (err < 0) {
237                         printf("%s: %s\n", address, snd_strerror(err));
238                         continue;
239                 }
240                 unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
241
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);
245                 }
246         }
247 }
248
249 void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
250 {
251         char address[256];
252         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
253
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;
259                 return;
260         }
261
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) {
265                 return;
266         } else if (result == ProbeResult::FAILURE) {
267                 return;
268         }
269         assert(result == ProbeResult::DEFER);
270
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();
277 }
278
279 void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
280 {
281         char address[256];
282         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
283
284         for ( ;; ) {  // Termination condition within the loop.
285                 sleep(1);
286
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);
293                         return;
294                 }
295
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);
301                         return;
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);
305                         return;
306                 }
307
308                 // Failed again.
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]);
312         }
313 }
314
315 ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
316 {
317         char address[256];
318         snprintf(address, sizeof(address), "hw:%d", card_index);
319         snd_ctl_t *ctl;
320         int err = snd_ctl_open(&ctl, address, 0);
321         if (err < 0) {
322                 printf("%s: %s\n", address, snd_strerror(err));
323                 return ALSAPool::ProbeResult::DEFER;
324         }
325         unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
326
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;
336         }
337
338         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
339
340         unsigned num_channels = 0;
341
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);
348                 }
349                 snd_pcm_free_chmaps(cmaps);
350         }
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);
356                 if (err < 0) {
357                         printf("%s: %s\n", address, snd_strerror(err));
358                         return ALSAPool::ProbeResult::DEFER;
359                 }
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;
366                 }
367                 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
368                 if (err < 0) {
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;
373                 }
374                 snd_pcm_close(pcm_handle);
375         }
376
377         if (num_channels == 0) {
378                 printf("%s: No channel maps with channels\n", address);
379                 return ALSAPool::ProbeResult::FAILURE;
380         }
381
382         snd_ctl_card_info_t *card_info;
383         snd_ctl_card_info_alloca(&card_info);
384         snd_ctl_card_info(ctl, card_info);
385
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;
393
394         fprintf(stderr, "%s: Probed successfully.\n", address);
395
396         return ALSAPool::ProbeResult::SUCCESS;
397 }
398
399 void ALSAPool::init()
400 {
401         thread(&ALSAPool::inotify_thread_func, this).detach();
402         enumerate_devices();
403 }
404
405 void ALSAPool::inotify_thread_func()
406 {
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");
411                 return;
412         }
413
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");
418                 close(inotify_fd);
419                 return;
420         }
421
422         int size = sizeof(inotify_event) + NAME_MAX + 1;
423         unique_ptr<char[]> buf(new char[size]);
424         for ( ;; ) {
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",
428                                 int(ret));
429                         close(watch_fd);
430                         close(inotify_fd);
431                         return;
432                 }
433
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;
437
438                         if (event->mask & IN_Q_OVERFLOW) {
439                                 fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
440                                 continue;
441                         }
442                         unsigned card, device;
443                         char type;
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);
447                                         // TODO: Unplug.
448                                 }
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);
452                                 }
453                         }
454                 }
455         }
456 }
457
458 void ALSAPool::reset_device(unsigned index)
459 {
460         lock_guard<mutex> lock(mu);
461         Device *device = &devices[index];
462         if (inputs[index] != nullptr) {
463                 inputs[index]->stop_capture_thread();
464         }
465         if (!device->held) {
466                 inputs[index].reset();
467         } else {
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();
472         }
473         device->input = inputs[index].get();
474 }
475
476 unsigned ALSAPool::get_capture_frequency(unsigned index)
477 {
478         lock_guard<mutex> lock(mu);
479         assert(devices[index].held);
480         if (devices[index].input)
481                 return devices[index].input->get_sample_rate();
482         else
483                 return OUTPUT_FREQUENCY;
484 }
485
486 ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
487 {
488         lock_guard<mutex> lock(mu);
489         assert(devices[index].held);
490         return devices[index].state;
491 }
492
493 void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
494 {
495         lock_guard<mutex> lock(mu);
496         devices[index].state = state;
497 }
498
499 unsigned ALSAPool::find_free_device_index()
500 {
501         for (unsigned i = 0; i < devices.size(); ++i) {
502                 if (devices[i].state == Device::State::EMPTY) {
503                         devices[i].state = Device::State::READY;
504                         return i;
505                 }
506         }
507         Device new_dev;
508         new_dev.state = Device::State::READY;
509         devices.push_back(new_dev);
510         inputs.emplace_back(nullptr);
511         return devices.size() - 1;
512 }
513
514 void ALSAPool::free_card(unsigned index)
515 {
516         lock_guard<mutex> lock(mu);
517         if (devices[index].held) {
518                 devices[index].state = Device::State::DEAD;
519         } else {
520                 devices[index].state = Device::State::EMPTY;
521                 inputs[index].reset();
522         }
523         while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
524                 devices.pop_back();
525                 inputs.pop_back();
526         }
527 }