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