-
Notifications
You must be signed in to change notification settings - Fork 0
/
host.cpp
352 lines (255 loc) · 11.4 KB
/
host.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
#include "host.h"
#include "node.h"
#include "vstnode.h"
#include "mixernode.h"
// bits for hi-res timing on Mac
#include <CoreServices/CoreServices.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
namespace En
{
Host::Host(NodeGroup* rootGroup)
: m_ioDevice(0)
, m_audioOutput(0)
, m_timer(0)
, m_globalSampleIndex(0)
, m_rootGroup(rootGroup)
, m_lastProfiledTime(0)
, m_busyAccumulatedTime(0)
{
rootGroup->setHost(this);
init();
}
Host::~Host()
{
delete m_audioOutput;
}
void Host::init()
{
m_format.setSampleRate(44100);
m_format.setChannelCount(2);
m_format.setSampleSize(16);
m_format.setCodec("audio/pcm");
m_format.setByteOrder(QAudioFormat::LittleEndian);
m_format.setSampleType(QAudioFormat::SignedInt);
// TODO: Use QSettings for this
auto selectedDeviceName = "MOTU MicroBook II";
QAudioDeviceInfo selectedDeviceInfo = QAudioDeviceInfo::defaultInputDevice();
foreach (const auto &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)) {
if (deviceInfo.deviceName() == selectedDeviceName) {
selectedDeviceInfo = deviceInfo;
}
}
qDebug() << "Device name: " << selectedDeviceInfo.deviceName();
qDebug() << "Supported channel count: " << selectedDeviceInfo.supportedChannelCounts();
m_audioOutput = new QAudioOutput(selectedDeviceInfo, m_format, this);
const int bufferSizeSamples = 512;
m_audioOutput->setBufferSize(bufferSizeSamples * m_format.channelCount() * m_format.sampleSize() / 8);
//connect(m_audioOutput, SIGNAL(notify()), SLOT(notified()));
connect(m_audioOutput, SIGNAL(stateChanged(QAudio::State)), SLOT(stateChanged(QAudio::State)));
m_ioDevice = m_audioOutput->start();
qDebug() << m_audioOutput->error() << QAudio::NoError;
qDebug() << "buffer size (bytes)" << m_audioOutput->bufferSize();
qDebug() << "period size (bytes)" << m_audioOutput->periodSize();
m_blockSizeSamples = m_audioOutput->periodSize() / m_format.channelCount() / (m_format.sampleSize() / 8);
qDebug() << "block size (samples)" << m_blockSizeSamples;
m_nullInputBuffer.resize(m_blockSizeSamples);
Node::s_nullInputBuffer = nullInputBuffer();
//for (int i = 0; i < 4; ++i)
// m_floatBlock[i].resize(m_blockSizeSamples);
m_buffer.resize(m_audioOutput->periodSize());
m_timer = new QTimer(this);
m_timer->setSingleShot(true);
m_timer->setInterval(0);
connect(m_timer, SIGNAL(timeout()), this, SLOT(writeData()));
m_timer->start();
m_globalMidiDevice = new En::MidiDevice(this);
}
void Host::stop()
{
m_timer->stop();
}
void Host::writeData()
{
//QElapsedTimer elTimer;
//elTimer.start();
if (m_lastProfiledTime != 0) {
uint64_t thisTime = mach_absolute_time();
uint64_t elapsed = thisTime - m_lastProfiledTime;
Nanoseconds nanoNano = AbsoluteToNanoseconds(*(AbsoluteTime*)&elapsed);
uint64_t elapsedNano = *(uint64_t*)&nanoNano;
// once every second...
if (elapsedNano > 1e9) {
nanoNano = AbsoluteToNanoseconds(*(AbsoluteTime*)&m_busyAccumulatedTime);
uint64_t busyNano = *(uint64_t*)&nanoNano;
float utilisationAmount = (double)busyNano / elapsedNano;
emit utilisation(utilisationAmount);
m_lastProfiledTime = thisTime;
m_busyAccumulatedTime = 0;
}
} else {
m_lastProfiledTime = mach_absolute_time();
}
if (!m_audioOutput || m_audioOutput->state() == QAudio::StoppedState) {
return;
}
//qDebug() << "checking in writeData";
//qDebug() << "bytesFree" << m_audioOutput->bytesFree();
//qDebug() << "periodSize" << m_audioOutput->periodSize();
int chunks = m_audioOutput->bytesFree() / m_audioOutput->periodSize();
//qDebug() << "chunks" << chunks;
if (chunks > 0) {
uint64_t busyTimeStart = mach_absolute_time();
for (int i = 0; i < chunks; ++i) {
// generate a buffer and write it
// Temporary ppqPos implementation. This should be ultimately be coming from the sequencer.
s_vstTimeInfo.ppqPos = s_vstTimeInfo.samplePos / 44100 * s_vstTimeInfo.tempo / 60;
//qDebug() << "sample pos" << s_vstTimeInfo.samplePos;
//qDebug() << "ppq pos" << s_vstTimeInfo.ppqPos;
Node* outputNode = m_rootGroup->outputNode();
//qDebug() << "checkpoint before dep calc" << elTimer.restart();
struct DependencyVisitor: public Node::Visitor {
typedef QMap<Node*, QSet<Node*> > NodeRelationMap;
// any need to have these separate? could be a QPair?
NodeRelationMap dependencyMap;
NodeRelationMap dependentMap;
void visitRecurse(Node* node) {
if (dependencyMap.contains(node)) {
return;
}
dependencyMap[node];
dependentMap[node];
foreach (const auto& input, node->inputs()) {
if (!input) {
continue;
}
dependencyMap[node] << input;
dependentMap[input] << node;
visitRecurse(input);
}
//node->accept(*this);
}
// void visit(VstNode* vstNode) {
// //qDebug() << "Visiting VstNode*" << vstNode->displayLabel();
// Node* input = vstNode->input();
// if (input) {
// dependencyMap[static_cast<Node*>(vstNode)] << input;
// dependentMap[input] << static_cast<Node*>(vstNode);
// visitRecurse(input);
// }
// }
// void visit(MixerNode* mixerNode) {
// //qDebug() << "Visiting MixerNode*" << mixerNode->displayLabel();
// for (unsigned i = 0; i < mixerNode->numInputs(); ++i) {
// Node* input = mixerNode->input(i);
// dependencyMap[static_cast<Node*>(mixerNode)] << input;
// dependentMap[input] << static_cast<Node*>(mixerNode);
// visitRecurse(input);
// }
// }
} dependencyVisitor;
Q_FOREACH (Node* node, m_rootGroup->childNodes()) {
dependencyVisitor.visitRecurse(node);
}
//qDebug() << "checkpoint before executor" << elTimer.restart();
//outputNode->accept(dependencyVisitor);
// TODO: fix the above so it only happens when the graph changes. no need to recalculate dependencies on every single buffer generation
struct SerialNodeExecutor: public Node::Visitor {
DependencyVisitor& dependencyVisitor;
QSet<Node*> visited;
SerialNodeExecutor(DependencyVisitor& d) : dependencyVisitor(d) {}
void execute() {
//qDebug() << "------------------------";
//Q_FOREACH (DependencyVisitor::NodeRelationMap::const_iterator it, dependencyVisitor.dependencyMap) {
QQueue<Node*> nodeQueue;
DependencyVisitor::NodeRelationMap::const_iterator it = dependencyVisitor.dependencyMap.constBegin();
while (it != dependencyVisitor.dependencyMap.constEnd()) {
Node* node = it.key();
//qDebug() << "Dependencies of" << node->displayLabel();
//bool hasDeps = false;
//Q_FOREACH (Node* depNode, it.value()) {
//qDebug() << " -" << depNode->displayLabel();
//hasDeps = true;
//}
bool hasDeps = !it.value().isEmpty();
if (!hasDeps) {
nodeQueue.append(node);
}
++it;
}
//qDebug() << "------------------------";
Q_FOREACH (Node* node, nodeQueue) {
dispatch(node);
}
}
void dispatch(Node* node) {
if (visited.contains(node)) {
return;
}
visited << node;
node->accept(*this);
}
virtual void visit(Node* node)
{
//qDebug() << "visit" << node;
node->processAudio();
Q_FOREACH (Node* dependentNode, dependencyVisitor.dependentMap[node]) {
dispatch(dependentNode);
}
}
} executor(dependencyVisitor);
executor.execute();
//qDebug() << "checkpoint before buffer write" << elTimer.restart();
// FIXME: what if output node does not have 2 outputs? deal with it.
// convert float data buffers to our audio format
qint16* ptr = (qint16*)m_buffer.data();
if (!outputNode) {
m_buffer.fill(0);
} else {
// If channel count on node is 1, just use it for all channels
// Otherwise fill them up.
QList<const float*> channelBuffers;
if (outputNode->numOutputChannels() == 1) {
for (int i = 0; i < m_format.channelCount(); ++i) {
channelBuffers.push_back(outputNode->outputChannelBufferConst(0));
}
} else {
for (int i = 0; i < m_format.channelCount(); ++i) {
if (i < outputNode->numOutputChannels()) {
channelBuffers.push_back(outputNode->outputChannelBufferConst(i));
} else {
channelBuffers.push_back(Node::s_nullInputBuffer);
}
}
}
for (unsigned sampleIndex = 0; sampleIndex < m_blockSizeSamples; sampleIndex++) {
for (int channel = 0; channel < m_format.channelCount(); ++channel) {
float clamped = std::min(std::max(channelBuffers[channel][sampleIndex], -1.f), 1.f);
*ptr++ = qint16(clamped * 32767);
}
}
}
//qDebug("writing buffer");
qint64 written = m_ioDevice->write(m_buffer.data(), m_buffer.size());
Q_UNUSED(written);
//qDebug() << "checkpoint finish" << elTimer.restart();
//m_ioDevice->waitForBytesWritten(-1);
//qDebug("%lld bytes written!", written);
//qDebug() << "error state" << m_audioOutput->error() << QAudio::NoError;
// update vst time info struct
s_vstTimeInfo.samplePos += m_blockSizeSamples;
}
//quint64 elapsedBusy = m_profileTimer.restart();
//qDebug() << "Host was busy for" << elapsedBusy << "ms";
m_busyAccumulatedTime += (mach_absolute_time() - busyTimeStart);
} else {
// do nothing.
}
//qDebug() << "bytesFree = " << m_audioOutput->bytesFree();
m_timer->start();
}
void Host::stateChanged(QAudio::State state)
{
qDebug() << "State changed" << state;
}
} // namespace En;