-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
testhappy-alsa.cpp
330 lines (220 loc) · 8.21 KB
/
testhappy-alsa.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// (C) 2022-2023 by folkert van heusden <[email protected]>, CC0 license
// This program interfaces to pulse-audio.
#include <condition_variable>
#include <cstring>
#include <queue>
#include <signal.h>
#include <unistd.h>
#include <alsa/asoundlib.h>
#include "sip.h"
typedef struct {
std::thread *rec_th; // recorder thread
std::mutex buffer_lock;
std::condition_variable_any buffer_cv;
int buffer_length;
std::queue<short *> buffers;
snd_pcm_t *capture_handle; // from alsa to voip
double t_avg = 0;
snd_pcm_t *play_handle; // from voip to alsa
std::atomic_bool *stop_flag;
} alsa_sessions_t;
snd_pcm_t *open_alsa_record(const std::string & dev_name, int *const frames)
{
snd_pcm_t *capture_handle { nullptr };
int err = snd_pcm_open(&capture_handle, dev_name.c_str(), SND_PCM_STREAM_CAPTURE, 0);
if (err < 0) {
fprintf(stderr, "cannot open audio device %s (%s)\n", dev_name.c_str(), snd_strerror(err));
return nullptr;
}
snd_pcm_hw_params_t *hw_params { nullptr };
err = snd_pcm_hw_params_malloc(&hw_params);
if (err < 0) {
fprintf(stderr, "cannot allocate hardware parameter structure (%s)\n", snd_strerror(err));
return nullptr;
}
err = snd_pcm_hw_params_any(capture_handle, hw_params);
if (err < 0) {
fprintf(stderr, "cannot initialize hardware parameter structure (%s)\n", snd_strerror(err));
return nullptr;
}
err = snd_pcm_hw_params_set_format(capture_handle, hw_params, SND_PCM_FORMAT_S16_LE);
if (err < 0) {
fprintf(stderr, "cannot set sample format (%s)\n", snd_strerror(err));
return nullptr;
}
unsigned rate = 44100;
err = snd_pcm_hw_params_set_rate_near(capture_handle, hw_params, &rate, 0);
if (err < 0) {
fprintf(stderr, "cannot set sample rate (%s)\n", snd_strerror(err));
return nullptr;
}
if (rate != 44100) {
fprintf(stderr, "audio device cannot handle 44100Hz\n");
return nullptr;
}
err = snd_pcm_hw_params_set_channels(capture_handle, hw_params, 1);
if (err < 0) {
fprintf(stderr, "cannot set channel count (%s)\n", snd_strerror(err));
return nullptr;
}
long unsigned temp_frames = *frames;
int dir { 0 };
snd_pcm_hw_params_set_period_size_near(capture_handle, hw_params, &temp_frames, &dir);
*frames = temp_frames;
printf("%d %d\n", *frames, dir);
err = snd_pcm_hw_params(capture_handle, hw_params);
if (err < 0) {
fprintf(stderr, "cannot set parameters (%s)\n", snd_strerror(err));
return nullptr;
}
snd_pcm_hw_params_free(hw_params);
err = snd_pcm_prepare(capture_handle);
if (err < 0) {
fprintf(stderr, "cannot prepare audio interface for use (%s)\n", snd_strerror(err));
return nullptr;
}
return capture_handle;
}
snd_pcm_t *open_alsa_play(const std::string & dev_name)
{
snd_pcm_t *play_handle { nullptr };
snd_pcm_hw_params_t *params { nullptr };
/* Open the PCM device in playback mode */
int err = snd_pcm_open(&play_handle, dev_name.c_str(), SND_PCM_STREAM_PLAYBACK, 0);
if (err < 0) {
printf("ERROR: Can't open \"%s\" PCM device %s\n", dev_name.c_str(), snd_strerror(err));
return nullptr;
}
snd_pcm_hw_params_alloca(¶ms);
snd_pcm_hw_params_any(play_handle, params);
err = snd_pcm_hw_params_set_format(play_handle, params, SND_PCM_FORMAT_S16_LE);
if (err < 0)
printf("ERROR: Can't set format %s\n", snd_strerror(err));
snd_pcm_hw_params_set_channels(play_handle, params, 1);
unsigned rate = 44100;
err = snd_pcm_hw_params_set_rate_near(play_handle, params, &rate, 0);
if (err < 0)
printf("ERROR: Can't set rate %s\n", snd_strerror(err));
snd_pcm_hw_params(play_handle, params);
return play_handle;
}
// invoked when a new session has started
// one can set 'session->private_data' to point to internal
// data of the callback. you need to free it yourself in
// e.g. the end_session callback.
bool cb_new_session(sip_session_t *const session, const std::string & from)
{
printf("cb_new_session, call-id: %s, caller: %s\n", session->call_id.c_str(), from.c_str());
session->private_data = new alsa_sessions_t;
alsa_sessions_t *p = reinterpret_cast<alsa_sessions_t *>(session->private_data);
p->buffer_length = 44100 * session->schema.frame_duration / 1000;
printf("buffer length: %d, frame size: %d, frame duration %d\n", p->buffer_length, session->schema.frame_size, session->schema.frame_duration);
// TODO handle errors
p->capture_handle = open_alsa_record("default", &p->buffer_length);
if (!p->capture_handle)
return false;
p->play_handle = open_alsa_play("default");
if (!p->play_handle)
return false;
p->stop_flag = &session->stop_flag;
p->rec_th = nullptr;
return true;
}
// invoked when the peer produces audio and which is then
// received by us
bool cb_recv(const short *const samples, const size_t n_samples, sip_session_t *const session)
{
alsa_sessions_t *p = reinterpret_cast<alsa_sessions_t *>(session->private_data);
double gain_n_samples = 300.0 / session->schema.frame_duration; // calculate fragment over 300ms
// update moving average for gain
double avg = 0;
for(size_t i=0; i<n_samples; i++)
avg += samples[i];
avg /= p->buffer_length;
p->t_avg = (p->t_avg * gain_n_samples + avg) / (gain_n_samples + 1);
// apply
double gain = std::max(1.5, std::min(5.0, 32767 / std::max(1.0, p->t_avg)));
// TODO clamp to -1...1
for(size_t i=0; i<n_samples; i++)
((short *)samples)[i] *= gain;
int err = snd_pcm_writei(p->play_handle, samples, n_samples);
if (err == -EPIPE) {
snd_pcm_prepare(p->play_handle);
}
else if (err < 0) {
printf("ERROR Can't write to PCM device %s\n", snd_strerror(err));
return false;
}
return true;
}
// invoked when the library wants to send audio to
// the peer
bool cb_send(short **const samples, size_t *const n_samples, sip_session_t *const session)
{
alsa_sessions_t *p = reinterpret_cast<alsa_sessions_t *>(session->private_data);
if (p->rec_th == nullptr) {
p->rec_th = new std::thread([p, session]() {
while(!*p->stop_flag) {
short *buffer = new short[p->buffer_length];
int err = snd_pcm_readi(p->capture_handle, buffer, p->buffer_length);
if (err < 0)
fprintf(stderr, "read %d frames from audio interface failed (%s)\n", p->buffer_length, snd_strerror(err));
std::unique_lock<std::mutex> lck(p->buffer_lock);
p->buffers.push(buffer);
p->buffer_cv.notify_all();
}
});
}
std::unique_lock<std::mutex> lck(p->buffer_lock);
using namespace std::chrono_literals;
while(p->buffers.empty()) {
p->buffer_cv.wait_for(lck, 500ms);
if (*p->stop_flag) {
printf("cb_send: terminate by stop_flag\n");
return false;
}
}
*samples = p->buffers.front();
p->buffers.pop();
*n_samples = p->buffer_length;
return true;
}
// called when we receive a 'BYE' from the peer (and
// the session thus ends)
void cb_end_session(sip_session_t *const session)
{
printf("cb_end_session, call-id: %s\n", session->call_id.c_str());
alsa_sessions_t *p = reinterpret_cast<alsa_sessions_t *>(session->private_data);
session->stop_flag = true;
p->rec_th->join();
delete p->rec_th;
while(p->buffers.empty() == false) {
delete [] p->buffers.front();
p->buffers.pop();
}
snd_pcm_close(p->play_handle);
snd_pcm_close(p->capture_handle);
delete p;
}
bool cb_dtmf(const uint8_t dtmf_code, const bool is_end, const uint8_t volume, sip_session_t *const session)
{
printf("DTMF pressed: %d\n", dtmf_code);
return true;
}
void sigh(int sig)
{
}
int main(int argc, char *argv[])
{
signal(SIGINT, sigh);
// filename, loglevel for logging to file, level for logging to screen
// levels: debug, info, warning, ll_error
setlog("/tmp/testhappy.log", warning, debug);
// remote ip (IP address of upstream asterisk server), my extension-number, my password, my ip, my sip port, samplerate-used-by-callbacks, [callbacks...], pointer to global private data (or nullptr)
// note: 'my ip' is only required when the library cannot figure out what IP address to use to contact the SIP server. This can happen when there's a NAT router in between for example.
sip s("192.168.64.1", "9999", "1234", { }, 5060, 60, 44100, cb_new_session, cb_recv, cb_send, cb_end_session, cb_dtmf, nullptr);
// sip s("10.208.11.13", "3535", "1234", { }, 5060, 60, 44100, cb_new_session, cb_recv, cb_send, cb_end_session, cb_dtmf, nullptr);
// do whatever you like here
pause();
return 0;
}