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
|
#define BACKEND_NAME "python"
#define PY_SSIZE_T_CLEAN
#include <string.h>
#include <Python.h>
#include "python.h"
#define MMPY_INSTANCE_KEY "midimonster_instance"
/*
* TODO might want to export the full MM_API set to python at some point
*/
static PyThreadState* python_main = NULL;
static wchar_t* program_name = NULL;
MM_PLUGIN_API int init(){
backend python = {
.name = BACKEND_NAME,
.conf = python_configure,
.create = python_instance,
.conf_instance = python_configure_instance,
.channel = python_channel,
.handle = python_set,
.process = python_handle,
.start = python_start,
.shutdown = python_shutdown
};
//register backend
if(mm_backend_register(python)){
LOG("Failed to register backend");
return 1;
}
return 0;
}
static int python_configure(char* option, char* value){
LOG("No backend configuration possible");
return 1;
}
static int python_prepend_str(PyObject* list, char* str){
if(!list || !str){
return 1;
}
PyObject* item = PyUnicode_FromString(str);
if(!item){
return 1;
}
if(PyList_Insert(list, 0, item) < 0){
Py_DECREF(item);
return 1;
}
Py_DECREF(item);
return 0;
}
static PyObject* mmpy_output(PyObject* self, PyObject* args){
instance* inst = *((instance**) PyModule_GetState(self));
python_instance_data* data = (python_instance_data*) inst->impl;
const char* channel_name = NULL;
channel* chan = NULL;
channel_value val = {
0
};
size_t u;
if(!PyArg_ParseTuple(args, "sd", &channel_name, &val.normalised)){
return NULL;
}
val.normalised = clamp(val.normalised, 1.0, 0.0);
for(u = 0; u < data->channels; u++){
if(!strcmp(data->channel[u].name, channel_name)){
DBGPF("Setting channel %s.%s to %f", inst->name, channel_name, val.normalised);
chan = mm_channel(inst, u, 0);
//this should never happen
if(!chan){
LOGPF("Failed to fetch parsed channel %s.%s", inst->name, channel_name);
break;
}
data->channel[u].out = val.normalised;
mm_channel_event(chan, val);
break;
}
}
if(u == data->channels){
DBGPF("Output on unknown channel %s.%s, no event pushed", inst->name, channel_name);
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* mmpy_channel_value(PyObject* self, PyObject* args, uint8_t in){
instance* inst = *((instance**) PyModule_GetState(self));
python_instance_data* data = (python_instance_data*) inst->impl;
const char* channel_name = NULL;
size_t u;
if(!PyArg_ParseTuple(args, "s", &channel_name)){
return NULL;
}
for(u = 0; u < data->channels; u++){
if(!strcmp(data->channel[u].name, channel_name)){
return PyFloat_FromDouble(in ? data->channel[u].in : data->channel[u].out);
}
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* mmpy_current_handler(PyObject* self, PyObject* args){
instance* inst = *((instance**) PyModule_GetState(self));
python_instance_data* data = (python_instance_data*) inst->impl;
if(data->current_channel){
return PyUnicode_FromString(data->current_channel->name);
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* mmpy_output_value(PyObject* self, PyObject* args){
return mmpy_channel_value(self, args, 0);
}
static PyObject* mmpy_input_value(PyObject* self, PyObject* args){
return mmpy_channel_value(self, args, 1);
}
static int mmpy_exec(PyObject* module) {
instance** inst = (instance**) PyModule_GetState(module);
//FIXME actually use interpreter dict (from python 3.8) here at some point
PyObject* capsule = PyDict_GetItemString(PyThreadState_GetDict(), MMPY_INSTANCE_KEY);
if(capsule && inst){
*inst = PyCapsule_GetPointer(capsule, NULL);
return 0;
}
//TODO raise exception
return -1;
}
static int python_configure_instance(instance* inst, char* option, char* value){
python_instance_data* data = (python_instance_data*) inst->impl;
PyObject* module = NULL;
//load python script
if(!strcmp(option, "module")){
//swap to interpreter
PyEval_RestoreThread(data->interpreter);
//import the module
module = PyImport_ImportModule(value);
if(!module){
LOGPF("Failed to import module %s to instance %s", value, inst->name);
PyErr_Print();
}
Py_XDECREF(module);
PyEval_ReleaseThread(data->interpreter);
return 0;
}
LOGPF("Unknown instance parameter %s for instance %s", option, inst->name);
return 1;
}
static PyObject* mmpy_init(){
static PyModuleDef_Slot mmpy_slots[] = {
{Py_mod_exec, (void*) mmpy_exec},
{0}
};
static PyMethodDef mmpy_methods[] = {
{"output", mmpy_output, METH_VARARGS, "Output a channel event"},
{"inputvalue", mmpy_input_value, METH_VARARGS, "Get last input value for a channel"},
{"outputvalue", mmpy_output_value, METH_VARARGS, "Get the last output value for a channel"},
{"current", mmpy_current_handler, METH_VARARGS, "Get the name of the currently executing channel handler"},
{0}
};
static struct PyModuleDef mmpy = {
PyModuleDef_HEAD_INIT,
"midimonster",
NULL, /*doc size*/
sizeof(instance*),
mmpy_methods,
mmpy_slots
};
//single-phase init
//return PyModule_Create(&mmpy);
//multi-phase init
return PyModuleDef_Init(&mmpy);
}
static int python_instance(instance* inst){
python_instance_data* data = calloc(1, sizeof(python_instance_data));
PyObject* interpreter_dict = NULL;
char current_directory[8192];
if(!data){
LOG("Failed to allocate memory");
return 1;
}
//lazy-init because we need the interpreter running before _start,
//but don't want it running if no instances are defined
if(!python_main){
LOG("Initializing main python interpreter");
if(PyImport_AppendInittab("midimonster", &mmpy_init)){
LOG("Failed to extend python inittab for main interpreter");
}
program_name = Py_DecodeLocale("midimonster", NULL);
Py_SetProgramName(program_name);
//initialize python
Py_InitializeEx(0);
//create, acquire and release the GIL
PyEval_InitThreads();
python_main = PyEval_SaveThread();
}
//acquire the GIL before creating a new interpreter
PyEval_RestoreThread(python_main);
//create subinterpreter for new instance
data->interpreter = Py_NewInterpreter();
//push cwd as import path
if(getcwd(current_directory, sizeof(current_directory))){
if(python_prepend_str(PySys_GetObject("path"), current_directory)){
LOG("Failed to push current working directory to python");
goto bail;
}
}
//push the instance pointer for later module initialization
//FIXME python 3.8 introduces interpreter_dict = PyInterpreterState_GetDict(data->interpreter->interp);
//for now use thread state...
interpreter_dict = PyThreadState_GetDict();
if(!interpreter_dict){
LOG("Failed to access per-interpreter data storage");
goto bail;
}
//FIXME this might leak a reference to the capsule
if(PyDict_SetItemString(interpreter_dict, MMPY_INSTANCE_KEY, PyCapsule_New(inst, NULL, NULL))){
LOG("Failed to set per-interpreter instance pointer");
goto bail;
}
//NewInterpreter leaves us with the GIL, drop it
PyEval_ReleaseThread(data->interpreter);
inst->impl = data;
return 0;
bail:
if(data->interpreter){
PyEval_ReleaseThread(data->interpreter);
}
free(data);
return 1;
}
static channel* python_channel(instance* inst, char* spec, uint8_t flags){
python_instance_data* data = (python_instance_data*) inst->impl;
size_t u;
for(u = 0; u < data->channels; u++){
if(!strcmp(data->channel[u].name, spec)){
break;
}
}
if(u == data->channels){
data->channel = realloc(data->channel, (data->channels + 1) * sizeof(mmpython_channel));
if(!data->channel){
data->channels = 0;
LOG("Failed to allocate memory");
return NULL;
}
memset(data->channel + u, 0, sizeof(mmpython_channel));
data->channel[u].name = strdup(spec);
if(!data->channel[u].name){
LOG("Failed to allocate memory");
return NULL;
}
data->channels++;
}
return mm_channel(inst, u, 1);
}
static int python_set(instance* inst, size_t num, channel** c, channel_value* v){
python_instance_data* data = (python_instance_data*) inst->impl;
mmpython_channel* chan = NULL;
PyObject* result = NULL;
size_t u;
//swap to interpreter
PyEval_RestoreThread(data->interpreter);
for(u = 0; u < num; u++){
chan = data->channel + c[u]->ident;
//update input value buffer
chan->in = v[u].normalised;
//call handler if present
if(chan->handler){
DBGPF("Calling handler for %s.%s", inst->name, chan->name);
data->current_channel = chan;
result = PyObject_CallFunction(chan->handler, "d", chan->in);
Py_XDECREF(result);
data->current_channel = NULL;
DBGPF("Done with handler for %s.%s", inst->name, chan->name);
}
}
PyEval_ReleaseThread(data->interpreter);
return 0;
}
static int python_handle(size_t num, managed_fd* fds){
//TODO implement some kind of intervaling functionality before people get it in their heads to start `import threading`
return 0;
}
static int python_start(size_t n, instance** inst){
python_instance_data* data = NULL;
PyObject* module = NULL;
size_t u, p;
char* module_name = NULL, *channel_name = NULL;
//resolve channel references to handler functions
for(u = 0; u < n; u++){
data = (python_instance_data*) inst[u]->impl;
//switch to interpreter
PyEval_RestoreThread(data->interpreter);
for(p = 0; p < data->channels; p++){
module = PyImport_AddModule("__main__");
channel_name = data->channel[p].name;
module_name = strchr(channel_name, '.');
if(module_name){
*module_name = 0;
//returns borrowed reference
module = PyImport_AddModule(channel_name);
if(!module){
LOGPF("Module %s for qualified channel %s.%s is not loaded on instance %s", channel_name, channel_name, module_name + 1, inst[u]->name);
return 1;
}
*module_name = '.';
channel_name = module_name + 1;
}
//returns new reference
data->channel[p].handler = PyObject_GetAttrString(module, channel_name);
}
//release interpreter
PyEval_ReleaseThread(data->interpreter);
}
return 0;
}
static int python_shutdown(size_t n, instance** inst){
size_t u, p;
python_instance_data* data = NULL;
//clean up channels
//this needs to be done before stopping the interpreters,
//because the handler references are refcounted
for(u = 0; u < n; u++){
data = (python_instance_data*) inst[u]->impl;
for(p = 0; p < data->channels; p++){
free(data->channel[p].name);
Py_XDECREF(data->channel[p].handler);
}
free(data->channel);
//do not free data here, needed for shutting down interpreters
}
if(python_main){
//just used to lock the GIL
PyEval_RestoreThread(python_main);
for(u = 0; u < n; u++){
data = (python_instance_data*) inst[u]->impl;
DBGPF("Shutting down interpreter for instance %s", inst[u]->name);
//swap to interpreter and end it, GIL is held after this but state is NULL
PyThreadState_Swap(data->interpreter);
PyErr_Clear();
//PyThreadState_Clear(data->interpreter);
Py_EndInterpreter(data->interpreter);
free(data);
}
//shut down main interpreter
PyThreadState_Swap(python_main);
if(Py_FinalizeEx()){
LOG("Failed to destroy python interpreters");
}
PyMem_RawFree(program_name);
}
LOG("Backend shut down");
return 0;
}
|