-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio_engine.cpp
270 lines (246 loc) · 7.57 KB
/
audio_engine.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
#include "PAZ_Audio"
#include "audio_engine.hpp"
#include "detect_os.hpp"
#ifdef PAZ_MACOS
#include <CoreAudio/CoreAudio.h>
#include <AudioUnit/AudioUnit.h>
#else
#include <portaudio.h>
#ifdef PAZ_LINUX
#include <stdarg.h> // Some versions of error.h don't include this
#include <alsa/error.h> // Just for error redirection below
#endif
#endif
#include <thread>
#include <mutex>
#include <condition_variable>
#include <cmath>
#include <stdexcept>
static constexpr double SampleRate = 44'100.;
#ifndef PAZ_MACOS
static constexpr unsigned long FramesPerBuf = 1024;
#endif
#ifdef PAZ_MACOS
static AudioComponent _outputComp;
static AudioComponentInstance _outputInstance;
#else
static PaStream* _stream;
#endif
static std::mutex _mx;
static std::condition_variable _cv;
static bool _bufComplete;
static std::array<std::uint8_t, 2> _masterVol;
static std::array<double, 2> _masterFreqScale = {1, 1};
// [samplesPtr, bufStartIndices, loop]
static std::vector<std::tuple<std::uintptr_t, std::array<std::size_t, 2>, bool>>
_activeTracks;
#ifdef PAZ_MACOS
static OSStatus audio_callback_stereo(void*, AudioUnitRenderActionFlags*, const
AudioTimeStamp*, UInt32, UInt32 framesPerBuffer, AudioBufferList* buffers)
{
auto* out = static_cast<float*>(buffers->mBuffers[0].mData);
#else
static int audio_callback_stereo(const void*, void* outBuf, unsigned long
framesPerBuffer, const PaStreamCallbackTimeInfo*, PaStreamCallbackFlags,
void*)
{
auto* out = static_cast<float*>(outBuf);
#endif
static std::array<std::uint8_t, 2> vol;
std::fill(out, out + 2*framesPerBuffer, 0);
std::lock_guard<std::mutex> lk(_mx);
for(unsigned long i = 0; i < framesPerBuffer; ++i)
{
for(const auto& n : _activeTracks)
{
const auto* samples = reinterpret_cast<const std::vector<float>*>(
std::get<0>(n));
for(int k = 0; k < 2; ++k)
{
const std::size_t idx = std::round(std::get<1>(n)[k] + i*
_masterFreqScale[k]);
out[2*i + k] += (*samples)[idx%samples->size()];
}
}
for(int j = 0; j < 2; ++j)
{
if(vol[j] < _masterVol[j])
{
++vol[j];
}
else if(vol[j] > _masterVol[j])
{
--vol[j];
}
const float v = vol[j]/255.;
out[2*i + j] = std::max(-1.f, std::min(1.f, out[2*i + j]*v*v));
}
}
for(auto& n : _activeTracks)
{
for(int k = 0; k < 2; ++k)
{
std::get<1>(n)[k] = static_cast<std::size_t>(std::round(std::get<1>(
n)[k] + framesPerBuffer*_masterFreqScale[k]))%reinterpret_cast<
const std::vector<float>*>(std::get<0>(n))->size();
}
}
if(!_bufComplete)
{
_bufComplete = true;
_cv.notify_all();
}
#ifdef PAZ_MACOS
return noErr;
#else
return 0;
#endif
}
paz::AudioInitializer& paz::init_audio()
{
static AudioInitializer initializer;
return initializer;
}
#ifdef PAZ_LINUX
static void alsa_error_handler(const char*, int, const char*, int, const char*,
...) {}
#endif
paz::AudioInitializer::AudioInitializer()
{
#ifdef PAZ_MACOS
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
_outputComp = AudioComponentFindNext(nullptr, &desc);
if(!_outputComp || AudioComponentInstanceNew(_outputComp, &_outputInstance))
{
throw std::runtime_error("Failed to open default audio device.");
}
if(AudioUnitInitialize(_outputInstance))
{
throw std::runtime_error("Failed to initialize audio unit instance.");
}
AudioStreamBasicDescription streamFormat;
streamFormat.mSampleRate = SampleRate;
streamFormat.mFormatID = kAudioFormatLinearPCM;
streamFormat.mFormatFlags = kAudioFormatFlagIsFloat;
streamFormat.mFramesPerPacket = 1;
streamFormat.mChannelsPerFrame = 2;
streamFormat.mBitsPerChannel = 32;
streamFormat.mBytesPerPacket = 2*sizeof(float);
streamFormat.mBytesPerFrame = 2*sizeof(float);
if(AudioUnitSetProperty(_outputInstance, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input, 0, &streamFormat, sizeof(streamFormat)))
{
throw std::runtime_error("Failed to set audio unit input property.");
}
AURenderCallbackStruct callback;
callback.inputProc = audio_callback_stereo;
if(AudioUnitSetProperty(_outputInstance,
kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0,
&callback, sizeof(AURenderCallbackStruct)))
{
throw std::runtime_error("Failed to attach an IOProc to the selected au"
"dio unit.");
}
if(AudioOutputUnitStart(_outputInstance))
{
throw std::runtime_error("Failed to start audio unit.");
}
#else
#ifdef PAZ_LINUX
// Redirect ALSA output on PortAudio initialization.
snd_lib_error_set_handler(alsa_error_handler);
#endif
PaError error;
error = Pa_Initialize();
if(error != paNoError)
{
throw std::runtime_error("Failed to initialize PortAudio: " + std::
string(Pa_GetErrorText(error)));
}
const auto numDevices = Pa_GetDeviceCount();
if(numDevices < 0)
{
throw std::runtime_error("Failed to get number of audio devices: " +
std::string(Pa_GetErrorText(numDevices)));
}
if(!numDevices)
{
throw std::runtime_error("No audio devices found.");
}
error = Pa_OpenDefaultStream(&_stream, 0, 2, paFloat32, SampleRate,
FramesPerBuf, audio_callback_stereo, nullptr);
if(error != paNoError)
{
throw std::runtime_error("Failed to open audio stream: " + std::string(
Pa_GetErrorText(error)));
}
error = Pa_StartStream(_stream);
if(error != paNoError)
{
throw std::runtime_error("Failed to start audio stream: " + std::string(
Pa_GetErrorText(error)));
}
#endif
// Wait for first buffer to be completed.
{
std::unique_lock<std::mutex> lk(_mx);
_cv.wait(lk, [](){ return _bufComplete; });
}
}
paz::AudioInitializer::~AudioInitializer()
{
#ifdef PAZ_MACOS
AudioOutputUnitStop(_outputInstance);
AudioComponentInstanceDispose(_outputInstance);
#else
Pa_StopStream(_stream);
Pa_CloseStream(_stream);
Pa_Terminate();
#endif
}
void paz::AudioEngine::Play(const paz::AudioTrack& track, bool loop)
{
init_audio();
if(!loop) throw std::logic_error("NOT IMPLEMENTED");
std::thread([track, loop]()
{
std::lock_guard<std::mutex> lk(_mx);
_activeTracks.emplace_back(reinterpret_cast<std::uintptr_t>(track.
_samples.get()), std::array<std::size_t, 2>{}, loop);
}
).detach();
}
void paz::AudioEngine::SetVolume(double vol, int ear)
{
vol = std::max(0., std::min(1., vol));
if(ear < 0)
{
std::lock_guard<std::mutex> lk(_mx);
_masterVol[0] = std::round(vol*255.);
_masterVol[1] = std::round(vol*255.);
}
else if(ear == 0 || ear == 1)
{
std::lock_guard<std::mutex> lk(_mx);
_masterVol[ear] = std::round(vol*255.);
}
}
void paz::AudioEngine::SetFreqScale(double scale, int ear)
{
if(ear < 0)
{
std::lock_guard<std::mutex> lk(_mx);
_masterFreqScale[0] = scale;
_masterFreqScale[1] = scale;
}
else if(ear == 0 || ear == 1)
{
std::lock_guard<std::mutex> lk(_mx);
_masterFreqScale[ear] = scale;
}
}