-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPluginProcessor.cpp
More file actions
385 lines (332 loc) · 13.7 KB
/
PluginProcessor.cpp
File metadata and controls
385 lines (332 loc) · 13.7 KB
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
#include "PluginProcessor.h"
#include "PluginEditor.h"
#include "MovementIn.h"
#include "SensorToAudio.cpp"
#include "Logger.h"
//==============================================================================
EnvironmentalInstrumentsAudioProcessor::EnvironmentalInstrumentsAudioProcessor()
: AudioProcessor (
BusesProperties().withOutput("Output", juce::AudioChannelSet::stereo(), true)),
movementIn(std::make_unique<MovementIn>(*this)),
sensorToAudio(std::make_unique<SensorToAudio>(*movementIn))
{
// Set up the bus layout for standalone and plugin modes
BusesLayout layout;
if (wrapperType == AudioProcessor::WrapperType::wrapperType_Standalone)
{
// Stereo for the standalone
layout.outputBuses.add(juce::AudioChannelSet::stereo());
}
else
{
// Otherwise, mono output for plugin versions
layout.outputBuses.add(juce::AudioChannelSet::mono());
}
setBusesLayout(layout);
logMessage("Version " + std::to_string(PROJECT_VERSION_MAJOR) + "."
+ std::to_string(PROJECT_VERSION_MINOR) + "."
+ std::to_string(PROJECT_VERSION_PATCH));
// Show build info to make sure we actually built
logMessage("Build " __DATE__ " " __TIME__ " " CMAKE_BUILD_TYPE);
// tell OpenMP (libtorch) threads to not spin CPU when doing nothing
setenv("OMP_WAIT_POLICY", "PASSIVE", 1);
backend = std::make_unique<Backend>();
logMessage("backend initialized...");
}
EnvironmentalInstrumentsAudioProcessor::~EnvironmentalInstrumentsAudioProcessor()
{
movementIn->stopPolling();
}
//==============================================================================
const juce::String EnvironmentalInstrumentsAudioProcessor::getName() const
{
return JucePlugin_Name;
}
bool EnvironmentalInstrumentsAudioProcessor::acceptsMidi() const
{
#if JucePlugin_WantsMidiInput
return true;
#else
return false;
#endif
}
bool EnvironmentalInstrumentsAudioProcessor::producesMidi() const
{
#if JucePlugin_ProducesMidiOutput
return true;
#else
return false;
#endif
}
bool EnvironmentalInstrumentsAudioProcessor::isMidiEffect() const
{
#if JucePlugin_IsMidiEffect
return true;
#else
return false;
#endif
}
double EnvironmentalInstrumentsAudioProcessor::getTailLengthSeconds() const
{
return 0.0;
}
int EnvironmentalInstrumentsAudioProcessor::getNumPrograms()
{
return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs,
// so this should be at least 1, even if you're not really implementing programs.
}
int EnvironmentalInstrumentsAudioProcessor::getCurrentProgram()
{
return 0;
}
void EnvironmentalInstrumentsAudioProcessor::setCurrentProgram (int index)
{
juce::ignoreUnused (index);
}
const juce::String EnvironmentalInstrumentsAudioProcessor::getProgramName (int index)
{
juce::ignoreUnused (index);
return {};
}
void EnvironmentalInstrumentsAudioProcessor::changeProgramName (int index, const juce::String& newName)
{
juce::ignoreUnused (index, newName);
}
bool EnvironmentalInstrumentsAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const
{
// This is the place where you check if the layout is supported.
// In this template code we only support mono or stereo.
// Some plugin hosts, such as certain GarageBand versions, will only
// load plugins that support stereo bus layouts.
if (layouts.getMainOutputChannelSet() != juce::AudioChannelSet::mono()
&& layouts.getMainOutputChannelSet() != juce::AudioChannelSet::stereo())
return false;
return true;
}
//==============================================================================
void EnvironmentalInstrumentsAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock)
{
auto logger = Logger::getLogger();
static auto spid = Logger::createSignpost();
movementIn->startPolling();
// pre-playback initialisation
audioBufferNumSamples = samplesPerBlock;
// Load model
juce::File modelFile = juce::File::getSpecialLocation(juce::File::currentExecutableFile)
.getParentDirectory()
.getParentDirectory()
.getChildFile("Resources/cornellbird_causal_epoch373_0.99.ts");
if (modelFile.existsAsFile())
{
if (backend->load(modelFile.getFullPathName().toStdString()))
logMessage("Model load error.");
else
logMessage("Model loaded.");
}
else
{
logMessage("Model file not found!");
}
if (!backend->is_loaded()) return;
auto modelParams = backend->get_method_params("decode");
// Get from model params
sizeModelWindow = modelParams[1];
assert(sizeModelWindow > 0);
modelOutputChannels = modelParams[2];
backend->prepare(modelOutputChannels, "decode");
int modelInputDim = modelParams[0];
// size of buffers
// - input ceiling(audioBufferNumSamples/sizeModelWindow)
// - output ceiling(audioBufferNumSamples/sizeModelWindow) * sizeModelWindow
// Pre-allocate model in/out buffers
int bs = (audioBufferNumSamples + sizeModelWindow - 1) / sizeModelWindow;
modelInput.setSize(modelInputDim, bs);
modelOutput.setSize(modelOutputChannels, bs * sizeModelWindow);
// This will be transferred to audio out when model runs, so shouldn't contain garbage
modelOutput.clear();
// initialize model out buffer
modelOutputBuffer = std::make_unique<circular_buffer<float>[]>(static_cast<size_t>(modelOutputChannels));
for (int c(0); c < modelOutputChannels; c++)
// make sure buffer is big enough to store model window and audio buffer plus some (to allow for audio callback jitter)
modelOutputBuffer[static_cast<size_t>(c)].initialize(static_cast<size_t>(bs * sizeModelWindow * 2));
// Pre-allocate pointer vectors with number of channels
modelInputPts.reserve(static_cast<size_t>(modelInputDim));
modelOutputPts.reserve(static_cast<size_t>(modelOutputChannels));
modelInputPts.clear();
modelOutputPts.clear();
// Fill with pointers to model buffers
for (int c = 0; c < modelInputDim; ++c)
{
modelInputPts.push_back(const_cast<float*>(modelInput.getReadPointer(c)));
}
for (int c = 0; c < modelOutputChannels; ++c)
{
modelOutputPts.push_back(modelOutput.getWritePointer(c));
}
// prepare to fill circular buffer with sensor data
sensorToAudio->prepareToPlay(sampleRate, sizeModelWindow, audioBufferNumSamples);
runAudio = false;
// flush some water through the model to clear the pipes
for (int i(0); i < 3; i++)
{
os_signpost_interval_begin(logger, spid, "Model warmup run", "");
backend->perform(modelInputPts, modelOutputPts, 1, "decode", 1);
os_signpost_interval_end(logger, spid, "Model warmup run", "");
}
shouldStopBackend = false;
backendThread = std::make_unique<std::thread>(
&EnvironmentalInstrumentsAudioProcessor::runBackend,
this
);
sensorToAudio->startPolling();
}
void EnvironmentalInstrumentsAudioProcessor::releaseResources()
{
auto logger = Logger::getLogger();
static auto spid = Logger::createSignpost();
os_signpost_interval_begin(logger, spid, "AudioProcessor release resources", "");
shouldStopBackend = true;
sensorToAudio->stopPolling();
if (backendThread && backendThread->joinable())
{
os_signpost_interval_begin(logger, spid, "AudioProcessor join backend thread", "");
backendThread->join();
os_signpost_interval_end(logger, spid, "AudioProcessor join backend thread", "");
backendThread.reset();
}
os_signpost_interval_end(logger, spid, "AudioProcessor release resources", "");
}
// run backend loop
void EnvironmentalInstrumentsAudioProcessor::runBackend()
{
auto logger = Logger::getLogger();
static auto spid = Logger::createSignpost();
int samplesRead;
while (!shouldStopBackend)
{
sensorToAudio->waitFlushBuffer(modelInput, samplesRead, shouldStopBackend);
if (shouldStopBackend)
return;
assert(samplesRead > 0);
os_signpost_interval_begin(logger, spid, "Process backend", "%d samples to process", samplesRead);
backend->perform(modelInputPts, modelOutputPts, samplesRead, "decode", 1);
os_signpost_interval_end(logger, spid, "Process backend", "");
// transfer from model out buffer to out circular buffer
// needs to be thread-safe
std::lock_guard<std::mutex> lock(mobLock);
for (int c(0); c < modelOutputChannels; c++)
modelOutputBuffer[static_cast<size_t>(c)].put(modelOutput.getReadPointer(c), samplesRead * sizeModelWindow);
}
}
void EnvironmentalInstrumentsAudioProcessor::processBlock (juce::AudioBuffer<float>& outBuffer,
juce::MidiBuffer& midiMessages)
{
juce::ignoreUnused (midiMessages);
juce::ScopedNoDenormals noDenormals;
auto logger = Logger::getLogger();
static auto spid = Logger::createSignpost();
if (!backend->is_loaded())
{
outBuffer.clear();
return;
}
{
std::lock_guard<std::mutex> lock(mobLock);
mobAvailable = static_cast<int>(modelOutputBuffer[0].size());
// wait until circular buffer can fill audio buffer to start consuming
if (!runAudio)
{
if (mobAvailable >= audioBufferNumSamples)
{
runAudio = true;
os_signpost_event_emit(logger, spid, "Audio playback started", "");
}
}
if (runAudio)
{
// transfer from out circular buffer to audio out buffer
for (int c(0); c < outBuffer.getNumChannels(); c++)
{
// check if our output channel is greater than channels supplied by model output
if (c >= modelOutputChannels)
// copy last channel supplied by model into all remaining channels
outBuffer.copyFrom(c, 0, outBuffer, c - 1, 0, audioBufferNumSamples);
else
modelOutputBuffer[static_cast<size_t>(c)].get(outBuffer.getWritePointer(c), audioBufferNumSamples);
}
// if buffer runs out, sensorToAudio has stopped supplying, so wait again
if (mobAvailable < audioBufferNumSamples)
{
runAudio = false;
os_signpost_event_emit(logger, spid, "Buffer underrun, audio playback stopped", "");
}
}
}
}
//==============================================================================
bool EnvironmentalInstrumentsAudioProcessor::hasEditor() const
{
return true; // (change this to false if you choose to not supply an editor)
}
juce::AudioProcessorEditor* EnvironmentalInstrumentsAudioProcessor::createEditor()
{
return new EnvironmentalInstrumentsAudioProcessorEditor (*this);
}
//==============================================================================
void EnvironmentalInstrumentsAudioProcessor::getStateInformation (juce::MemoryBlock& destData)
{
// You should use this method to store your parameters in the memory block.
// You could do that either as raw data, or use the XML or ValueTree classes
// as intermediaries to make it easy to save and load complex data.
juce::ignoreUnused (destData);
}
void EnvironmentalInstrumentsAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
{
// You should use this method to restore your parameters from this memory block,
// whose contents will have been created by the getStateInformation() call.
juce::ignoreUnused (data, sizeInBytes);
}
EnvironmentalInstrumentsAudioProcessor::UIState EnvironmentalInstrumentsAudioProcessor::getLockUiState()
{
std::unique_lock<std::mutex> tempLock(uiStateMutex); // Lock the mutex
uiStateLock = std::move(tempLock); // Transfer ownership of the lock to the class member
return uiState;
}
EnvironmentalInstrumentsAudioProcessor::UIState EnvironmentalInstrumentsAudioProcessor::getUiState()
{
std::lock_guard<std::mutex> lock(uiStateMutex);
return uiState;
}
void EnvironmentalInstrumentsAudioProcessor::setEditor(EnvironmentalInstrumentsAudioProcessorEditor *editor)
{
pluginEditor = editor;
if (uiStateLock.owns_lock()) { // Check if it's currently locked
uiStateLock.unlock(); // Unlock the mutex
}
}
void EnvironmentalInstrumentsAudioProcessor::destroyEditor()
{
pluginEditor = nullptr;
}
void EnvironmentalInstrumentsAudioProcessor::logMessage(const juce::String &message)
{
juce::ScopedLock loglock(logLock);
std::lock_guard<std::mutex> uilock(uiStateMutex);
// append message to UI log text
uiState.logText += message + "\n";
// log to editor if exists
if (pluginEditor) pluginEditor->logMessage(message);
}
void EnvironmentalInstrumentsAudioProcessor::updateJoyConConnectionStatus(const bool leftJC, const bool rightJC)
{
std::lock_guard<std::mutex> lock(uiStateMutex);
uiState.lConnected = leftJC;
uiState.rConnected = rightJC;
if (pluginEditor) pluginEditor->showJCConnectionStatus();
}
//==============================================================================
// This creates new instances of the plugin..
juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
return new EnvironmentalInstrumentsAudioProcessor();
}