]> git.sesse.net Git - nageru/blob - alsa_input.cpp
Various Makefile tweaks (mostly related to cleaning moc files).
[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::placeholders;
16
17 #define RETURN_ON_ERROR(msg, expr) do {                                                    \
18         int err = (expr);                                                                  \
19         if (err < 0) {                                                                     \
20                 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err));  \
21                 if (err == -ENODEV) return CaptureEndReason::DEVICE_GONE;                  \
22                 return CaptureEndReason::OTHER_ERROR;                                      \
23         }                                                                                  \
24 } while (false)
25
26 #define RETURN_FALSE_ON_ERROR(msg, expr) do {                                              \
27         int err = (expr);                                                                  \
28         if (err < 0) {                                                                     \
29                 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err));  \
30                 return false;                                                              \
31         }                                                                                  \
32 } while (false)
33
34 #define WARN_ON_ERROR(msg, expr) do {                                                      \
35         int err = (expr);                                                                  \
36         if (err < 0) {                                                                     \
37                 fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err));  \
38         }                                                                                  \
39 } while (false)
40
41 ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index)
42         : device(device),
43           sample_rate(sample_rate),
44           num_channels(num_channels),
45           audio_callback(audio_callback),
46           parent_pool(parent_pool),
47           internal_dev_index(internal_dev_index)
48 {
49 }
50
51 bool ALSAInput::open_device()
52 {
53         RETURN_FALSE_ON_ERROR("snd_pcm_open()", snd_pcm_open(&pcm_handle, device.c_str(), SND_PCM_STREAM_CAPTURE, 0));
54
55         // Set format.
56         snd_pcm_hw_params_t *hw_params;
57         snd_pcm_hw_params_alloca(&hw_params);
58         if (!set_base_params(device.c_str(), pcm_handle, hw_params, &sample_rate)) {
59                 return false;
60         }
61
62         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_channels()", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
63
64         // Fragment size of 64 samples (about 1 ms at 48 kHz; a frame at 60
65         // fps/48 kHz is 800 samples.) We ask for 64 such periods in our buffer
66         // (~85 ms buffer); more than that, and our jitter is probably so high
67         // that the resampling queue can't keep up anyway.
68         // The entire thing with periods and such is a bit mysterious to me;
69         // seemingly I can get 96 frames at a time with no problems even if
70         // the period size is 64 frames. And if I set num_periods to e.g. 1,
71         // I can't have a big buffer.
72         num_periods = 16;
73         int dir = 0;
74         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));
75         period_size = 64;
76         dir = 0;
77         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));
78         buffer_frames = 64 * 64;
79         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));
80         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params()", snd_pcm_hw_params(pcm_handle, hw_params));
81         //snd_pcm_hw_params_free(hw_params);
82
83         // Figure out which format the card actually chose.
84         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_current()", snd_pcm_hw_params_current(pcm_handle, hw_params));
85         snd_pcm_format_t chosen_format;
86         RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_get_format()", snd_pcm_hw_params_get_format(hw_params, &chosen_format));
87
88         audio_format.num_channels = num_channels;
89         audio_format.bits_per_sample = 0;
90         switch (chosen_format) {
91         case SND_PCM_FORMAT_S16_LE:
92                 audio_format.bits_per_sample = 16;
93                 break;
94         case SND_PCM_FORMAT_S24_LE:
95                 audio_format.bits_per_sample = 24;
96                 break;
97         case SND_PCM_FORMAT_S32_LE:
98                 audio_format.bits_per_sample = 32;
99                 break;
100         default:
101                 assert(false);
102         }
103         //printf("num_periods=%u period_size=%u buffer_frames=%u sample_rate=%u bits_per_sample=%d\n",
104         //      num_periods, unsigned(period_size), unsigned(buffer_frames), sample_rate, audio_format.bits_per_sample);
105
106         buffer.reset(new uint8_t[buffer_frames * num_channels * audio_format.bits_per_sample / 8]);
107
108         snd_pcm_sw_params_t *sw_params;
109         snd_pcm_sw_params_alloca(&sw_params);
110         RETURN_FALSE_ON_ERROR("snd_pcm_sw_params_current()", snd_pcm_sw_params_current(pcm_handle, sw_params));
111         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));
112         RETURN_FALSE_ON_ERROR("snd_pcm_sw_params()", snd_pcm_sw_params(pcm_handle, sw_params));
113
114         RETURN_FALSE_ON_ERROR("snd_pcm_nonblock()", snd_pcm_nonblock(pcm_handle, 1));
115         RETURN_FALSE_ON_ERROR("snd_pcm_prepare()", snd_pcm_prepare(pcm_handle));
116         return true;
117 }
118
119 bool ALSAInput::set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate)
120 {
121         int err;
122         err = snd_pcm_hw_params_any(pcm_handle, hw_params);
123         if (err < 0) {
124                 fprintf(stderr, "[%s] snd_pcm_hw_params_any(): %s\n", device_name, snd_strerror(err));
125                 return false;
126         }
127         err = snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
128         if (err < 0) {
129                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_access(): %s\n", device_name, snd_strerror(err));
130                 return false;
131         }
132         snd_pcm_format_mask_t *format_mask;
133         snd_pcm_format_mask_alloca(&format_mask);
134         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S16_LE);
135         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S24_LE);
136         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S32_LE);
137         err = snd_pcm_hw_params_set_format_mask(pcm_handle, hw_params, format_mask);
138         if (err < 0) {
139                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_format_mask(): %s\n", device_name, snd_strerror(err));
140                 return false;
141         }
142         err = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, sample_rate, 0);
143         if (err < 0) {
144                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_rate_near(): %s\n", device_name, snd_strerror(err));
145                 return false;
146         }
147         return true;
148 }
149
150 ALSAInput::~ALSAInput()
151 {
152         if (pcm_handle) {
153                 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
154         }
155 }
156
157 void ALSAInput::start_capture_thread()
158 {
159         should_quit = false;
160         capture_thread = thread(&ALSAInput::capture_thread_func, this);
161 }
162
163 void ALSAInput::stop_capture_thread()
164 {
165         should_quit = true;
166         capture_thread.join();
167 }
168
169 void ALSAInput::capture_thread_func()
170 {
171         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
172
173         // If the device hasn't been opened already, we need to do so
174         // before we can capture.
175         while (!should_quit && pcm_handle == nullptr) {
176                 if (!open_device()) {
177                         fprintf(stderr, "[%s] Waiting one second and trying again...\n",
178                                 device.c_str());
179                         sleep(1);
180                 }
181         }
182
183         if (should_quit) {
184                 // Don't call free_card(); that would be a deadlock.
185                 WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
186                 pcm_handle = nullptr;
187                 return;
188         }
189
190         // Do the actual capture. (Termination condition within loop.)
191         for ( ;; ) {
192                 switch (do_capture()) {
193                 case CaptureEndReason::REQUESTED_QUIT:
194                         // Don't call free_card(); that would be a deadlock.
195                         WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
196                         pcm_handle = nullptr;
197                         return;
198                 case CaptureEndReason::DEVICE_GONE:
199                         parent_pool->free_card(internal_dev_index);
200                         WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
201                         pcm_handle = nullptr;
202                         return;
203                 case CaptureEndReason::OTHER_ERROR:
204                         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
205                         fprintf(stderr, "[%s] Sleeping one second and restarting capture...\n",
206                                 device.c_str());
207                         sleep(1);
208                         break;
209                 }
210         }
211 }
212
213 ALSAInput::CaptureEndReason ALSAInput::do_capture()
214 {
215         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
216         RETURN_ON_ERROR("snd_pcm_start()", snd_pcm_start(pcm_handle));
217         parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::RUNNING);
218
219         uint64_t num_frames_output = 0;
220         while (!should_quit) {
221                 int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
222                 if (ret == 0) continue;  // Timeout.
223                 if (ret == -EPIPE) {
224                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
225                         snd_pcm_prepare(pcm_handle);
226                         snd_pcm_start(pcm_handle);
227                         continue;
228                 }
229                 RETURN_ON_ERROR("snd_pcm_wait()", ret);
230
231                 snd_pcm_sframes_t frames = snd_pcm_readi(pcm_handle, buffer.get(), buffer_frames);
232                 if (frames == -EPIPE) {
233                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
234                         snd_pcm_prepare(pcm_handle);
235                         snd_pcm_start(pcm_handle);
236                         continue;
237                 }
238                 if (frames == 0) {
239                         fprintf(stderr, "snd_pcm_readi() returned 0\n");
240                         break;
241                 }
242                 RETURN_ON_ERROR("snd_pcm_readi()", frames);
243
244                 const int64_t prev_pts = frames_to_pts(num_frames_output);
245                 const int64_t pts = frames_to_pts(num_frames_output + frames);
246                 bool success;
247                 do {
248                         if (should_quit) return CaptureEndReason::REQUESTED_QUIT;
249                         success = audio_callback(buffer.get(), frames, audio_format, pts - prev_pts);
250                 } while (!success);
251                 num_frames_output += frames;
252         }
253         return CaptureEndReason::REQUESTED_QUIT;
254 }
255
256 int64_t ALSAInput::frames_to_pts(uint64_t n) const
257 {
258         return (n * TIMEBASE) / sample_rate;
259 }
260