-
Notifications
You must be signed in to change notification settings - Fork 3
/
audiodevice.cpp
461 lines (377 loc) · 12.7 KB
/
audiodevice.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#include "precomp.h"
#include "audiodevice.h"
#include "logger.h"
#include <system_error>
#include <thread>
namespace {
#ifdef HAVE_ALSA
snd_pcm_format_t SampleFormatToASound(SampleFormat sf)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
const bool littleEndian = true;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
const bool littleEndian = false;
#elif
#error "__BYTE_ORDER__ not defined"
#endif
snd_pcm_format_t sndFormat = SND_PCM_FORMAT_UNKNOWN;
switch(sf)
{
case SF_FMT_U8:
sndFormat = SND_PCM_FORMAT_U8;
break;
case SF_FMT_S16:
sndFormat = littleEndian ? SND_PCM_FORMAT_S16_LE : SND_PCM_FORMAT_S16_BE;
break;
case SF_FMT_S32:
sndFormat = littleEndian ? SND_PCM_FORMAT_S32_LE : SND_PCM_FORMAT_S32_BE;
break;
case SF_FMT_FLOAT:
sndFormat = littleEndian ? SND_PCM_FORMAT_FLOAT_LE : SND_PCM_FORMAT_FLOAT_BE;
break;
case SF_FMT_DOUBLE:
sndFormat = littleEndian ? SND_PCM_FORMAT_FLOAT64_LE : SND_PCM_FORMAT_FLOAT64_BE;
break;
default:
break;
}
return sndFormat;
}
#endif
}
namespace audiodevice
{
#ifdef HAVE_ALSA
Result Create(Device*& device)
{
Result result;
device = new Device();
int err = snd_pcm_open(&device->playbackHandle, "default", SND_PCM_STREAM_PLAYBACK, 0);
if( err < 0 )
{
result = Result(false, "Cannot open audio device %s", snd_strerror(err));
return result;
}
return result;
}
void Destroy(Device*& device)
{
snd_pcm_close(device->playbackHandle);
delete device;
device = nullptr;
}
Result SetInputFormat(Device* device, uint32_t channels, uint32_t sampleRate, SampleFormat sampleFormat)
{
Result result;
assert(device);
if(!device)
{
result = Result(false, "Invalid audiodevice");
}
snd_pcm_hw_params_t* hwParams = nullptr;
int err = snd_pcm_hw_params_malloc(&hwParams);
if( err < 0 )
{
result = Result(false, "Cannot allocate hardware parameter structure %s", snd_strerror(err));
return result;
}
err = snd_pcm_hw_params_any(device->playbackHandle, hwParams);
if( err < 0 )
{
result = Result(false, "Cannot initialize parameter structure %s", snd_strerror(err));
return result;
}
err = snd_pcm_hw_params_set_access(device->playbackHandle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED);
if( err < 0 )
{
result = Result(false, "Cannot set access type %s", snd_strerror(err));
return result;
}
err = snd_pcm_hw_params_set_format (device->playbackHandle, hwParams,SampleFormatToASound(sampleFormat));
if( err < 0 )
{
result = Result(false, "Cannot set sample format %s", snd_strerror(err));
return result;
}
err = snd_pcm_hw_params_set_rate_near(device->playbackHandle, hwParams, &sampleRate, 0);
if( err < 0 )
{
result = Result(false, "Cannot set sample rate %s", snd_strerror(err));
return result;
}
err = snd_pcm_hw_params_set_channels(device->playbackHandle, hwParams, channels);
if( err < 0 )
{
result = Result(false, "Cannot set channel count %s", snd_strerror(err));
return result;
}
err = snd_pcm_hw_params(device->playbackHandle, hwParams);
if( err < 0 )
{
result = Result(false, "Cannot set parameters %s", snd_strerror(err));
return result;
}
snd_pcm_hw_params_free(hwParams);
err = snd_pcm_prepare(device->playbackHandle);
if( err < 0 )
{
result = Result(false, "Cannot prepare audio interface for use %s", snd_strerror(err));
return result;
}
err = snd_pcm_hw_params_can_pause(hwParams);
if( err != 1 ) // can pause
{
result = Result(false, "Cannot prepare audio interface for use since it cannot pause.");
return result;
}
return result;
}
Result StartWhenReady(Device* device)
{
Result result;
while( snd_pcm_state(device->playbackHandle) != SND_PCM_STATE_RUNNING )
{
std::this_thread::yield();
}
return result;
}
Result WriteInterleaved(Device* device, void* buf, uint32_t frames, std::atomic<bool>& bufferInUse)
{
Result result;
assert(device);
if(!device)
{
return Result(false, "Invalid audiodevice");
}
bufferInUse = false;
snd_pcm_sframes_t written = snd_pcm_writei(device->playbackHandle, buf, frames);
if( written < 0 )
{
snd_pcm_prepare(device->playbackHandle);
result = Result(false, "Audio write failed %s", snd_strerror(written));
}
return result;
}
Result Flush(Device* device)
{
Result result;
assert(device);
if(!device)
{
result = Result(false, "Invalid audiodevice");
}
int err = snd_pcm_drop(device->playbackHandle);
if( err < 0 )
{
result = Result(false, "Cannot prepare audio interface for use %s", snd_strerror(err));
return result;
}
err = snd_pcm_prepare(device->playbackHandle);
if( err < 0 )
{
result = Result(false, "Cannot prepare audio interface for use %s", snd_strerror(err));
return result;
}
return result;
}
Result Pause(Device* device)
{
Result result;
assert(device);
if(!device)
{
result = Result(false, "Invalid audiodevice");
}
int err = snd_pcm_pause(device->playbackHandle,1);
if( err < 0 )
{
result = Result(false, "Cannot prepare audio interface for use %s", snd_strerror(err));
return result;
}
return result;
}
Result Resume(Device* device)
{
Result result;
assert(device);
if(!device)
{
result = Result(false, "Invalid audiodevice");
}
int err = snd_pcm_pause(device->playbackHandle,0);
if( err < 0 )
{
result = Result(false, "Cannot prepare audio interface for use %s", snd_strerror(err));
return result;
}
return result;
}
#endif
#ifdef WIN32
class Audio2VoiceCallback : public IXAudio2VoiceCallback
{
public:
Audio2VoiceCallback() {}
~Audio2VoiceCallback() {}
//Called when the voice has just finished playing a contiguous audio stream.
void OnStreamEnd() { }
void OnVoiceProcessingPassEnd() { }
void OnVoiceProcessingPassStart(UINT32 SamplesRequired) { }
void OnBufferEnd(void* pBufferContext)
{
std::atomic<bool>* bufferInUse = reinterpret_cast<std::atomic<bool>*>(pBufferContext);
*bufferInUse = false;
}
void OnBufferStart(void* pBufferContext) { }
void OnLoopEnd(void* pBufferContext) { }
void OnVoiceError(void* pBufferContext, HRESULT Error) { }
};
Result Create(Device*& device)
{
Result result;
HRESULT hr;
if (FAILED(hr = CoInitialize(nullptr)))
{
return Result(false, "CoInitialize failed. Error: %s", std::system_category().message(hr).c_str());
}
device = new Device();
memset(device, 0, sizeof(Device));
if (FAILED(hr = XAudio2Create(&device->xaudioHandle, 0, XAUDIO2_DEFAULT_PROCESSOR)))
{
return Result(false, "XAudio2Create failed. Error: %s", std::system_category().message(hr).c_str());
}
return result;
}
Result SetInputFormat(Device* device, uint32_t channels, uint32_t sampleRate, SampleFormat sampleFormat)
{
Result result;
HRESULT hr;
if (FAILED(hr = device->xaudioHandle->CreateMasteringVoice(&device->masterVoice, channels, sampleRate, 0, 0, 0)))
{
return Result(false, "CreateMasteringVoice failed. Error: %s", std::system_category().message(hr).c_str());
}
WAVEFORMATEX& wfx = device->wfx;
wfx.nChannels = channels;
wfx.nSamplesPerSec = sampleRate;
switch (sampleFormat)
{
case SF_FMT_U8:
wfx.wBitsPerSample = 8;
wfx.wFormatTag = WAVE_FORMAT_PCM;
break;
case SF_FMT_S16:
wfx.wBitsPerSample = 16;
wfx.wFormatTag = WAVE_FORMAT_PCM;
break;
case SF_FMT_S32:
wfx.wBitsPerSample = 32;
wfx.wFormatTag = WAVE_FORMAT_PCM;
break;
case SF_FMT_FLOAT:
wfx.wBitsPerSample = 32;
wfx.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
break;
case SF_FMT_DOUBLE:
wfx.wBitsPerSample = 64;
wfx.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
break;
case SF_FMT_INVALID:
return Result(false, "Invalid Sample Format.");
}
wfx.nBlockAlign = wfx.nChannels * (wfx.wBitsPerSample / 8);
wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
wfx.cbSize = 0;
device->voiceCallbacks = new Audio2VoiceCallback();
if (FAILED(hr = device->xaudioHandle->CreateSourceVoice(&device->sourceVoice, (WAVEFORMATEX*)&wfx, 0, 2.0f, device->voiceCallbacks)))
{
return Result(false, "CreateSourceVoice failed. Error: %s", std::system_category().message(hr).c_str());
}
return result;
}
Result WriteInterleaved(Device* device, void* buf, uint32_t nbSamples, std::atomic<bool>& bufferInUse)
{
const uint32_t sleepTimeOnErrorMMS = 100;
Result result;
const WAVEFORMATEX& wfx = device->wfx;
XAUDIO2_BUFFER buffer;
memset(&buffer, 0, sizeof(XAUDIO2_BUFFER));
buffer.AudioBytes = nbSamples * wfx.nChannels * wfx.wBitsPerSample / 8;
buffer.pAudioData = reinterpret_cast<BYTE*>(buf);
buffer.pContext = &bufferInUse;
bufferInUse = true;
HRESULT hr;
do
{
if (FAILED(hr = device->sourceVoice->SubmitSourceBuffer(&buffer)) && hr != XAUDIO2_E_INVALID_CALL)
{
return Result(false, "SubmitSourceBuffer failed. Error: %s", std::system_category().message(hr).c_str());
}
if (FAILED(hr))
{
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTimeOnErrorMMS));
}
} while (hr == XAUDIO2_E_INVALID_CALL);
return result;
}
Result StartWhenReady(Device* device)
{
const uint32_t REQUIRED_BUFFERS = 5;
Result result;
HRESULT hr;
XAUDIO2_VOICE_STATE state;
do
{
device->sourceVoice->GetState(&state, 0);
} while (state.BuffersQueued < REQUIRED_BUFFERS);
if (FAILED(hr = device->sourceVoice->Start()))
{
return Result(false, "Start failed. Error: %s", std::system_category().message(hr).c_str());
}
return result;
}
Result Pause(Device* device)
{
Result result;
HRESULT hr;
if (FAILED(hr = device->sourceVoice->Stop()))
{
return Result(false, "Stop failed. Error: %s", std::system_category().message(hr).c_str());
}
return result;
}
Result Resume(Device* device)
{
Result result;
HRESULT hr;
if (FAILED(hr = device->sourceVoice->Start()))
{
return Result(false, "Start failed. Error: %s", std::system_category().message(hr).c_str());
}
return result;
}
Result Flush(Device* device)
{
if (!device->sourceVoice)
{
return Result(false, "audiodevice::Drop Cannot drop sinnce audio is not configure yet.");
}
Result result;
HRESULT hr;
if (FAILED(hr = device->sourceVoice->FlushSourceBuffers()))
{
return Result(false, "FlushSourceBuffers failed. Error: %s", std::system_category().message(hr).c_str());
}
return result;
}
void Destroy(Device*& device)
{
if (device)
{
device->xaudioHandle->Release();
delete device->voiceCallbacks;
delete device;
device = nullptr;
}
}
#endif
}