Debian Codegraph @

embedded/m_pyo.h

raw
1 /**************************************************************************
2 * Copyright 2014-2020 Olivier Belanger *
3 * *
4 * This file is part of pyo, a python module to help digital signal *
5 * processing script creation. *
6 * *
7 * pyo is free software: you can redistribute it and/or modify *
8 * it under the terms of the GNU Lesser General Public License as *
9 * published by the Free Software Foundation, either version 3 of the *
10 * License, or (at your option) any later version. *
11 * *
12 * pyo is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU Lesser General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Lesser General Public *
18 * License along with pyo. If not, see <http://www.gnu.org/licenses/>. *
19 *************************************************************************/
20 #include <stdlib.h>
21
22 #if !defined(_WIN32)
23 #include <dlfcn.h>
24 #endif
25
26 #include "Python.h"
27
28 #ifndef __m_pyo_h_
29 #define __m_pyo_h_
30
31 #if defined(_LANGUAGE_C_PLUS_PLUS) || defined(__cplusplus)
32 #define INLINE inline
33 extern "C" {
34 #else
35 #define INLINE
36 #endif
37
38 #if !defined(_WIN32)
39 /* libpython handle. libpython must be made available to the program loaded
40 ** in a new interpreter. */
41 static void *libpython_handle;
42 #endif
43
44 /*
45 ** Creates a new python interpreter and starts a pyo server in it.
46 ** Each instance of pyo, in order to be fully independent of other
47 ** instances, must be started in its own interpreter. An instance
48 ** can be an object in a programming language or a plugin in a daw.
49 **
50 ** arguments:
51 ** sr : float, host sampling rate.
52 ** bufsize : int, host buffer size.
53 ** chnls : int, number of in/out channels of the pyo server.
54 **
55 ** returns the new python thread's interpreter state.
56 */
57 INLINE PyThreadState * pyo_new_interpreter(float sr, int bufsize, int chnls) {
58 char msg[64];
59 PyThreadState *interp;
60 if(!Py_IsInitialized()) {
61 Py_InitializeEx(0);
62 }
63
64 #if !defined(_WIN32)
65 /* This call hardcodes 3.9 as the python version to be used to embed pyo in
66 a C or C++ program. This is not a good idea and must be fixed when everthing
67 is stable.
68 */
69 if (libpython_handle == NULL) {
70 #ifdef __linux__
71 libpython_handle = dlopen("libpython3.9.so", RTLD_LAZY | RTLD_GLOBAL);
72 #elif __APPLE__
73 libpython_handle = dlopen("libpython3.9.dylib", RTLD_LAZY | RTLD_GLOBAL);
74 #endif
75 }
76 #endif
77
78 PyGILState_Ensure(); /* get the GIL */
79
80 interp = Py_NewInterpreter(); /* add a new sub-interpreter */
81
82 /* On MacOS, trying to import wxPython in embedded python hang the process. */
83 PyRun_SimpleString("import os; os.environ['PYO_GUI_WX'] = '0'");
84
85 /* Force embedded audio server. */
86 PyRun_SimpleString("os.environ['PYO_SERVER_AUDIO'] = 'embedded'");
87
88 /* Set the default BPM (60 beat per minute). */
89 PyRun_SimpleString("BPM = 60.0");
90
91 PyRun_SimpleString("from pyo import *");
92 sprintf(msg, "_s_ = Server(%f, %d, %d, 1)", sr, chnls, bufsize);
93 PyRun_SimpleString(msg);
94 PyRun_SimpleString("_s_.boot()\n_s_.start()\n_s_.setServer()");
95 PyRun_SimpleString("_server_id_ = _s_.getServerID()");
96
97 /*
98 ** printf %p specifier behaves differently in Linux/MacOS and Windows.
99 */
100
101 #if defined(_WIN32)
102 PyRun_SimpleString("_in_address_ = '0x' + _s_.getInputAddr().lower()");
103 PyRun_SimpleString("_out_address_ = '0x' + _s_.getOutputAddr().lower()");
104 PyRun_SimpleString("_emb_callback_ = '0x' + _s_.getEmbedICallbackAddr().lower()");
105 #else
106 PyRun_SimpleString("_in_address_ = _s_.getInputAddr()");
107 PyRun_SimpleString("_out_address_ = _s_.getOutputAddr()");
108 PyRun_SimpleString("_emb_callback_ = _s_.getEmbedICallbackAddr()");
109 #endif
110
111 PyEval_ReleaseThread(interp);
112
113 return interp;
114 }
115
116 /*
117 ** Returns the address, as unsigned long, of the pyo input buffer.
118 ** Used this function if pyo's audio samples resolution is 32-bit.
119 **
120 ** arguments:
121 ** interp : pointer, pointer to the targeted Python thread state.
122 **
123 ** returns an "unsigned long" that should be recast to a float pointer.
124 */
125 INLINE unsigned long pyo_get_input_buffer_address(PyThreadState *interp) {
126 PyObject *module, *obj;
127 const char *address;
128 unsigned long uadd;
129 PyEval_AcquireThread(interp);
130 module = PyImport_AddModule("__main__");
131 obj = PyObject_GetAttrString(module, "_in_address_");
132 address = PyUnicode_AsUTF8(obj);
133 uadd = strtoul(address, NULL, 0);
134 PyEval_ReleaseThread(interp);
135 return uadd;
136 }
137
138 /*
139 ** Returns the address, as unsigned long long, of the pyo input buffer.
140 ** Used this function if pyo's audio samples resolution is 64-bit.
141 **
142 ** arguments:
143 ** interp : pointer, pointer to the targeted Python thread state.
144 **
145 ** returns an "unsigned long long" that should be recast to a double pointer.
146 */
147 INLINE unsigned long long pyo_get_input_buffer_address_64(PyThreadState *interp) {
148 PyObject *module, *obj;
149 const char *address;
150 unsigned long long uadd;
151 PyEval_AcquireThread(interp);
152 module = PyImport_AddModule("__main__");
153 obj = PyObject_GetAttrString(module, "_in_address_");
154 address = PyUnicode_AsUTF8(obj);
155 uadd = strtoull(address, NULL, 0);
156 PyEval_ReleaseThread(interp);
157 return uadd;
158 }
159
160 /*
161 ** Returns the address, as unsigned long, of the pyo output buffer.
162 ** Used this function if pyo's audio samples resolution is 32-bit.
163 **
164 ** arguments:
165 ** interp : pointer, pointer to the targeted Python thread state.
166 **
167 ** returns an "unsigned long" that should be recast to a float pointer.
168 */
169 INLINE unsigned long pyo_get_output_buffer_address(PyThreadState *interp) {
170 PyObject *module, *obj;
171 const char *address;
172 unsigned long uadd;
173 PyEval_AcquireThread(interp);
174 module = PyImport_AddModule("__main__");
175 obj = PyObject_GetAttrString(module, "_out_address_");
176 address = PyUnicode_AsUTF8(obj);
177 uadd = strtoul(address, NULL, 0);
178 PyEval_ReleaseThread(interp);
179 return uadd;
180 }
181
182 /*
183 ** Returns the address, as unsigned long long, of the pyo output buffer.
184 ** Used this function if pyo's audio samples resolution is 64-bit.
185 **
186 ** arguments:
187 ** interp : pointer, pointer to the targeted Python thread state.
188 **
189 ** returns an "unsigned long long" that should be recast to a double pointer.
190 */
191 INLINE unsigned long long pyo_get_output_buffer_address_64(PyThreadState *interp) {
192 PyObject *module, *obj;
193 const char *address;
194 unsigned long long uadd;
195 PyEval_AcquireThread(interp);
196 module = PyImport_AddModule("__main__");
197 obj = PyObject_GetAttrString(module, "_out_address_");
198 address = PyUnicode_AsUTF8(obj);
199 uadd = strtoull(address, NULL, 0);
200 PyEval_ReleaseThread(interp);
201 return uadd;
202 }
203
204 /*
205 ** Returns the address, as unsigned long, of the pyo embedded callback.
206 ** This callback must be called in the host's perform routine whenever
207 ** pyo has to compute a new buffer of samples.
208 **
209 ** arguments:
210 ** interp : pointer, pointer to the targeted Python thread state.
211 **
212 ** returns an "unsigned long" that should be recast to a void pointer.
213 **
214 ** The callback should be called with the server id (int) as argument.
215 **
216 ** Prototype:
217 ** void (*callback)(int);
218 */
219 INLINE unsigned long pyo_get_embedded_callback_address(PyThreadState *interp) {
220 PyObject *module, *obj;
221 const char *address;
222 unsigned long uadd;
223 PyEval_AcquireThread(interp);
224 module = PyImport_AddModule("__main__");
225 obj = PyObject_GetAttrString(module, "_emb_callback_");
226 address = PyUnicode_AsUTF8(obj);
227 uadd = strtoul(address, NULL, 0);
228 PyEval_ReleaseThread(interp);
229 return uadd;
230 }
231
232 /*
233 ** Returns the address, as unsigned long long, of the pyo embedded callback.
234 ** This callback must be called in the host's perform routine whenever
235 ** pyo has to compute a new buffer of samples.
236 **
237 ** arguments:
238 ** interp : pointer, pointer to the targeted Python thread state.
239 **
240 ** returns an "unsigned long long" that should be recast to a void pointer.
241 **
242 ** The callback should be called with the server id (int) as argument.
243 **
244 ** Prototype:
245 ** void (*callback)(int);
246 */
247 INLINE unsigned long long pyo_get_embedded_callback_address_64(PyThreadState *interp) {
248 PyObject *module, *obj;
249 const char *address;
250 unsigned long long uadd;
251 PyEval_AcquireThread(interp);
252 module = PyImport_AddModule("__main__");
253 obj = PyObject_GetAttrString(module, "_emb_callback_");
254 address = PyUnicode_AsUTF8(obj);
255 uadd = strtoull(address, NULL, 0);
256 PyEval_ReleaseThread(interp);
257 return uadd;
258 }
259
260 /*
261 ** Returns the pyo server id of this thread, as an integer.
262 ** The id must be pass as argument to the callback function.
263 **
264 ** arguments:
265 ** interp : pointer, pointer to the targeted Python thread state.
266 **
267 ** returns an integer.
268 */
269 INLINE int pyo_get_server_id(PyThreadState *interp) {
270 PyObject *module, *obj;
271 int id;
272 PyEval_AcquireThread(interp);
273 module = PyImport_AddModule("__main__");
274 obj = PyObject_GetAttrString(module, "_server_id_");
275 id = PyLong_AsLong(obj);
276 PyEval_ReleaseThread(interp);
277 return id;
278 }
279
280 /*
281 ** Closes the interpreter linked to the thread state given as argument.
282 **
283 ** arguments:
284 ** interp : pointer, pointer to the targeted Python thread state.
285 */
286 INLINE void pyo_end_interpreter(PyThreadState *interp) {
287 /* Clean up pyo's server. */
288 PyEval_AcquireThread(interp);
289 PyRun_SimpleString("_s_.setServer()\n_s_.stop()\n_s_.shutdown()");
290 PyEval_ReleaseThread(interp);
291
292 PyGILState_STATE state = PyGILState_Ensure();
293
294 /* End the sub-interpreter. */
295 PyThreadState* _ts = PyThreadState_Swap(interp);
296 Py_EndInterpreter(interp);
297 PyThreadState_Swap(_ts);
298
299 PyGILState_Release(state);
300
301 #if !defined(_WIN32)
302 if (libpython_handle != NULL) {
303 dlclose(libpython_handle);
304 }
305 #endif
306
307 }
308
309 /*
310 ** Shutdown and reboot the pyo server while keeping current in/out buffers.
311 **
312 ** arguments:
313 ** interp : pointer, pointer to the targeted Python thread state.
314 */
315 INLINE void pyo_server_reboot(PyThreadState *interp) {
316 PyEval_AcquireThread(interp);
317 PyRun_SimpleString("_s_.setServer()\n_s_.stop()\n_s_.shutdown()");
318 PyRun_SimpleString("_s_.boot(newBuffer=False).start()");
319 PyEval_ReleaseThread(interp);
320 }
321
322 /*
323 ** Reboot the pyo server with new sampling rate and buffer size.
324 **
325 ** arguments:
326 ** interp : pointer, pointer to the targeted Python thread state.
327 ** sr : float, host sampling rate.
328 ** bufsize : int, host buffer size.
329 */
330 INLINE void pyo_set_server_params(PyThreadState *interp, float sr, int bufsize) {
331 char msg[64];
332 PyEval_AcquireThread(interp);
333 PyRun_SimpleString("_s_.setServer()\n_s_.stop()\n_s_.shutdown()");
334 sprintf(msg, "_s_.setSamplingRate(%f)", sr);
335 PyRun_SimpleString(msg);
336 sprintf(msg, "_s_.setBufferSize(%d)", bufsize);
337 PyRun_SimpleString(msg);
338 PyRun_SimpleString("_s_.boot(newBuffer=False).start()");
339 PyEval_ReleaseThread(interp);
340 }
341
342 /*
343 ** This function can be used to pass the DAW's bpm value to the
344 ** python interpreter. Changes the value of the BPM variable in
345 ** the interpreter's global scope. (which defaults to 60).
346 **
347 ** arguments:
348 ** interp : pointer, pointer to the targeted Python thread state.
349 ** bpm : double, new BPM.
350 */
351 INLINE void pyo_set_bpm(PyThreadState *interp, double bpm) {
352 char msg[64];
353 PyEval_AcquireThread(interp);
354 sprintf(msg, "BPM = %f", bpm);
355 PyRun_SimpleString(msg);
356 PyEval_ReleaseThread(interp);
357 }
358
359 /*
360 ** Add a MIDI event in the pyo server processing chain. When used in
361 ** an embedded framework, pyo can't open MIDI ports by itself. MIDI
362 ** inputs must be handled by the host program and sent to pyo with
363 ** the pyo_add_midi_event function.
364 **
365 ** arguments:
366 ** interp : pointer, pointer to the targeted Python thread state.
367 ** status : int, status byte.
368 ** data1 : int, first data byte.
369 ** data2 : int, second data byte.
370 */
371 INLINE void pyo_add_midi_event(PyThreadState *interp, int status, int data1, int data2) {
372 char msg[64];
373 PyEval_AcquireThread(interp);
374 sprintf(msg, "_s_.addMidiEvent(%d, %d, %d)", status, data1, data2);
375 PyRun_SimpleString(msg);
376 PyEval_ReleaseThread(interp);
377 }
378
379 /*
380 ** Returns 1 if the pyo server is started for the given thread,
381 ** Otherwise returns 0.
382 **
383 ** arguments:
384 ** interp : pointer, pointer to the targeted Python thread state.
385 */
386 INLINE int pyo_is_server_started(PyThreadState *interp) {
387 int started;
388 PyObject *module, *obj;
389 PyEval_AcquireThread(interp);
390 PyRun_SimpleString("started = _s_.getIsStarted()");
391 module = PyImport_AddModule("__main__");
392 obj = PyObject_GetAttrString(module, "started");
393 started = PyLong_AsLong(obj);
394 PyEval_ReleaseThread(interp);
395 return started;
396 }
397
398 /*
399 ** Execute a python script "file" in the given thread's interpreter (interp).
400 ** A pre-allocated string "msg" must be given to create the python command
401 ** used for error handling. An integer "add" is needed to indicate if the
402 ** pyo server should be reboot or not.
403 **
404 ** arguments:
405 ** interp : pointer, pointer to the targeted Python thread state.
406 ** file : char *, filename to execute as a python script. The file is first
407 ** searched in the current working directory. If not found,
408 ** the module will try to open it as an absolute path.
409 ** msg : char *, pre-allocated string used to create the python command
410 ** used for error handling.
411 ** add, int, if positive, the commands in the file will be added to whatever
412 ** is already running in the pyo server. If 0, the server will be
413 ** shutdown and reboot before executing the file.
414 **
415 ** returns 0 (no error), 1 (failed to open the file) or 2 (bad code in file).
416 */
417 INLINE int pyo_exec_file(PyThreadState *interp, const char *file, char *msg, int add) {
418 int ok, isrel, badcode, err = 0;
419 PyObject *module;
420 PyEval_AcquireThread(interp);
421 sprintf(msg, "import os\n_isrel_ = True\n_ok_ = os.path.isfile('./%s')", file);
422 PyRun_SimpleString(msg);
423 sprintf(msg, "if not _ok_:\n _isrel_ = False\n _ok_ = os.path.isfile('%s')", file);
424 PyRun_SimpleString(msg);
425 module = PyImport_AddModule("__main__");
426 ok = PyLong_AsLong(PyObject_GetAttrString(module, "_ok_"));
427 isrel = PyLong_AsLong(PyObject_GetAttrString(module, "_isrel_"));
428 if (ok) {
429 if (!add) {
430 PyRun_SimpleString("_s_.setServer()\n_s_.stop()\n_s_.shutdown()");
431 PyRun_SimpleString("_s_.boot(newBuffer=False).start()");
432 }
433 if (isrel) {
434 sprintf(msg, "_badcode_ = False\ntry:\n exec(open('./%s').read())\nexcept:\n _badcode_ = True", file);
435 } else {
436 sprintf(msg, "_badcode_ = False\ntry:\n exec(open('%s').read())\nexcept:\n _badcode_ = True", file);
437 }
438 PyRun_SimpleString(msg);
439 badcode = PyLong_AsLong(PyObject_GetAttrString(module, "_badcode_"));
440 if (badcode) {
441 err = 2; // err = 2 means bad code in the file.
442 }
443 }
444 else {
445 err = 1; // err = 1 means problem opening the file.
446 }
447 PyEval_ReleaseThread(interp);
448 return err;
449 }
450
451 /*
452 ** Execute a python statement "msg" in the thread's interpreter "interp".
453 ** If "debug" is true, the statement will be executed in a try - except
454 ** block. The error message, if any, will be write back in the *msg
455 ** pointer and the function will return 1. If no error occured, the
456 ** function returned 0. If debug is false, the statement is executed
457 ** without any error checking (unsafe but faster).
458 **
459 ** arguments:
460 ** interp : pointer, pointer to the targeted Python thread state.
461 ** msg : char *, pointer to a string containing the statement to execute.
462 ** In debug mode, if an error occured, the output log will
463 ** be write back in this string.
464 ** debug, int, if positive, the commands will be executed in a try-except
465 ** statement. If 0, there will be no error checking, which is
466 ** much faster.
467 **
468 ** returns 0 (no error) or 1 (bad code in file).
469 */
470 INLINE int pyo_exec_statement(PyThreadState *interp, char *msg, int debug) {
471 int err = 0;
472 if (debug) {
473 PyObject *module, *obj;
474 char pp[26] = "_error_=None\ntry:\n ";
475 memmove(msg + strlen(pp), msg, strlen(msg)+1);
476 memmove(msg, pp, strlen(pp));
477 strcat(msg, "\nexcept Exception, _e_:\n _error_=str(_e_)");
478 PyEval_AcquireThread(interp);
479 PyRun_SimpleString(msg);
480 module = PyImport_AddModule("__main__");
481 obj = PyObject_GetAttrString(module, "_error_");
482 if (obj != Py_None) {
483 strcpy(msg, PyUnicode_AsUTF8(obj));
484 err = 1;
485 }
486 PyEval_ReleaseThread(interp);
487 }
488 else {
489 PyEval_AcquireThread(interp);
490 PyRun_SimpleString(msg);
491 PyEval_ReleaseThread(interp);
492 }
493 return err;
494 }
495
496 #if defined(_LANGUAGE_C_PLUS_PLUS) || defined(__cplusplus)
497 }
498 #endif
499
500 #endif /* __m_pyo_h_ */