]> git.sesse.net Git - nageru/blob - alsa_input.cpp
Update the queue length metric after trimming, not before.
[nageru] / alsa_input.cpp
1 #include "alsa_input.h"
2
3 #include <alsa/error.h>
4 #include <assert.h>
5 #include <errno.h>
6 #include <stdio.h>
7 #include <unistd.h>
8 #include <cstdint>
9
10 #include "alsa_pool.h"
11 #include "bmusb/bmusb.h"
12 #include "timebase.h"
13
14 using namespace std;
15 using namespace std::chrono;
16 using namespace std::placeholders;
17
18 #define RETURN_ON_ERROR(msg, expr) do {                                                    \
19         int err = (expr);                                                                  \
20         if (err < 0) {                                                                     \
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;                                      \
24         }                                                                                  \
25 } while (false)
26
27 #define RETURN_FALSE_ON_ERROR(msg, expr) do {                                              \
28         int err = (expr);                                                                  \
29         if (err < 0) {                                                                     \
30                 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err));  \
31                 return false;                                                              \
32         }                                                                                  \
33 } while (false)
34
35 #define WARN_ON_ERROR(msg, expr) do {                                                      \
36         int err = (expr);                                                                  \
37         if (err < 0) {                                                                     \
38                 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err));  \
39         }                                                                                  \
40 } while (false)
41
42 ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index)
43         : device(device),
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)
49 {
50 }
51
52 bool ALSAInput::open_device()
53 {
54         RETURN_FALSE_ON_ERROR("snd_pcm_open()", snd_pcm_open(&pcm_handle, device.c_str(), SND_PCM_STREAM_CAPTURE, 0));
55
56         // Set format.
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)) {
60                 return false;
61         }
62
63         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_channels()", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
64
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.
73         num_periods = 16;
74         int dir = 0;
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));
76         period_size = 64;
77         dir = 0;
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);
83
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));
88
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;
94                 break;
95         case SND_PCM_FORMAT_S24_LE:
96                 audio_format.bits_per_sample = 24;
97                 break;
98         case SND_PCM_FORMAT_S32_LE:
99                 audio_format.bits_per_sample = 32;
100                 break;
101         default:
102                 assert(false);
103         }
104         //printf("num_periods=%u period_size=%u buffer_frames=%u sample_rate=%u bits_per_sample=%d\n",
105         //      num_periods, unsigned(period_size), unsigned(buffer_frames), sample_rate, audio_format.bits_per_sample);
106
107         buffer.reset(new uint8_t[buffer_frames * num_channels * audio_format.bits_per_sample / 8]);
108
109         snd_pcm_sw_params_t *sw_params;
110         snd_pcm_sw_params_alloca(&sw_params);
111         RETURN_FALSE_ON_ERROR("snd_pcm_sw_params_current()", snd_pcm_sw_params_current(pcm_handle, sw_params));
112         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));
113         RETURN_FALSE_ON_ERROR("snd_pcm_sw_params()", snd_pcm_sw_params(pcm_handle, sw_params));
114
115         RETURN_FALSE_ON_ERROR("snd_pcm_nonblock()", snd_pcm_nonblock(pcm_handle, 1));
116         RETURN_FALSE_ON_ERROR("snd_pcm_prepare()", snd_pcm_prepare(pcm_handle));
117         return true;
118 }
119
120 bool ALSAInput::set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate)
121 {
122         int err;
123         err = snd_pcm_hw_params_any(pcm_handle, hw_params);
124         if (err < 0) {
125                 fprintf(stderr, "[%s] snd_pcm_hw_params_any(): %s\n", device_name, snd_strerror(err));
126                 return false;
127         }
128         err = snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
129         if (err < 0) {
130                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_access(): %s\n", device_name, snd_strerror(err));
131                 return false;
132         }
133         snd_pcm_format_mask_t *format_mask;
134         snd_pcm_format_mask_alloca(&format_mask);
135         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S16_LE);
136         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S24_LE);
137         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S32_LE);
138         err = snd_pcm_hw_params_set_format_mask(pcm_handle, hw_params, format_mask);
139         if (err < 0) {
140                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_format_mask(): %s\n", device_name, snd_strerror(err));
141                 return false;
142         }
143         err = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, sample_rate, 0);
144         if (err < 0) {
145                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_rate_near(): %s\n", device_name, snd_strerror(err));
146                 return false;
147         }
148         return true;
149 }
150
151 ALSAInput::~ALSAInput()
152 {
153         if (pcm_handle) {
154                 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
155         }
156 }
157
158 void ALSAInput::start_capture_thread()
159 {
160         should_quit.unquit();
161         capture_thread = thread(&ALSAInput::capture_thread_func, this);
162 }
163
164 void ALSAInput::stop_capture_thread()
165 {
166         should_quit.quit();
167         capture_thread.join();
168 }
169
170 void ALSAInput::capture_thread_func()
171 {
172         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
173
174         // If the device hasn't been opened already, we need to do so
175         // before we can capture.
176         while (!should_quit.should_quit() && pcm_handle == nullptr) {
177                 if (!open_device()) {
178                         fprintf(stderr, "[%s] Waiting one second and trying again...\n",
179                                 device.c_str());
180                         should_quit.sleep_for(seconds(1));
181                 }
182         }
183
184         if (should_quit.should_quit()) {
185                 // Don't call free_card(); that would be a deadlock.
186                 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
187                 pcm_handle = nullptr;
188                 return;
189         }
190
191         // Do the actual capture. (Termination condition within loop.)
192         for ( ;; ) {
193                 switch (do_capture()) {
194                 case CaptureEndReason::REQUESTED_QUIT:
195                         // Don't call free_card(); that would be a deadlock.
196                         WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
197                         pcm_handle = nullptr;
198                         return;
199                 case CaptureEndReason::DEVICE_GONE:
200                         parent_pool->free_card(internal_dev_index);
201                         WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
202                         pcm_handle = nullptr;
203                         return;
204                 case CaptureEndReason::OTHER_ERROR:
205                         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
206                         fprintf(stderr, "[%s] Sleeping one second and restarting capture...\n",
207                                 device.c_str());
208                         should_quit.sleep_for(seconds(1));
209                         break;
210                 }
211         }
212 }
213
214 ALSAInput::CaptureEndReason ALSAInput::do_capture()
215 {
216         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
217         RETURN_ON_ERROR("snd_pcm_start()", snd_pcm_start(pcm_handle));
218         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::RUNNING);
219
220         uint64_t num_frames_output = 0;
221         while (!should_quit.should_quit()) {
222                 int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
223                 if (ret == 0) continue;  // Timeout.
224                 if (ret == -EPIPE) {
225                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
226                         snd_pcm_prepare(pcm_handle);
227                         snd_pcm_start(pcm_handle);
228                         continue;
229                 }
230                 RETURN_ON_ERROR("snd_pcm_wait()", ret);
231
232                 snd_pcm_sframes_t frames = snd_pcm_readi(pcm_handle, buffer.get(), buffer_frames);
233                 if (frames == -EPIPE) {
234                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
235                         snd_pcm_prepare(pcm_handle);
236                         snd_pcm_start(pcm_handle);
237                         continue;
238                 }
239                 if (frames == 0) {
240                         fprintf(stderr, "snd_pcm_readi() returned 0\n");
241                         break;
242                 }
243                 RETURN_ON_ERROR("snd_pcm_readi()", frames);
244
245                 const int64_t prev_pts = frames_to_pts(num_frames_output);
246                 const int64_t pts = frames_to_pts(num_frames_output + frames);
247                 const steady_clock::time_point now = steady_clock::now();
248                 bool success;
249                 do {
250                         if (should_quit.should_quit()) return CaptureEndReason::REQUESTED_QUIT;
251                         success = audio_callback(buffer.get(), frames, audio_format, pts - prev_pts, now);
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