iPlug2 - C++ Audio Plug-in Framework
Loading...
Searching...
No Matches
IPlugFaustGen.cpp
Go to the documentation of this file.
1/*
2 ==============================================================================
3
4 This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers.
5
6 See LICENSE.txt for more info.
7
8 ==============================================================================
9*/
10
16#ifndef FAUST_COMPILED
17
18#include "IPlugFaustGen.h"
19#include "IPlugUtilities.h"
20
21#include <algorithm>
22#include <filesystem>
23#include <fstream>
24#include <mutex>
25#include <sstream>
26
27#include "faust/dsp/interpreter-dsp.h"
28
29#ifdef OS_WIN
30 #include <windows.h>
31#endif
32
33using namespace iplug;
34
35namespace
36{
37 // The libfaust compiler API is not thread safe
38 std::mutex& GetCompileMutex()
39 {
40 static std::mutex sMutex;
41 return sMutex;
42 }
43
44 std::filesystem::path ToPath(const std::string& utf8Path)
45 {
46#if defined OS_WIN
47 return std::filesystem::u8path(utf8Path);
48#else
49 return std::filesystem::path(utf8Path);
50#endif
51 }
52
53 std::string ToUTF8(const std::filesystem::path& path)
54 {
55 const auto str = path.u8string(); // std::u8string in C++20
56 return std::string(str.begin(), str.end());
57 }
58
59 void LoadFaustLibrary()
60 {
61#if defined OS_WIN && defined FAUST_DLL_PATH
62 // faust.dll is delay-loaded, load it from the Faust installation the plug-in was built against
63 static HMODULE sModule = LoadLibraryExA(FAUST_DLL_PATH, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
64 assert(sModule && "Could not load faust.dll");
65#endif
66 }
67}
68
69FaustGen::FaustGen(const char* name, const char* inputDSPFile, int nVoices, const char* libraryPath)
70: IPlugFaust(name, nVoices)
71{
72 LoadFaustLibrary();
73
74 if (CStringHasContents(libraryPath))
75 AddLibraryPath(libraryPath);
76
77 if (CStringHasContents(inputDSPFile))
78 {
79 mDSPFile = inputDSPFile;
80 AddLibraryPath(ToUTF8(ToPath(mDSPFile).parent_path()).c_str());
81 }
82
83 if (sizeof(FAUSTFLOAT) == sizeof(double))
84 mCompileOptions.push_back("-double");
85}
86
87FaustGen::~FaustGen()
88{
89 SetAutoRecompile(false);
90
91 // DSP instances must be deleted before the factory that created them
92 ReleaseDSP();
93
94 if (mFactory)
95 {
96 std::lock_guard<std::mutex> lock(GetCompileMutex());
97 deleteInterpreterDSPFactory(mFactory);
98 }
99}
100
102{
103 bool success = false;
104
105 if (mDSPFile.size())
106 {
107 std::string sourceCode;
108
109 if (ReadFile(sourceCode))
110 success = Compile(sourceCode);
111 else
112 mErrorMessage = "Could not read " + mDSPFile;
113 }
114 else if (mSourceCode.size())
115 {
116 success = Compile(mSourceCode);
117 }
118
119 if (!success)
120 {
121 DBGMSG("FaustGen-%s: %s\n", mName.Get(), mErrorMessage.c_str());
122 CompileDefault();
123 }
124
125 OnCompiled(success);
126}
127
128bool FaustGen::LoadFile(const char* path)
129{
130 mDSPFile = path;
131 AddLibraryPath(ToUTF8(ToPath(mDSPFile).parent_path()).c_str());
132
133 std::string sourceCode;
134
135 if (!ReadFile(sourceCode))
136 {
137 mErrorMessage = "Could not read " + mDSPFile;
138 return false;
139 }
140
141 const bool success = Compile(sourceCode);
142
143 OnCompiled(success);
144
145 return success;
146}
147
148bool FaustGen::SetSourceCode(const char* sourceCode)
149{
150 const bool success = Compile(sourceCode);
151
152 OnCompiled(success);
153
154 return success;
155}
156
157void FaustGen::OnCompiled(bool success)
158{
159 if (mOnCompileFunc)
160 mOnCompileFunc(success);
161
163}
164
165void FaustGen::AddLibraryPath(const char* path)
166{
167 if (CStringHasContents(path) && std::find(mLibraryPaths.begin(), mLibraryPaths.end(), path) == mLibraryPaths.end())
168 mLibraryPaths.push_back(path);
169}
170
171void FaustGen::SetBundleResourcePath(const char* resourcesPath)
172{
173 std::error_code ec;
174 const auto faustDir = ToPath(resourcesPath) / "faust";
175
176 if (!CStringHasContents(resourcesPath) || !std::filesystem::is_directory(faustDir, ec))
177 {
178 DBGMSG("FaustGen-%s: no bundled Faust files in %s\n", mName.Get(), resourcesPath);
179 return;
180 }
181
182 const std::string faustDirStr = ToUTF8(faustDir);
183 mLibraryPaths.erase(std::remove(mLibraryPaths.begin(), mLibraryPaths.end(), faustDirStr), mLibraryPaths.end());
184 mLibraryPaths.insert(mLibraryPaths.begin(), faustDirStr);
185
186 if (mDSPFile.size() && !std::filesystem::exists(ToPath(mDSPFile), ec))
187 {
188 const auto bundledFile = faustDir / ToPath(mDSPFile).filename();
189
190 if (std::filesystem::exists(bundledFile, ec))
191 {
192 DBGMSG("FaustGen-%s: using bundled %s\n", mName.Get(), ToUTF8(bundledFile).c_str());
193 mDSPFile = ToUTF8(bundledFile);
194 }
195 }
196}
197
198void FaustGen::AddCompileOption(const char* option)
199{
200 if (CStringHasContents(option))
201 mCompileOptions.push_back(option);
202}
203
205{
206 if (enable && !mFileWatchTimer && mDSPFile.size())
207 {
208 mFileWatchTimer = std::unique_ptr<Timer>(Timer::Create(std::bind(&FaustGen::OnTimer, this, std::placeholders::_1), FAUST_RECOMPILE_INTERVAL));
209 }
210 else if (!enable && mFileWatchTimer)
211 {
212 mFileWatchTimer->Stop();
213 mFileWatchTimer = nullptr;
214 }
215}
216
217bool FaustGen::Compile(const std::string& sourceCode)
218{
219 std::vector<std::string> args = mCompileOptions;
220
221 for (const auto& path : mLibraryPaths)
222 {
223 args.push_back("-I");
224 args.push_back(path);
225 }
226
227 std::vector<const char*> argv;
228
229 for (const auto& arg : args)
230 argv.push_back(arg.c_str());
231
232 argv.push_back(nullptr);
233
234 std::string error;
235 interpreter_dsp_factory* pFactory = nullptr;
236 ::dsp* pDSP = nullptr;
237
238 {
239 std::lock_guard<std::mutex> lock(GetCompileMutex());
240 pFactory = createInterpreterDSPFactoryFromString(mName.Get(), sourceCode, static_cast<int>(args.size()), argv.data(), error);
241
242 if (pFactory)
243 pDSP = pFactory->createDSPInstance();
244 }
245
246 if (!pFactory || !pDSP)
247 {
248 mErrorMessage = error.size() ? error : "Unknown error";
249 DBGMSG("FaustGen-%s: compilation failed: %s\n", mName.Get(), mErrorMessage.c_str());
250
251 if (pFactory)
252 {
253 std::lock_guard<std::mutex> lock(GetCompileMutex());
254 deleteInterpreterDSPFactory(pFactory);
255 }
256
257 return false;
258 }
259
260 // Swap in the new DSP, then the previous factory can be deleted
261 SetDSP(pDSP);
262
263 if (mFactory)
264 {
265 std::lock_guard<std::mutex> lock(GetCompileMutex());
266 deleteInterpreterDSPFactory(mFactory);
267 }
268
269 mFactory = pFactory;
270 mSourceCode = sourceCode;
271 mErrorMessage.clear();
272
273 DBGMSG("FaustGen-%s: compiled, %i input(s), %i output(s), %i parameter(s)\n", mName.Get(), NInputs(), NOutputs(), NParams());
274
275 return true;
276}
277
278void FaustGen::CompileDefault()
279{
280 // Pass through as many channels as possible, and output silence on the rest
281 const int nOutputs = GetMaxNOutputs() > -1 ? GetMaxNOutputs() : 2;
282 const int nInputs = std::min(GetMaxNInputs() > -1 ? GetMaxNInputs() : 2, nOutputs);
283
284 std::string code = "process = ";
285
286 if (nInputs > 0)
287 code += "par(i, " + std::to_string(nInputs) + ", _)";
288
289 if (nOutputs > nInputs)
290 code += std::string(nInputs > 0 ? ", " : "") + "par(i, " + std::to_string(nOutputs - nInputs) + ", 0)";
291
292 if (nOutputs == 0)
293 code += "0 : !";
294
295 code += ";";
296
297 const std::string errorMessage = mErrorMessage;
298 Compile(code);
299 mErrorMessage = errorMessage;
300}
301
302bool FaustGen::ReadFile(std::string& contents)
303{
304 std::error_code ec;
305 const auto path = ToPath(mDSPFile);
306 const auto modifiedTime = std::filesystem::last_write_time(path, ec);
307
308 if (ec)
309 return false;
310
311 std::ifstream file(path, std::ios::in | std::ios::binary);
312
313 if (!file.is_open())
314 return false;
315
316 std::stringstream buffer;
317 buffer << file.rdbuf();
318 contents = buffer.str();
319 mFileModifiedTime = modifiedTime.time_since_epoch().count();
320
321 return true;
322}
323
324void FaustGen::OnTimer(Timer& timer)
325{
326 std::error_code ec;
327 const auto modifiedTime = std::filesystem::last_write_time(ToPath(mDSPFile), ec);
328
329 if (ec || modifiedTime.time_since_epoch().count() == mFileModifiedTime)
330 return;
331
332 std::string sourceCode;
333
334 if (!ReadFile(sourceCode) || sourceCode == mSourceCode)
335 return;
336
337 DBGMSG("FaustGen-%s: %s changed, recompiling\n", mName.Get(), mDSPFile.c_str());
338
339 const bool success = Compile(sourceCode); // if this fails, the previous DSP keeps running
340
341 OnCompiled(success);
342}
343
344#endif // #ifndef FAUST_COMPILED
Utility functions and macros.
void SetBundleResourcePath(const char *resourcesPath)
Use the .dsp file and Faust libraries that iplug_add_faust(... BUNDLE) copies into the bundle's resou...
void AddLibraryPath(const char *path)
Add a path that is searched for imported .lib/.dsp files.
void Init() override
Compile the DSP.
void SetAutoRecompile(bool enable)
Watch the .dsp file and recompile it when it changes.
bool LoadFile(const char *path)
Load and compile a .dsp file, replacing the current DSP if compilation succeeds.
FaustGen(const char *name, const char *inputDSPFile=nullptr, int nVoices=0, const char *libraryPath=FAUST_SHARE_PATH)
bool SetSourceCode(const char *sourceCode)
Compile Faust source code, replacing the current DSP if compilation succeeds.
void AddCompileOption(const char *option)
Add a compiler option such as "-vec" (see faust –help)
int NParams() const
Definition: IPlugFaust.h:148
void InformHostIfParamsChanged()
If SetDSP() re-initialized the linked plug-in parameters (i.e.
Definition: IPlugFaust.cpp:356
void ReleaseDSP()
Destroys the DSP, waiting for a block that is being processed to finish first.
Definition: IPlugFaust.cpp:56
void SetDSP(::dsp *pMonoDSP)
Takes ownership of a newly created DSP, wraps it for polyphony if required, (re)builds the parameters...
Definition: IPlugFaust.cpp:367
Base class for timer.
Definition: IPlugTimer.h:43
static Timer * Create(ITimerFunction func, uint32_t intervalMs)
On Linux, callbacks run on a worker; returns nullptr if that worker cannot be created.