-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathPyPlugin.cpp
More file actions
472 lines (401 loc) · 13.4 KB
/
PyPlugin.cpp
File metadata and controls
472 lines (401 loc) · 13.4 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
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
461
462
463
464
465
466
467
468
469
470
471
/*
* Vampy : This plugin is a wrapper around the Vamp plugin API.
* It allows for writing Vamp plugins in Python.
* Centre for Digital Music, Queen Mary University of London.
* Copyright (C) 2008-2009 Gyorgy Fazekas, QMUL. (See Vamp sources
* for licence information.)
*/
#include <Python.h>
#include "PyPlugin.h"
#include "PyTypeInterface.h"
#include <stdlib.h>
#include "PyExtensionModule.h"
#include "Debug.h"
#ifdef _WIN32
#define PATHSEP ('\\')
#else
#define PATHSEP ('/')
#endif
using std::string;
using std::vector;
using std::cerr;
using std::endl;
using std::map;
Mutex PyPlugin::m_pythonInterpreterMutex;
PyPlugin::PyPlugin(std::string pluginKey, float inputSampleRate, PyObject *pyClass, int &instcount, bool &numpyInstalled) :
Plugin(inputSampleRate),
m_pyClass(pyClass),
m_instcount(instcount),
m_stepSize(0),
m_blockSize(0),
m_channels(0),
m_plugin(pluginKey),
m_class(pluginKey.substr(pluginKey.rfind(':')+1,pluginKey.size()-1)),
m_path((pluginKey.substr(0,pluginKey.rfind(PATHSEP)))),
m_processType(not_implemented),
m_pyProcess(NULL),
m_inputDomain(TimeDomain),
m_quitOnErrorFlag(false),
m_debugFlag(false),
m_numpyInstalled(numpyInstalled),
m_processFailure(false)
{
m_ti.setInputSampleRate(inputSampleRate);
MutexLocker locker(&m_pythonInterpreterMutex);
DSTREAM << "Creating instance " << m_instcount << " of " << pluginKey << endl;
// Create an instance
Py_INCREF(m_pyClass);
PyObject *pyInputSampleRate = PyFloat_FromDouble(inputSampleRate);
PyObject *args = PyTuple_Pack(1, pyInputSampleRate);
m_pyInstance = PyObject_Call(m_pyClass, args, NULL);
if (!m_pyInstance || PyErr_Occurred()) {
if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); }
Py_DECREF(m_pyClass);
Py_CLEAR(args);
Py_CLEAR(pyInputSampleRate);
cerr << "PyPlugin::PyPlugin: Failed to create Python plugin instance for key \""
<< pluginKey << "\" (is the 1-arg class constructor from sample rate correctly provided?)" << endl;
throw std::string("Constructor failed");
}
Py_INCREF(m_pyInstance);
Py_DECREF(args);
Py_DECREF(pyInputSampleRate);
m_instcount++;
// query and decode vampy flags
m_vampyFlags = getBinaryFlags("vampy_flags",vf_NULL);
m_debugFlag = (bool) (m_vampyFlags & vf_DEBUG);
m_quitOnErrorFlag = (bool) (m_vampyFlags & vf_QUIT);
bool st_flag = (bool) (m_vampyFlags & vf_STRICT);
m_useRealTimeFlag = (bool) (m_vampyFlags & vf_REALTIME);
if (m_debugFlag) cerr << "Debug messages ON for Vampy plugin: " << m_class << endl;
else DSTREAM << "Debug messages OFF for Vampy plugin: " << m_class << endl;
if (m_debugFlag && m_quitOnErrorFlag) cerr << "Quit on type error ON for: " << m_class << endl;
if (m_debugFlag && st_flag) cerr << "Strict type conversion ON for: " << m_class << endl;
m_ti.setStrictTypingFlag(st_flag);
m_ti.setNumpyInstalled(m_numpyInstalled);
}
PyPlugin::~PyPlugin()
{
MutexLocker locker(&m_pythonInterpreterMutex);
m_instcount--;
// cerr << "Deleting plugin instance. Count: " << m_instcount << endl;
if (m_pyInstance) Py_DECREF(m_pyInstance);
//we increase the class refcount before creating an instance
if (m_pyClass) Py_DECREF(m_pyClass);
if (m_pyProcess) Py_CLEAR(m_pyProcess);
DSTREAM << "PyPlugin::PyPlugin:" << m_class << " instance " << m_instcount << " deleted." << endl;
}
string
PyPlugin::getIdentifier() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
string rString="vampy-xxx";
if (!m_debugFlag) return genericMethodCall("getIdentifier",rString);
rString = genericMethodCall("getIdentifier",rString);
if (rString == "vampy-xxx")
cerr << "Warning: Plugin must return a unique identifier." << endl;
return rString;
}
string
PyPlugin::getName() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
string rString="VamPy Plugin (Noname)";
return genericMethodCall("getName",rString);
}
string
PyPlugin::getDescription() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
string rString="Not given. (Hint: Implement getDescription method.)";
return genericMethodCall("getDescription",rString);
}
string
PyPlugin::getMaker() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
string rString="VamPy Plugin.";
return genericMethodCall("getMaker",rString);
}
int
PyPlugin::getPluginVersion() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
size_t rValue=2;
return genericMethodCall("getPluginVersion",rValue);
}
string
PyPlugin::getCopyright() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
string rString="Licence information not available.";
return genericMethodCall("getCopyright",rString);
}
bool
PyPlugin::initialise(size_t channels, size_t stepSize, size_t blockSize)
{
if (channels < getMinChannelCount() ||
channels > getMaxChannelCount()) return false;
m_inputDomain = getInputDomain();
//Note: placing Mutex before the calls above causes deadlock !!
MutexLocker locker(&m_pythonInterpreterMutex);
m_stepSize = stepSize;
m_blockSize = blockSize;
m_channels = channels;
//query the process implementation type
//two optional flags can be used: 'use_numpy_interface' or 'use_legacy_interface'
//if they are not provided, we fall back to the original method
setProcessType();
return genericMethodCallArgs<bool>("initialise",channels,stepSize,blockSize);
}
void
PyPlugin::reset()
{
MutexLocker locker(&m_pythonInterpreterMutex);
m_processFailure = false;
genericMethodCall("reset");
}
PyPlugin::InputDomain
PyPlugin::getInputDomain() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
return genericMethodCall("getInputDomain",m_inputDomain);
}
size_t
PyPlugin::getPreferredBlockSize() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
size_t rValue = 0;
return genericMethodCall("getPreferredBlockSize",rValue);
}
size_t
PyPlugin::getPreferredStepSize() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
size_t rValue = 0;
return genericMethodCall("getPreferredStepSize",rValue);
}
size_t
PyPlugin::getMinChannelCount() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
size_t rValue = 1;
return genericMethodCall("getMinChannelCount",rValue);
}
size_t
PyPlugin::getMaxChannelCount() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
size_t rValue = 1;
return genericMethodCall("getMaxChannelCount",rValue);
}
PyPlugin::OutputList
PyPlugin::getOutputDescriptors() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
OutputList list;
return genericMethodCall("getOutputDescriptors",list);
}
PyPlugin::ParameterList
PyPlugin::getParameterDescriptors() const
{
MutexLocker locker(&m_pythonInterpreterMutex);
ParameterList list;
#ifdef _DEBUG
///Note: This function is often called first by the host.
if (!m_pyInstance) {cerr << "Error: pyInstance is NULL" << endl; return list;}
#endif
return genericMethodCall("getParameterDescriptors",list);
}
void PyPlugin::setParameter(std::string paramid, float newval)
{
MutexLocker locker(&m_pythonInterpreterMutex);
genericMethodCallArgs<NoneType>("setParameter",paramid,newval);
}
float PyPlugin::getParameter(std::string paramid) const
{
MutexLocker locker(&m_pythonInterpreterMutex);
return genericMethodCallArgs<float>("getParameter",paramid);
}
#ifdef _DEBUG_VALUES
static int proccounter = 0;
#endif
PyPlugin::FeatureSet
PyPlugin::process(const float *const *inputBuffers,Vamp::RealTime timestamp)
{
MutexLocker locker(&m_pythonInterpreterMutex);
#ifdef _DEBUG_VALUES
/// we only need this if we'd like to see what frame a set of values belong to
cerr << "[Vampy::call] process, frame:" << proccounter << endl;
proccounter++;
#endif
if (m_blockSize == 0 || m_channels == 0) {
cerr << "ERROR: PyPlugin::process: "
<< "Plugin has not been initialised" << endl;
return FeatureSet();
}
if (m_processType == not_implemented) {
cerr << "ERROR: In Python plugin [" << m_class
<< "] No process implementation found. Returning empty feature set." << endl;
return FeatureSet();
}
if (m_processFailure) return FeatureSet();
return processMethodCall(inputBuffers,timestamp);
}
PyPlugin::FeatureSet
PyPlugin::getRemainingFeatures()
{
MutexLocker locker(&m_pythonInterpreterMutex);
if (m_processFailure) return FeatureSet();
FeatureSet rValue;
return genericMethodCall("getRemainingFeatures",rValue);
}
bool
PyPlugin::getBooleanFlag(const char flagName[], bool defValue = false) const
{
bool rValue = defValue;
if (PyObject_HasAttrString(m_pyInstance,flagName))
{
PyObject *pyValue = PyObject_GetAttrString(m_pyInstance,flagName);
if (!pyValue)
{
if (PyErr_Occurred()) {PyErr_Print(); PyErr_Clear();}
} else {
rValue = m_ti.PyValue_To_Bool(pyValue);
if (m_ti.error) {
Py_CLEAR(pyValue);
typeErrorHandler(flagName);
rValue = defValue;
} else Py_DECREF(pyValue);
}
}
if (m_debugFlag) cerr << FLAG_VALUE << endl;
return rValue;
}
int
PyPlugin::getBinaryFlags(const char flagName[], eVampyFlags defValue = vf_NULL) const
{
int rValue = defValue;
if (PyObject_HasAttrString(m_pyInstance,flagName))
{
PyObject *pyValue = PyObject_GetAttrString(m_pyInstance,flagName);
if (!pyValue)
{
if (PyErr_Occurred()) {PyErr_Print(); PyErr_Clear();}
} else {
rValue |= (int) m_ti.PyValue_To_Size_t(pyValue);
if (m_ti.error) {
Py_CLEAR(pyValue);
typeErrorHandler(flagName);
rValue = defValue;
} else Py_DECREF(pyValue);
}
}
if (m_debugFlag) cerr << FLAG_VALUE << endl;
return rValue;
}
void
PyPlugin::setProcessType()
{
//quering process implementation type
char legacyMethod[]="process";
char numpyMethod[]="processN";
m_processFailure = false;
if (PyObject_HasAttrString(m_pyInstance,legacyMethod) &&
m_processType == 0)
{
m_processType = legacyProcess;
m_pyProcess = PyString_FromString(legacyMethod);
m_pyProcessCallable = PyObject_GetAttr(m_pyInstance,m_pyProcess);
}
if (PyObject_HasAttrString(m_pyInstance,numpyMethod) &&
m_processType == 0)
{
m_processType = numpy_bufferProcess;
m_pyProcess = PyString_FromString(numpyMethod);
m_pyProcessCallable = PyObject_GetAttr(m_pyInstance,m_pyProcess);
}
// These flags are optional. If provided, they override the
// implementation type making the use of the odd processN()
// function redundant.
// However, the code above provides backward compatibility.
if (m_vampyFlags & vf_BUFFER) {
m_processType = numpy_bufferProcess;
if (m_debugFlag) cerr << "Process using (numpy) buffer interface." << endl;
}
if (m_vampyFlags & vf_ARRAY) {
#ifdef HAVE_NUMPY
if (m_numpyInstalled) { m_processType = numpy_arrayProcess;
if (m_debugFlag)
cerr << "Process using numpy array interface." << endl;
}
else {
m_processFailure = true;
char method[]="initialise::setProcessType";
cerr << PLUGIN_ERROR
<< "This plugin requests the Numpy array interface by setting "
<< " the vf_ARRAY flag in its __init__() function." << endl
<< "However, we could not found a version of Numpy compatible with this build of Vampy." << endl
<< "If you have a numerical library installed that supports the buffer interface, " << endl
<< "you can request this interface instead by setting the vf_BUFFER flag." << endl;
}
#else
m_processFailure = true;
char method[]="initialise::setProcessType";
cerr << PLUGIN_ERROR
<< "Error: This version of vampy was compiled without numpy support, "
<< "however the vf_ARRAY flag is set for plugin: " << m_class << endl
<< "The default behaviour is: passing a python list of samples for each channel in process() "
<< "or a list of memory buffers in processN(). " << endl
<< "This can be used create numpy arrays using the numpy.frombuffer() command." << endl;
#endif
}
if (!m_pyProcessCallable)
{
m_processType = not_implemented;
m_pyProcess = NULL;
char method[]="initialise::setProcessType";
cerr << PLUGIN_ERROR << " No process implementation found. Plugin will do nothing." << endl;
m_processFailure = true;
}
}
void
PyPlugin::typeErrorHandler(const char *method, bool process) const
{
bool strict = false;
while (m_ti.error) {
PyTypeInterface::ValueError e = m_ti.getError();
#ifdef HAVE_NUMPY
// disable the process completely if numpy types are returned
// but a compatible version was not loaded.
// This is required because if an object is returned from
// the wrong build, malloc complains about its size
// (i.e. the interpreter doesn't free it properly)
// and the process may be leaking.
// Note: this only happens in the obscure situation when
// someone forces to return wrong numpy types from an
// incompatible version using the buffer interface.
// In this case the incampatible library is still usable,
// but manual conversion to python builtins is required.
// If the ARRAY interface is set but Numpy is not installed
// the process will be disabled already at initialisation.
if (process && !m_numpyInstalled && e.str().find("numpy")!=std::string::npos)
{
m_processFailure = true;
cerr << "Warning: incompatible numpy type encountered. Disabling process." << endl;
}
#endif
cerr << PLUGIN_ERROR << e.str() << endl;
if (e.strict) strict = true;
// e.print();
}
/// quit on hard errors like accessing NULL pointers or strict type conversion
/// errors IF the user sets the quitOnErrorFlag in the plugin.
/// Otherwise most errors will go unnoticed apart from
/// a messages in the terminal.
/// It would be best if hosts could catch an exception instead
/// and display something meaningful to the user.
if (strict && m_quitOnErrorFlag) exit(EXIT_FAILURE);
// this would disable all outputs even if some are valid
// if (process) m_processFailure = true;
}