forked from NeuroNetMem/PythonPlugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonPlugin.cpp
More file actions
667 lines (549 loc) · 18.3 KB
/
Copy pathPythonPlugin.cpp
File metadata and controls
667 lines (549 loc) · 18.3 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/*
------------------------------------------------------------------
Python Plugin
Copyright (C) 2016 FP Battaglia
based on
Open Ephys GUI
Copyright (C) 2013, 2015 Open Ephys
------------------------------------------------------------------
v
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
==============================================================================
PythonPlugin.cpp
Created: 13 Jun 2014 5:56:17pm
Author: fpbatta
==============================================================================
*/
#include "PythonPlugin.h"
#include "PythonPlugin.h"
#include "PythonEditor.h"
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#ifdef DEBUG
#define PYTHON_DEBUG
#endif
#ifdef PYTHON_DEBUG
#if defined(__linux__)
#include <sys/syscall.h>
#include <unistd.h>
#else
#include <pthread.h>
#endif
#endif
PythonPlugin::PythonPlugin(const String &processorName)
: GenericProcessor(processorName) //, threshold(200.0), state(true)
{
//parameters.add(Parameter("thresh", 0.0, 500.0, 200.0, 0));
filePath = "";
plugin = 0;
#define QUOTE(name) #name
#define STR(macro) QUOTE(macro)
#define PYTHON_HOME_NAME STR(PYTHON_HOME)
char * old_python_home = getenv("PYTHONHOME");
if (old_python_home == NULL)
{
#ifdef PYTHON_DEBUG
std::cout << "setting PYTHONHOME" << std::endl;
#endif
setenv("PYTHONHOME", PYTHON_HOME_NAME, 1);
}
// setenv("PYTHONHOME", "/usr/local/anaconda", 1); // FIXME hardcoded PYTHONHOME!
#ifdef PYTHON_DEBUG
std::cout << "PYTHONHOME: " << getenv("PYTHONHOME") << std::endl;
#endif
#ifdef PYTHON_DEBUG
#if defined(__linux__)
pid_t tid;
tid = syscall(SYS_gettid);
#else
uint64_t tid;
pthread_threadid_np(NULL, &tid);
#endif
std::cout << "in constructor pthread_threadid_np()=" << tid << std::endl;
#endif
#if PY_MAJOR_VERSION==3
Py_SetProgramName ((wchar_t *)"PythonPlugin");
#else
Py_SetProgramName ((char *)"PythonPlugin");
#endif
Py_Initialize ();
PyEval_InitThreads();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.setcheckinterval(10000)");
#ifdef PYTHON_DEBUG
std::cout << Py_GetPrefix() << std::endl;
std::cout << Py_GetVersion() << std::endl;
#endif
GUIThreadState = PyEval_SaveThread();
}
PythonPlugin::~PythonPlugin()
{
dlclose(plugin);
}
void PythonPlugin::createEventChannels()
{
EventChannel* ev = new EventChannel(EventChannel::TTL, 8, 1, CoreServices::getGlobalSampleRate(), this);
ev->setName("Python events");
ev->setDescription("Events generated by a Python plugin");
String identifier = "dataderived.python";
ev->setIdentifier(identifier);
MetaDataDescriptor md(MetaDataDescriptor::CHAR, 25, "Plugin type", "Description of the plugin", "channelInfo.extra");
MetaDataValue mv(md);
mv.setValue("Python plugin");
ev->addMetaData(md, mv);
eventChannelArray.add(ev);
ttlChannel = ev;
std::cout << "Python event channel created" << std::endl;
}
AudioProcessorEditor* PythonPlugin::createEditor()
{
// std::cout << "in PythonEditor::createEditor()" << std::endl;
editor = new PythonEditor(this, true);
return editor;
}
bool PythonPlugin::isReady()
{
#ifdef PYTHON_DEBUG
#if defined(__linux__)
pid_t tid;
tid = syscall(SYS_gettid);
#else
uint64_t tid;
pthread_threadid_np(NULL, &tid);
#endif
std::cout << "in isReady pthread_threadid_np()=" << tid << std::endl;
#endif
bool ret;
PyEval_RestoreThread(GUIThreadState);
if (plugin == 0 )
{
// sendActionMessage("No plugin selected in Python Plugin."); // FIXME how to send error message?
ret = false;
}
else if (pluginIsReady && !(*pluginIsReady)())
{
// sendActionMessage("Plugin is not ready"); // FIXME how to send error message?
ret = false;
}
else
{
ret = true;
}
GUIThreadState = PyEval_SaveThread();
return ret;
}
void PythonPlugin::setParameter(int parameterIndex, float newValue)
{
editor->updateParameterButtons(parameterIndex);
//Parameter& p = parameters.getReference(parameterIndex);
//p.setValue(newValue, 0);
//threshold = newValue;
//std::cout << float(p[0]) << std::endl;
editor->updateParameterButtons(parameterIndex);
}
void PythonPlugin::resetConnections()
{
#ifdef PYTHON_DEBUG
#if defined(__linux__)
pid_t tid;
tid = syscall(SYS_gettid);
#else
uint64_t tid;
pthread_threadid_np(NULL, &tid);
#endif
std::cout << "in resetConnection pthread_threadid_np()=" << tid << std::endl;
#endif
nextAvailableChannel = 0;
wasConnected = false;
#ifdef PYTHON_DEBUG
std::cout << "resetting ThreadState, which was " << processThreadState << std::endl;
#endif
processThreadState = 0;
}
void PythonPlugin::process(AudioSampleBuffer& buffer)
{
checkForEvents();
#ifdef PYTHON_DEBUG
#if defined(__linux__)
pid_t tid;
tid = syscall(SYS_gettid);
#else
uint64_t tid;
pthread_threadid_np(NULL, &tid);
#endif
// std::cout << "in process pthread_threadid_np()=" << tid << std::endl;
#endif
if(!processThreadState)
{
//DEBUG
PyThreadState *nowState;
nowState = PyGILState_GetThisThreadState();
#ifdef PYTHON_DEBUG
std::cout << "currentState: " << nowState << std::endl;
std::cout << "initialiting ThreadState" << std::endl;
#endif
if(nowState) //UGLY HACK!!!
{
processThreadState = nowState;
}
else
{
processThreadState = PyThreadState_New(GUIThreadState->interp);
}
if(!processThreadState)
std::cout << "ThreadState is Null!" << std::endl;
}
PyEval_RestoreThread(processThreadState);
PythonEvent *pyEvents = (PythonEvent *)calloc(1, sizeof(PythonEvent));
pyEvents->type = 0; // this marks an empty event
#ifdef PYTHON_DEBUG
// std::cout << "in process, trying to acquire lock" << std::endl;
#endif
// PyEval_InitThreads();
//
// std::cout << "in process, threadstate: " << PyGILState_GetThisThreadState() << std::endl;
// PyGILState_STATE gstate;
// gstate = PyGILState_Ensure();
// std::cout << "in process, lock acquired" << std::endl;
(*pluginFunction)(*(buffer.getArrayOfWritePointers()), buffer.getNumChannels(), buffer.getNumSamples(), getNumSamples(0), pyEvents);
// PyGILState_Release(gstate);
// std::cout << "in process, lock released" << std::endl;
if(wasTriggered)
{
uint8 ttlData = 0;
// std::cout << "in Python plugin resetting channel: " << lastChan << std::endl;
TTLEventPtr event = TTLEvent::createTTLEvent(ttlChannel, getTimestamp(0),
&ttlData, sizeof(uint8), lastChan);
addEvent(ttlChannel, event, 0);
wasTriggered = false;
}
if(pyEvents->type != 0)
{
#ifdef PYTHON_DEBUG
// std::cout << "Event emitted " << (int)pyEvents->type << std::endl;
#endif
// uint8 ttlData = 1 << module.outputChan;
// TTLEventPtr event = TTLEvent::createTTLEvent(moduleEventChannels[m], getTimestamp(module.inputChan) + i, &ttlData, sizeof(uint8), module.outputChan);
// addEvent(moduleEventChannels[m], event, i);
lastChan = (uint16)pyEvents->eventId;
uint8 ttlData = 1 << lastChan;
// std::cout << "in Python plugin ts is " << getTimestamp(0) + pyEvents->sampleNum << " and sampleNum is " <<
// pyEvents->sampleNum << " eventId: " << uint16(pyEvents->eventId) << " ttlData: " << int(ttlData) << std::endl;
// FIXME now we set the ts at the first samble in the block
TTLEventPtr event = TTLEvent::createTTLEvent(ttlChannel, getTimestamp(0) + pyEvents->sampleNum,
&ttlData, sizeof(uint8), lastChan);
addEvent(ttlChannel, event, pyEvents->sampleNum);
PythonEvent *lastEvent = pyEvents;
PythonEvent *nextEvent = lastEvent->nextEvent;
free((void *)lastEvent);
wasTriggered = true;
// std::cout << "lastChan is " << lastChan << std::endl;
while (nextEvent) {
lastChan = (uint16)nextEvent->eventId;
uint8 ttlData = 1 << lastChan;
// std::cout << "in Python plugin ts is " << getTimestamp(0) << " and sampleNum is " <<
// nextEvent->sampleNum << " ttlData: " << ttlData << std::endl;
TTLEventPtr event = TTLEvent::createTTLEvent(ttlChannel, getTimestamp(0) + nextEvent->sampleNum,
&ttlData, sizeof(uint8), lastChan);
addEvent(ttlChannel, event, nextEvent->sampleNum);
lastEvent = nextEvent;
nextEvent = nextEvent->nextEvent;
free((void *)lastEvent);
wasTriggered = true;
}
}
processThreadState = PyEval_SaveThread();
#ifdef PYTHON_DEBUG
// std::cout << "Thread saved" << std::endl;
#endif
}
/* The complete API that the Cython plugin has to expose is
void pluginStartup(void): a function to initialize the plugin data structures prior to start ACQ
int isReady(void): a boolean function telling the processor whether the plugin is ready to receive data
int getParamNum(void) get the number of parameters that the plugin takes
ParamConfig *getParamConfig(void) this will allow generating the editor GUI TODO
void setIntParameter(char *name, int value) set integer parameter
void set FloatParameter(char *name, float value) set float parameter
*/
void PythonPlugin::setFile(String fullpath)
{
#ifdef PYTHON_DEBUG
#if defined(__linux__)
pid_t tid;
tid = syscall(SYS_gettid);
#else
uint64_t tid;
pthread_threadid_np(NULL, &tid);
#endif
std::cout << "in setFile pthread_threadid_np()=" << tid << std::endl;
#endif
filePath = fullpath;
const char* path = filePath.getCharPointer();
plugin = dlopen(path, RTLD_LAZY);
if (!plugin)
{
std::cout << "Can't open plugin "
<< '"' << path << "\""
<< dlerror()
<< std::endl;
return;
}
String initPlugin = filePath.fromLastOccurrenceOf(String("/"), false, true);
initPlugin = initPlugin.upToFirstOccurrenceOf(String("."), false, true);
#if PY_MAJOR_VERSION>=3
String initPluginName = String("PyInit_");
#else
String initPluginName = String("init");
#endif
initPluginName.append(initPlugin, 200);
std::cout << "init function is: " << initPluginName << std::endl;
void *initializer = dlsym(plugin,initPluginName.getCharPointer());
#ifdef PYTHON_DEBUG
std::cout << "initializer: " << initializer << std::endl;
#endif
if (!initializer)
{
std::cout << "Can't find init function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
plugin = 0;
return;
}
initfunc_t initF = (initfunc_t) initializer;
void *cfunc = dlsym(plugin,"pluginisready");
if (!cfunc)
{
std::cout << "Can't find ready function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
plugin = 0;
return;
}
pluginIsReady = (isreadyfunc_t)cfunc;
cfunc = dlsym(plugin,"pluginStartup");
if (!cfunc)
{
std::cout << "Can't find startup function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
plugin = 0;
return;
}
pluginStartupFunction = (startupfunc_t)cfunc;
cfunc = dlsym(plugin,"getParamNum");
if (!cfunc)
{
std::cout << "Can't find getParamNum function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
plugin = 0;
return;
}
getParamNumFunction = (getparamnumfunc_t)cfunc;
cfunc = dlsym(plugin,"getParamConfig");
if (!cfunc)
{
std::cout << "Can't find getParamNum function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
// plugin = 0;
// return;
}
getParamConfigFunction = (getparamconfigfunc_t)cfunc;
cfunc = dlsym(plugin,"pluginFunction");
// std::cout << "plugin: " << cfunc << std::endl;
if (!cfunc)
{
std::cout << "Can't find plugin function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
plugin = 0;
return;
}
pluginFunction = (pluginfunc_t)cfunc;
cfunc = dlsym(plugin,"setIntParam");
// std::cout << "plugin: " << cfunc << std::endl;
if (!cfunc)
{
std::cout << "Can't find setIntParam function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
plugin = 0;
return;
}
setIntParamFunction = (setintparamfunc_t)cfunc;
cfunc = dlsym(plugin,"setFloatParam");
// std::cout << "plugin: " << cfunc << std::endl;
if (!cfunc)
{
std::cout << "Can't find setFloatParam function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
plugin = 0;
return;
}
setFloatParamFunction = (setfloatparamfunc_t)cfunc;
cfunc = dlsym(plugin, "getIntParam");
// std::cout << "plugin: " << cfunc << std::endl;
if (!cfunc)
{
std::cout << "Can't find getIntParam function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
plugin = 0;
return;
}
getIntParamFunction = (getintparamfunc_t)cfunc;
cfunc = dlsym(plugin, "getFloatParam");
// std::cout << "plugin: " << cfunc << std::endl;
if (!cfunc)
{
std::cout << "Can't find getFloatParam function in plugin "
<< '"' << path << "\"" << std::endl
<< dlerror()
<< std::endl;
plugin = 0;
return;
}
getFloatParamFunction = (getfloatparamfunc_t)cfunc;
// now the API should be fully loaded
PyEval_RestoreThread(GUIThreadState);
// initialize the plugin
#ifdef PYTHON_DEBUG
std::cout << "before initplugin" << std::endl; // DEBUG
#endif
(*initF)();
#ifdef PYTHON_DEBUG
std::cout << "after initplugin" << std::endl; // DEBUG
#endif
(*pluginStartupFunction)(getSampleRate());
// load the parameter configuration
numPythonParams = (*getParamNumFunction)();
#ifdef PYTHON_DEBUG
std::cout << "the plugin wants " << numPythonParams
<< " parameters" << std::endl;
#endif
params = (ParamConfig *)calloc(numPythonParams, sizeof(ParamConfig));
paramsControl = (Component **)calloc(numPythonParams, sizeof(Component *));
(*getParamConfigFunction)(params);
#ifdef PYTHON_DEBUG
std::cout << "release paramconfig" << std::endl;
#endif
for(int i = 0; i < numPythonParams; i++)
{
#ifdef PYTHON_DEBUG
std::cout << "param " << i << " is a " << params[i].type << std::endl;
std::cout << "it is named: " << params[i].name << std::endl << std::endl;
#endif
switch (params[i].type) {
case TOGGLE:
paramsControl[i] = dynamic_cast<PythonEditor *>(getEditor())->addToggleButton(String(params[i].name), params[i].isEnabled);
break;
case INT_SET:
paramsControl[i] = dynamic_cast<PythonEditor *>(getEditor())->addComboBox(String(params[i].name), params[i].nEntries, params[i].entries);
break;
case FLOAT_RANGE:
paramsControl[i] = dynamic_cast<PythonEditor *>(getEditor())->addSlider(String(params[i].name), params[i].rangeMin, params[i].rangeMax, params[i].startValue);
break;
default:
break;
}
}
GUIThreadState = PyEval_SaveThread();
}
String PythonPlugin::getFile()
{
return filePath;
}
void PythonPlugin::updateSettings()
{
}
void PythonPlugin::setIntPythonParameter(String name, int value)
{
#ifdef PYTHON_DEBUG
#if defined(__linux__)
pid_t tid;
tid = syscall(SYS_gettid);
#else
uint64_t tid;
pthread_threadid_np(NULL, &tid);
#endif
std::cout << "in setintparam pthread_threadid_np()=" << tid << std::endl;
#endif
PyEval_RestoreThread(GUIThreadState);
(*setIntParamFunction)(name.getCharPointer().getAddress(), value);
GUIThreadState = PyEval_SaveThread();
}
void PythonPlugin::setFloatPythonParameter(String name, float value)
{
#ifdef PYTHON_DEBUG
#if defined(__linux__)
pid_t tid;
tid = syscall(SYS_gettid);
#else
uint64_t tid;
pthread_threadid_np(NULL, &tid);
#endif
std::cout << "in setfloatparam pthread_threadid_np()=" << tid << std::endl;
#endif
PyEval_RestoreThread(GUIThreadState);
(*setFloatParamFunction)(name.getCharPointer().getAddress(), value);
GUIThreadState = PyEval_SaveThread();
}
int PythonPlugin::getIntPythonParameter(String name)
{
#ifdef PYTHON_DEBUG
#if defined(__linux__)
pid_t tid;
tid = syscall(SYS_gettid);
#else
uint64_t tid;
pthread_threadid_np(NULL, &tid);
#endif
std::cout << "in getintparam pthread_threadid_np()=" << tid << std::endl;
#endif
int value;
PyEval_RestoreThread(GUIThreadState);
value = (*getIntParamFunction)(name.getCharPointer().getAddress());
GUIThreadState = PyEval_SaveThread();
return value;
}
float PythonPlugin::getFloatPythonParameter(String name)
{
#ifdef PYTHON_DEBUG
#if defined(__linux__)
pid_t tid;
tid = syscall(SYS_gettid);
#else
uint64_t tid;
pthread_threadid_np(NULL, &tid);
#endif
std::cout << "in getfloatparam pthread_threadid_np()=" << tid << std::endl;
#endif
PyEval_RestoreThread(GUIThreadState);
float value;
value = (*getFloatParamFunction)(name.getCharPointer().getAddress());
GUIThreadState = PyEval_SaveThread();
return value;
}