]> git.sesse.net Git - nageru/blob - alsa_input.cpp
Add support for ALSA devices that have no channel maps.
[nageru] / alsa_input.cpp
1
2 #include "alsa_input.h"
3
4 using namespace std;
5
6 ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback)
7         : device(device), sample_rate(sample_rate), num_channels(num_channels), audio_callback(audio_callback)
8 {
9         die_on_error(device, snd_pcm_open(&pcm_handle, device, SND_PCM_STREAM_CAPTURE, 0));
10
11         // Set format.
12         snd_pcm_hw_params_t *hw_params;
13         snd_pcm_hw_params_alloca(&hw_params);
14         if (!set_base_params(device, pcm_handle, hw_params, &sample_rate)) {
15                 exit(1);
16         }
17
18         die_on_error("snd_pcm_hw_params_set_channels()", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
19
20         // Fragment size of 64 samples (about 1 ms at 48 kHz; a frame at 60
21         // fps/48 kHz is 800 samples.) We ask for 64 such periods in our buffer
22         // (~85 ms buffer); more than that, and our jitter is probably so high
23         // that the resampling queue can't keep up anyway.
24         // The entire thing with periods and such is a bit mysterious to me;
25         // seemingly I can get 96 frames at a time with no problems even if
26         // the period size is 64 frames. And if I set num_periods to e.g. 1,
27         // I can't have a big buffer.
28         num_periods = 16;
29         int dir = 0;
30         die_on_error("snd_pcm_hw_params_set_periods_near()", snd_pcm_hw_params_set_periods_near(pcm_handle, hw_params, &num_periods, &dir));
31         period_size = 64;
32         dir = 0;
33         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));
34         buffer_frames = 64 * 64;
35         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));
36         die_on_error("snd_pcm_hw_params()", snd_pcm_hw_params(pcm_handle, hw_params));
37         //snd_pcm_hw_params_free(hw_params);
38
39         // Figure out which format the card actually chose.
40         die_on_error("snd_pcm_hw_params_current()", snd_pcm_hw_params_current(pcm_handle, hw_params));
41         snd_pcm_format_t chosen_format;
42         die_on_error("snd_pcm_hw_params_get_format()", snd_pcm_hw_params_get_format(hw_params, &chosen_format));
43
44         audio_format.num_channels = num_channels;
45         audio_format.bits_per_sample = 0;
46         switch (chosen_format) {
47         case SND_PCM_FORMAT_S16_LE:
48                 audio_format.bits_per_sample = 16;
49                 break;
50         case SND_PCM_FORMAT_S24_LE:
51                 audio_format.bits_per_sample = 24;
52                 break;
53         case SND_PCM_FORMAT_S32_LE:
54                 audio_format.bits_per_sample = 32;
55                 break;
56         default:
57                 assert(false);
58         }
59         //printf("num_periods=%u period_size=%u buffer_frames=%u sample_rate=%u bits_per_sample=%d\n",
60         //      num_periods, unsigned(period_size), unsigned(buffer_frames), sample_rate, audio_format.bits_per_sample);
61
62         buffer.reset(new uint8_t[buffer_frames * num_channels * audio_format.bits_per_sample / 8]);
63
64         snd_pcm_sw_params_t *sw_params;
65         snd_pcm_sw_params_alloca(&sw_params);
66         die_on_error("snd_pcm_sw_params_current()", snd_pcm_sw_params_current(pcm_handle, sw_params));
67         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));
68         die_on_error("snd_pcm_sw_params()", snd_pcm_sw_params(pcm_handle, sw_params));
69
70         die_on_error("snd_pcm_nonblock()", snd_pcm_nonblock(pcm_handle, 1));
71         die_on_error("snd_pcm_prepare()", snd_pcm_prepare(pcm_handle));
72 }
73
74 ALSAInput::~ALSAInput()
75 {
76         die_on_error("snd_pcm_close()", snd_pcm_close(pcm_handle));
77 }
78
79 void ALSAInput::start_capture_thread()
80 {
81         should_quit = false;
82         capture_thread = thread(&ALSAInput::capture_thread_func, this);
83 }
84
85 void ALSAInput::stop_capture_thread()
86 {
87         should_quit = true;
88         capture_thread.join();
89 }
90
91 void ALSAInput::capture_thread_func()
92 {
93         die_on_error("snd_pcm_start()", snd_pcm_start(pcm_handle));
94         uint64_t num_frames_output = 0;
95         while (!should_quit) {
96                 int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
97                 if (ret == 0) continue;  // Timeout.
98                 if (ret == -EPIPE) {
99                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
100                         snd_pcm_prepare(pcm_handle);
101                         snd_pcm_start(pcm_handle);
102                         continue;
103                 }
104                 die_on_error("snd_pcm_wait()", ret);
105
106                 snd_pcm_sframes_t frames = snd_pcm_readi(pcm_handle, buffer.get(), buffer_frames);
107                 if (frames == -EPIPE) {
108                         fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
109                         snd_pcm_prepare(pcm_handle);
110                         snd_pcm_start(pcm_handle);
111                         continue;
112                 }
113                 if (frames == 0) {
114                         fprintf(stderr, "snd_pcm_readi() returned 0\n");
115                         break;
116                 }
117                 die_on_error("snd_pcm_readi()", frames);
118
119                 const int64_t prev_pts = frames_to_pts(num_frames_output);
120                 const int64_t pts = frames_to_pts(num_frames_output + frames);
121                 bool success;
122                 do {
123                         if (should_quit) return;
124                         success = audio_callback(buffer.get(), frames, audio_format, pts - prev_pts);
125                 } while (!success);
126                 num_frames_output += frames;
127         }
128 }
129
130 int64_t ALSAInput::frames_to_pts(uint64_t n) const
131 {
132         return (n * TIMEBASE) / sample_rate;
133 }
134
135 void ALSAInput::die_on_error(const char *func_name, int err)
136 {
137         if (err < 0) {
138                 fprintf(stderr, "[%s] %s: %s\n", device.c_str(), func_name, snd_strerror(err));
139                 exit(1);
140         }
141 }
142
143 bool ALSAInput::set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate)
144 {
145         int err;
146         err = snd_pcm_hw_params_any(pcm_handle, hw_params);
147         if (err < 0) {
148                 fprintf(stderr, "[%s] snd_pcm_hw_params_any(): %s\n", device_name, snd_strerror(err));
149                 return false;
150         }
151         err = snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
152         if (err < 0) {
153                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_access(): %s\n", device_name, snd_strerror(err));
154                 return false;
155         }
156         snd_pcm_format_mask_t *format_mask;
157         snd_pcm_format_mask_alloca(&format_mask);
158         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S16_LE);
159         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S24_LE);
160         snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S32_LE);
161         err = snd_pcm_hw_params_set_format_mask(pcm_handle, hw_params, format_mask);
162         if (err < 0) {
163                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_format_mask(): %s\n", device_name, snd_strerror(err));
164                 return false;
165         }
166         err = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, sample_rate, 0);
167         if (err < 0) {
168                 fprintf(stderr, "[%s] snd_pcm_hw_params_set_rate_near(): %s\n", device_name, snd_strerror(err));
169                 return false;
170         }
171         return true;
172 }
173
174 vector<ALSAInput::Device> ALSAInput::enumerate_devices()
175 {
176         vector<Device> ret;
177
178         // Enumerate all cards.
179         for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
180                 char address[256];
181                 snprintf(address, sizeof(address), "hw:%d", card_index);
182
183                 snd_ctl_t *ctl;
184                 int err = snd_ctl_open(&ctl, address, 0);
185                 if (err < 0) {
186                         printf("%s: %s\n", address, snd_strerror(err));
187                         continue;
188                 }
189                 snd_ctl_card_info_t *card_info;
190                 snd_ctl_card_info_alloca(&card_info);
191                 snd_ctl_card_info(ctl, card_info);
192
193                 string card_name = snd_ctl_card_info_get_name(card_info);
194
195                 // Enumerate all devices on this card.
196                 for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
197                         snd_pcm_info_t *pcm_info;
198                         snd_pcm_info_alloca(&pcm_info);
199                         snd_pcm_info_set_device(pcm_info, dev_index);
200                         snd_pcm_info_set_subdevice(pcm_info, 0);
201                         snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
202                         if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
203                                 // Not available for capture.
204                                 continue;
205                         }
206
207                         snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
208
209                         unsigned num_channels = 0;
210
211                         // Find all channel maps for this device, and pick out the one
212                         // with the most channels.
213                         snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
214                         if (cmaps != nullptr) {
215                                 for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
216                                         num_channels = max(num_channels, (*ptr)->map.channels);
217                                 }
218                                 snd_pcm_free_chmaps(cmaps);
219                         }
220                         if (num_channels == 0) {
221                                 // Device had no channel maps. We need to open it to query.
222                                 snd_pcm_t *pcm_handle;
223                                 int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
224                                 if (err < 0) {
225                                         // TODO: When we go to hotplug support, we should support some
226                                         // retry here, as the device could legitimately be busy.
227                                         printf("%s: %s\n", address, snd_strerror(err));
228                                         continue;
229                                 }
230                                 snd_pcm_hw_params_t *hw_params;
231                                 snd_pcm_hw_params_alloca(&hw_params);
232                                 unsigned sample_rate;
233                                 if (!set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
234                                         snd_pcm_close(pcm_handle);
235                                         continue;
236                                 }
237                                 err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
238                                 if (err < 0) {
239                                         fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
240                                                 address, snd_strerror(err));
241                                         snd_pcm_close(pcm_handle);
242                                         continue;
243                                 }
244                                 snd_pcm_close(pcm_handle);
245                         }
246
247                         if (num_channels == 0) {
248                                 printf("%s: No channel maps with channels\n", address);
249                                 continue;
250                         }
251
252                         Device dev;
253                         dev.address = address;
254                         dev.name = card_name;
255                         dev.info = snd_pcm_info_get_name(pcm_info);
256                         dev.num_channels = num_channels;
257
258                         ret.push_back(dev);
259                 }
260                 snd_ctl_close(ctl);
261         }
262
263         return ret;
264 }