1 #include "alsa_input.h"
3 #include <alsa/error.h>
10 #include "alsa_pool.h"
11 #include "bmusb/bmusb.h"
12 #include "shared/timebase.h"
15 using namespace std::chrono;
16 using namespace std::placeholders;
18 #define RETURN_ON_ERROR(msg, expr) do { \
21 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err)); \
22 if (err == -ENODEV) return CaptureEndReason::DEVICE_GONE; \
23 return CaptureEndReason::OTHER_ERROR; \
27 #define RETURN_FALSE_ON_ERROR(msg, expr) do { \
30 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err)); \
35 #define WARN_ON_ERROR(msg, expr) do { \
38 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err)); \
42 ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index)
44 sample_rate(sample_rate),
45 num_channels(num_channels),
46 audio_callback(audio_callback),
47 parent_pool(parent_pool),
48 internal_dev_index(internal_dev_index)
52 bool ALSAInput::open_device()
54 RETURN_FALSE_ON_ERROR("snd_pcm_open()", snd_pcm_open(&pcm_handle, device.c_str(), SND_PCM_STREAM_CAPTURE, 0));
57 snd_pcm_hw_params_t *hw_params;
58 snd_pcm_hw_params_alloca(&hw_params);
59 if (!set_base_params(device.c_str(), pcm_handle, hw_params, &sample_rate)) {
63 RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_channels()", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
65 // Fragment size of 64 samples (about 1 ms at 48 kHz; a frame at 60
66 // fps/48 kHz is 800 samples.) We ask for 64 such periods in our buffer
67 // (~85 ms buffer); more than that, and our jitter is probably so high
68 // that the resampling queue can't keep up anyway.
69 // The entire thing with periods and such is a bit mysterious to me;
70 // seemingly I can get 96 frames at a time with no problems even if
71 // the period size is 64 frames. And if I set num_periods to e.g. 1,
72 // I can't have a big buffer.
75 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));
78 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));
79 buffer_frames = 64 * 64;
80 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));
81 RETURN_FALSE_ON_ERROR("snd_pcm_hw_params()", snd_pcm_hw_params(pcm_handle, hw_params));
82 //snd_pcm_hw_params_free(hw_params);
84 // Figure out which format the card actually chose.
85 RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_current()", snd_pcm_hw_params_current(pcm_handle, hw_params));
86 snd_pcm_format_t chosen_format;
87 RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_get_format()", snd_pcm_hw_params_get_format(hw_params, &chosen_format));
89 audio_format.num_channels = num_channels;
90 audio_format.bits_per_sample = 0;
91 switch (chosen_format) {
92 case SND_PCM_FORMAT_S16_LE:
93 audio_format.bits_per_sample = 16;
95 case SND_PCM_FORMAT_S24_LE:
96 audio_format.bits_per_sample = 24;
98 case SND_PCM_FORMAT_S32_LE:
99 audio_format.bits_per_sample = 32;
104 audio_format.sample_rate = sample_rate;
105 //printf("num_periods=%u period_size=%u buffer_frames=%u sample_rate=%u bits_per_sample=%d\n",
106 // num_periods, unsigned(period_size), unsigned(buffer_frames), sample_rate, audio_format.bits_per_sample);
108 buffer.reset(new uint8_t[buffer_frames * num_channels * audio_format.bits_per_sample / 8]);
110 snd_pcm_sw_params_t *sw_params;
111 snd_pcm_sw_params_alloca(&sw_params);
112 RETURN_FALSE_ON_ERROR("snd_pcm_sw_params_current()", snd_pcm_sw_params_current(pcm_handle, sw_params));
113 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));
114 RETURN_FALSE_ON_ERROR("snd_pcm_sw_params_set_tstamp_mode", snd_pcm_sw_params_set_tstamp_mode(pcm_handle, sw_params, SND_PCM_TSTAMP_ENABLE));
115 RETURN_FALSE_ON_ERROR("snd_pcm_sw_params_set_tstamp_type", snd_pcm_sw_params_set_tstamp_type(pcm_handle, sw_params, SND_PCM_TSTAMP_TYPE_MONOTONIC));
117 RETURN_FALSE_ON_ERROR("snd_pcm_sw_params()", snd_pcm_sw_params(pcm_handle, sw_params));
119 RETURN_FALSE_ON_ERROR("snd_pcm_nonblock()", snd_pcm_nonblock(pcm_handle, 1));
120 RETURN_FALSE_ON_ERROR("snd_pcm_prepare()", snd_pcm_prepare(pcm_handle));
124 bool ALSAInput::set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate)
127 err = snd_pcm_hw_params_any(pcm_handle, hw_params);
129 fprintf(stderr, "[%s] snd_pcm_hw_params_any(): %s\n", device_name, snd_strerror(err));
132 err = snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
134 fprintf(stderr, "[%s] snd_pcm_hw_params_set_access(): %s\n", device_name, snd_strerror(err));
137 snd_pcm_format_mask_t *format_mask;
138 snd_pcm_format_mask_alloca(&format_mask);
139 snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S16_LE);
140 snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S24_LE);
141 snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S32_LE);
142 err = snd_pcm_hw_params_set_format_mask(pcm_handle, hw_params, format_mask);
144 fprintf(stderr, "[%s] snd_pcm_hw_params_set_format_mask(): %s\n", device_name, snd_strerror(err));
147 err = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, sample_rate, 0);
149 fprintf(stderr, "[%s] snd_pcm_hw_params_set_rate_near(): %s\n", device_name, snd_strerror(err));
155 ALSAInput::~ALSAInput()
158 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
162 void ALSAInput::start_capture_thread()
164 assert(!device.empty());
165 should_quit.unquit();
166 capture_thread = thread(&ALSAInput::capture_thread_func, this);
169 void ALSAInput::stop_capture_thread()
172 capture_thread.join();
175 void ALSAInput::capture_thread_func()
178 char thread_name[16];
179 snprintf(thread_name, sizeof(thread_name), "ALSA_C_%d", internal_dev_index);
180 pthread_setname_np(pthread_self(), thread_name);
185 parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
187 // If the device hasn't been opened already, we need to do so
188 // before we can capture.
189 while (!should_quit.should_quit() && pcm_handle == nullptr) {
190 if (!open_device()) {
191 fprintf(stderr, "[%s] Waiting one second and trying again...\n",
193 should_quit.sleep_for(seconds(1));
197 if (should_quit.should_quit()) {
198 // Don't call free_card(); that would be a deadlock.
200 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
202 pcm_handle = nullptr;
206 // Do the actual capture. (Termination condition within loop.)
208 switch (do_capture()) {
209 case CaptureEndReason::REQUESTED_QUIT:
210 // Don't call free_card(); that would be a deadlock.
211 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
212 pcm_handle = nullptr;
214 case CaptureEndReason::DEVICE_GONE:
215 parent_pool->free_card(internal_dev_index);
216 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
217 pcm_handle = nullptr;
219 case CaptureEndReason::OTHER_ERROR:
220 parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
221 fprintf(stderr, "[%s] Sleeping one second and restarting capture...\n",
223 should_quit.sleep_for(seconds(1));
229 ALSAInput::CaptureEndReason ALSAInput::do_capture()
231 parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
232 RETURN_ON_ERROR("snd_pcm_start()", snd_pcm_start(pcm_handle));
233 parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::RUNNING);
235 snd_pcm_status_t *status;
236 snd_pcm_status_alloca(&status);
237 while (!should_quit.should_quit()) {
238 int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
239 if (ret == 0) continue; // Timeout.
241 fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
242 snd_pcm_prepare(pcm_handle);
243 snd_pcm_start(pcm_handle);
246 RETURN_ON_ERROR("snd_pcm_wait()", ret);
248 ret = snd_pcm_status(pcm_handle, status);
249 RETURN_ON_ERROR("snd_pcm_status()", ret);
251 snd_pcm_sframes_t avail = snd_pcm_status_get_avail(status);
252 snd_htimestamp_t alsa_ts;
253 snd_pcm_status_get_htstamp(status, &alsa_ts);
255 snd_pcm_sframes_t frames = snd_pcm_readi(pcm_handle, buffer.get(), avail);
256 if (frames == -EPIPE) {
257 fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
258 snd_pcm_prepare(pcm_handle);
259 snd_pcm_start(pcm_handle);
263 fprintf(stderr, "snd_pcm_readi() returned 0\n");
266 RETURN_ON_ERROR("snd_pcm_readi()", frames);
268 // NOTE: This assumes steady_clock::time_point is the same as clock_gettime(CLOCK_MONOTONIC).
269 const steady_clock::time_point ts = steady_clock::time_point(seconds(alsa_ts.tv_sec) + nanoseconds(alsa_ts.tv_nsec));
272 if (should_quit.should_quit()) return CaptureEndReason::REQUESTED_QUIT;
273 success = audio_callback(buffer.get(), frames, audio_format, ts);
276 return CaptureEndReason::REQUESTED_QUIT;