1 /******************************************************************************
2     Copyright (C) 2015 by Andrew Skinner <obs@theandyroid.com>
3     Copyright (C) 2017 by Hugh Bailey <jim@obsproject.com>
4 
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 2 of the License, or
8     (at your option) any later version.
9 
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14 
15     You should have received a copy of the GNU General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 ******************************************************************************/
18 
19 #include "obs-scripting-python.h"
20 #include "obs-scripting-config.h"
21 #include <util/base.h>
22 #include <util/platform.h>
23 #include <util/darray.h>
24 #include <util/dstr.h>
25 
26 #include <obs.h>
27 
28 /* ========================================================================= */
29 
30 // #define DEBUG_PYTHON_STARTUP
31 
32 static const char *startup_script = "\n\
33 import sys\n\
34 import os\n\
35 import obspython\n\
36 class stdout_logger(object):\n\
37 	def write(self, message):\n\
38 		obspython.script_log_no_endl(obspython.LOG_INFO, message)\n\
39 	def flush(self):\n\
40 		pass\n\
41 class stderr_logger(object):\n\
42 	def write(self, message):\n\
43 		obspython.script_log_no_endl(obspython.LOG_ERROR, message)\n\
44 	def flush(self):\n\
45 		pass\n\
46 os.environ['PYTHONUNBUFFERED'] = '1'\n\
47 sys.stdout = stdout_logger()\n\
48 sys.stderr = stderr_logger()\n";
49 
50 #if RUNTIME_LINK
51 static wchar_t home_path[1024] = {0};
52 #endif
53 
54 DARRAY(char *) python_paths;
55 static bool python_loaded = false;
56 static bool mutexes_loaded = false;
57 
58 static pthread_mutex_t tick_mutex;
59 static struct obs_python_script *first_tick_script = NULL;
60 
61 static PyObject *py_obspython = NULL;
62 struct obs_python_script *cur_python_script = NULL;
63 struct python_obs_callback *cur_python_cb = NULL;
64 
65 /* -------------------------------------------- */
66 
py_to_libobs_(const char * type,PyObject * py_in,void * libobs_out,const char * id,const char * func,int line)67 bool py_to_libobs_(const char *type, PyObject *py_in, void *libobs_out,
68 		   const char *id, const char *func, int line)
69 {
70 	swig_type_info *info = SWIG_TypeQuery(type);
71 	if (info == NULL) {
72 		warn("%s:%d: SWIG could not find type: %s%s%s", func, line,
73 		     id ? id : "", id ? "::" : "", type);
74 		return false;
75 	}
76 
77 	int ret = SWIG_ConvertPtr(py_in, libobs_out, info, 0);
78 	if (!SWIG_IsOK(ret)) {
79 		warn("%s:%d: SWIG failed to convert python object to obs "
80 		     "object: %s%s%s",
81 		     func, line, id ? id : "", id ? "::" : "", type);
82 		return false;
83 	}
84 
85 	return true;
86 }
87 
libobs_to_py_(const char * type,void * libobs_in,bool ownership,PyObject ** py_out,const char * id,const char * func,int line)88 bool libobs_to_py_(const char *type, void *libobs_in, bool ownership,
89 		   PyObject **py_out, const char *id, const char *func,
90 		   int line)
91 {
92 	swig_type_info *info = SWIG_TypeQuery(type);
93 	if (info == NULL) {
94 		warn("%s:%d: SWIG could not find type: %s%s%s", func, line,
95 		     id ? id : "", id ? "::" : "", type);
96 		return false;
97 	}
98 
99 	*py_out = SWIG_NewPointerObj(libobs_in, info, (int)ownership);
100 	if (*py_out == Py_None) {
101 		warn("%s:%d: SWIG failed to convert obs object to python "
102 		     "object: %s%s%s",
103 		     func, line, id ? id : "", id ? "::" : "", type);
104 		return false;
105 	}
106 
107 	return true;
108 }
109 
110 #define libobs_to_py(type, obs_obj, ownership, py_obj)                        \
111 	libobs_to_py_(#type " *", obs_obj, ownership, py_obj, NULL, __func__, \
112 		      __LINE__)
113 #define py_to_libobs(type, py_obj, libobs_out) \
114 	py_to_libobs_(#type " *", py_obj, libobs_out, NULL, __func__, __LINE__)
115 
116 #define lock_callback(cb)                                                \
117 	lock_python();                                                   \
118 	struct obs_python_script *__last_script = cur_python_script;     \
119 	struct python_obs_callback *__last_cb = cur_python_cb;           \
120 	cur_python_script = (struct obs_python_script *)cb->base.script; \
121 	cur_python_cb = cb
122 #define unlock_callback()                  \
123 	cur_python_cb = __last_cb;         \
124 	cur_python_script = __last_script; \
125 	unlock_python()
126 
127 /* ========================================================================= */
128 
add_functions_to_py_module(PyObject * module,PyMethodDef * method_list)129 void add_functions_to_py_module(PyObject *module, PyMethodDef *method_list)
130 {
131 	PyObject *dict = PyModule_GetDict(module);
132 	PyObject *name = PyModule_GetNameObject(module);
133 	if (!dict || !name) {
134 		return;
135 	}
136 	for (PyMethodDef *ml = method_list; ml->ml_name != NULL; ml++) {
137 		PyObject *func = PyCFunction_NewEx(ml, module, name);
138 		if (!func) {
139 			continue;
140 		}
141 		PyDict_SetItemString(dict, ml->ml_name, func);
142 		Py_DECREF(func);
143 	}
144 	Py_DECREF(name);
145 }
146 
147 /* -------------------------------------------- */
148 
py_get_current_script_path(PyObject * self,PyObject * args)149 static PyObject *py_get_current_script_path(PyObject *self, PyObject *args)
150 {
151 	PyObject *dir;
152 
153 	UNUSED_PARAMETER(args);
154 
155 	dir = PyDict_GetItemString(PyModule_GetDict(self), "__script_dir__");
156 	Py_XINCREF(dir);
157 	return dir;
158 }
159 
get_defaults(struct obs_python_script * data,PyObject * get_defs)160 static void get_defaults(struct obs_python_script *data, PyObject *get_defs)
161 {
162 	PyObject *py_settings;
163 	if (!libobs_to_py(obs_data_t, data->base.settings, false, &py_settings))
164 		return;
165 
166 	PyObject *args = Py_BuildValue("(O)", py_settings);
167 	PyObject *py_ret = PyObject_CallObject(get_defs, args);
168 	py_error();
169 	Py_XDECREF(py_ret);
170 	Py_XDECREF(args);
171 	Py_XDECREF(py_settings);
172 }
173 
load_python_script(struct obs_python_script * data)174 static bool load_python_script(struct obs_python_script *data)
175 {
176 	PyObject *py_file = NULL;
177 	PyObject *py_module = NULL;
178 	PyObject *py_success = NULL;
179 	PyObject *py_tick = NULL;
180 	PyObject *py_load = NULL;
181 	PyObject *py_defaults = NULL;
182 	bool success = false;
183 	int ret;
184 
185 	cur_python_script = data;
186 
187 	if (!data->module) {
188 		py_file = PyUnicode_FromString(data->name.array);
189 		py_module = PyImport_Import(py_file);
190 	} else {
191 		py_module = PyImport_ReloadModule(data->module);
192 	}
193 
194 	if (!py_module) {
195 		py_error();
196 		goto fail;
197 	}
198 
199 	Py_XINCREF(py_obspython);
200 	ret = PyModule_AddObject(py_module, "obspython", py_obspython);
201 	if (py_error() || ret != 0)
202 		goto fail;
203 
204 	ret = PyModule_AddStringConstant(py_module, "__script_dir__",
205 					 data->dir.array);
206 	if (py_error() || ret != 0)
207 		goto fail;
208 
209 	PyObject *py_data = PyCapsule_New(data, NULL, NULL);
210 	ret = PyModule_AddObject(py_module, "__script_data__", py_data);
211 	if (py_error() || ret != 0)
212 		goto fail;
213 
214 	static PyMethodDef global_funcs[] = {
215 		{"script_path", py_get_current_script_path, METH_NOARGS,
216 		 "Gets the script path"},
217 		{0}};
218 
219 	add_functions_to_py_module(py_module, global_funcs);
220 
221 	data->update = PyObject_GetAttrString(py_module, "script_update");
222 	if (!data->update)
223 		PyErr_Clear();
224 
225 	data->save = PyObject_GetAttrString(py_module, "script_save");
226 	if (!data->save)
227 		PyErr_Clear();
228 
229 	data->get_properties =
230 		PyObject_GetAttrString(py_module, "script_properties");
231 	if (!data->get_properties)
232 		PyErr_Clear();
233 
234 	PyObject *func = PyObject_GetAttrString(py_module, "script_defaults");
235 	if (func) {
236 		get_defaults(data, func);
237 		Py_DECREF(func);
238 	} else {
239 		PyErr_Clear();
240 	}
241 
242 	func = PyObject_GetAttrString(py_module, "script_description");
243 	if (func) {
244 		PyObject *py_ret = PyObject_CallObject(func, NULL);
245 		py_error();
246 		PyObject *py_desc = PyUnicode_AsUTF8String(py_ret);
247 		if (py_desc) {
248 			const char *desc = PyBytes_AS_STRING(py_desc);
249 			if (desc)
250 				dstr_copy(&data->base.desc, desc);
251 			Py_DECREF(py_desc);
252 		}
253 		Py_XDECREF(py_ret);
254 		Py_DECREF(func);
255 	} else {
256 		PyErr_Clear();
257 	}
258 
259 	py_tick = PyObject_GetAttrString(py_module, "script_tick");
260 	if (py_tick) {
261 		pthread_mutex_lock(&tick_mutex);
262 
263 		struct obs_python_script *next = first_tick_script;
264 		data->next_tick = next;
265 		data->p_prev_next_tick = &first_tick_script;
266 		if (next)
267 			next->p_prev_next_tick = &data->next_tick;
268 		first_tick_script = data;
269 
270 		data->tick = py_tick;
271 		py_tick = NULL;
272 
273 		pthread_mutex_unlock(&tick_mutex);
274 	} else {
275 		PyErr_Clear();
276 	}
277 
278 	py_load = PyObject_GetAttrString(py_module, "script_load");
279 	if (py_load) {
280 		PyObject *py_s;
281 		libobs_to_py(obs_data_t, data->base.settings, false, &py_s);
282 		PyObject *args = Py_BuildValue("(O)", py_s);
283 		PyObject *py_ret = PyObject_CallObject(py_load, args);
284 		py_error();
285 		Py_XDECREF(py_ret);
286 		Py_XDECREF(args);
287 		Py_XDECREF(py_s);
288 	} else {
289 		PyErr_Clear();
290 	}
291 
292 	if (data->module)
293 		Py_XDECREF(data->module);
294 	data->module = py_module;
295 	py_module = NULL;
296 
297 	success = true;
298 
299 fail:
300 	Py_XDECREF(py_load);
301 	Py_XDECREF(py_tick);
302 	Py_XDECREF(py_defaults);
303 	Py_XDECREF(py_success);
304 	Py_XDECREF(py_file);
305 	if (!success)
306 		Py_XDECREF(py_module);
307 	cur_python_script = NULL;
308 	return success;
309 }
310 
unload_python_script(struct obs_python_script * data)311 static void unload_python_script(struct obs_python_script *data)
312 {
313 	PyObject *py_module = data->module;
314 	PyObject *py_func = NULL;
315 	PyObject *py_ret = NULL;
316 
317 	cur_python_script = data;
318 
319 	py_func = PyObject_GetAttrString(py_module, "script_unload");
320 	if (PyErr_Occurred() || !py_func) {
321 		PyErr_Clear();
322 		goto fail;
323 	}
324 
325 	py_ret = PyObject_CallObject(py_func, NULL);
326 	if (py_error())
327 		goto fail;
328 
329 fail:
330 	Py_XDECREF(py_ret);
331 	Py_XDECREF(py_func);
332 
333 	cur_python_script = NULL;
334 }
335 
add_to_python_path(const char * path)336 static void add_to_python_path(const char *path)
337 {
338 	PyObject *py_path_str = NULL;
339 	PyObject *py_path = NULL;
340 	int ret;
341 
342 	if (!path || !*path)
343 		return;
344 
345 	for (size_t i = 0; i < python_paths.num; i++) {
346 		const char *python_path = python_paths.array[i];
347 		if (strcmp(path, python_path) == 0)
348 			return;
349 	}
350 
351 	ret = PyRun_SimpleString("import sys");
352 	if (py_error() || ret != 0)
353 		goto fail;
354 
355 	/* borrowed reference here */
356 	py_path = PySys_GetObject("path");
357 	if (py_error() || !py_path)
358 		goto fail;
359 
360 	py_path_str = PyUnicode_FromString(path);
361 	ret = PyList_Append(py_path, py_path_str);
362 	if (py_error() || ret != 0)
363 		goto fail;
364 
365 	char *new_path = bstrdup(path);
366 	da_push_back(python_paths, &new_path);
367 
368 fail:
369 	Py_XDECREF(py_path_str);
370 }
371 
372 /* -------------------------------------------- */
373 
374 struct python_obs_timer {
375 	struct python_obs_timer *next;
376 	struct python_obs_timer **p_prev_next;
377 
378 	uint64_t last_ts;
379 	uint64_t interval;
380 };
381 
382 static pthread_mutex_t timer_mutex;
383 static struct python_obs_timer *first_timer = NULL;
384 
python_obs_timer_init(struct python_obs_timer * timer)385 static inline void python_obs_timer_init(struct python_obs_timer *timer)
386 {
387 	pthread_mutex_lock(&timer_mutex);
388 
389 	struct python_obs_timer *next = first_timer;
390 	timer->next = next;
391 	timer->p_prev_next = &first_timer;
392 	if (next)
393 		next->p_prev_next = &timer->next;
394 	first_timer = timer;
395 
396 	pthread_mutex_unlock(&timer_mutex);
397 }
398 
python_obs_timer_remove(struct python_obs_timer * timer)399 static inline void python_obs_timer_remove(struct python_obs_timer *timer)
400 {
401 	struct python_obs_timer *next = timer->next;
402 	if (next)
403 		next->p_prev_next = timer->p_prev_next;
404 	*timer->p_prev_next = timer->next;
405 }
406 
407 static inline struct python_obs_callback *
python_obs_timer_cb(struct python_obs_timer * timer)408 python_obs_timer_cb(struct python_obs_timer *timer)
409 {
410 	return &((struct python_obs_callback *)timer)[-1];
411 }
412 
timer_remove(PyObject * self,PyObject * args)413 static PyObject *timer_remove(PyObject *self, PyObject *args)
414 {
415 	struct obs_python_script *script = cur_python_script;
416 	PyObject *py_cb;
417 
418 	UNUSED_PARAMETER(self);
419 
420 	if (!parse_args(args, "O", &py_cb))
421 		return python_none();
422 
423 	struct python_obs_callback *cb =
424 		find_python_obs_callback(script, py_cb);
425 	if (cb)
426 		remove_python_obs_callback(cb);
427 	return python_none();
428 }
429 
timer_call(struct script_callback * p_cb)430 static void timer_call(struct script_callback *p_cb)
431 {
432 	struct python_obs_callback *cb = (struct python_obs_callback *)p_cb;
433 
434 	if (p_cb->removed)
435 		return;
436 
437 	lock_callback(cb);
438 	PyObject *py_ret = PyObject_CallObject(cb->func, NULL);
439 	py_error();
440 	Py_XDECREF(py_ret);
441 	unlock_callback();
442 }
443 
defer_timer_init(void * p_cb)444 static void defer_timer_init(void *p_cb)
445 {
446 	struct python_obs_callback *cb = p_cb;
447 	struct python_obs_timer *timer = python_obs_callback_extra_data(cb);
448 	python_obs_timer_init(timer);
449 }
450 
timer_add(PyObject * self,PyObject * args)451 static PyObject *timer_add(PyObject *self, PyObject *args)
452 {
453 	struct obs_python_script *script = cur_python_script;
454 	PyObject *py_cb;
455 	int ms;
456 
457 	UNUSED_PARAMETER(self);
458 
459 	if (!parse_args(args, "Oi", &py_cb, &ms))
460 		return python_none();
461 
462 	struct python_obs_callback *cb = add_python_obs_callback_extra(
463 		script, py_cb, sizeof(struct python_obs_timer));
464 	struct python_obs_timer *timer = python_obs_callback_extra_data(cb);
465 
466 	timer->interval = (uint64_t)ms * 1000000ULL;
467 	timer->last_ts = obs_get_video_frame_time();
468 
469 	defer_call_post(defer_timer_init, cb);
470 	return python_none();
471 }
472 
473 /* -------------------------------------------- */
474 
obs_python_tick_callback(void * priv,float seconds)475 static void obs_python_tick_callback(void *priv, float seconds)
476 {
477 	struct python_obs_callback *cb = priv;
478 
479 	if (cb->base.removed) {
480 		obs_remove_tick_callback(obs_python_tick_callback, cb);
481 		return;
482 	}
483 
484 	lock_callback(cb);
485 
486 	PyObject *args = Py_BuildValue("(f)", seconds);
487 	PyObject *py_ret = PyObject_CallObject(cb->func, args);
488 	py_error();
489 	Py_XDECREF(py_ret);
490 	Py_XDECREF(args);
491 
492 	unlock_callback();
493 }
494 
obs_python_remove_tick_callback(PyObject * self,PyObject * args)495 static PyObject *obs_python_remove_tick_callback(PyObject *self, PyObject *args)
496 {
497 	struct obs_python_script *script = cur_python_script;
498 	PyObject *py_cb = NULL;
499 
500 	if (!script) {
501 		PyErr_SetString(PyExc_RuntimeError,
502 				"No active script, report this to Jim");
503 		return NULL;
504 	}
505 
506 	UNUSED_PARAMETER(self);
507 
508 	if (!parse_args(args, "O", &py_cb))
509 		return python_none();
510 	if (!py_cb || !PyFunction_Check(py_cb))
511 		return python_none();
512 
513 	struct python_obs_callback *cb =
514 		find_python_obs_callback(script, py_cb);
515 	if (cb)
516 		remove_python_obs_callback(cb);
517 	return python_none();
518 }
519 
obs_python_add_tick_callback(PyObject * self,PyObject * args)520 static PyObject *obs_python_add_tick_callback(PyObject *self, PyObject *args)
521 {
522 	struct obs_python_script *script = cur_python_script;
523 	PyObject *py_cb = NULL;
524 
525 	if (!script) {
526 		PyErr_SetString(PyExc_RuntimeError,
527 				"No active script, report this to Jim");
528 		return NULL;
529 	}
530 
531 	UNUSED_PARAMETER(self);
532 
533 	if (!parse_args(args, "O", &py_cb))
534 		return python_none();
535 	if (!py_cb || !PyFunction_Check(py_cb))
536 		return python_none();
537 
538 	struct python_obs_callback *cb = add_python_obs_callback(script, py_cb);
539 	obs_add_tick_callback(obs_python_tick_callback, cb);
540 	return python_none();
541 }
542 
543 /* -------------------------------------------- */
544 
calldata_signal_callback(void * priv,calldata_t * cd)545 static void calldata_signal_callback(void *priv, calldata_t *cd)
546 {
547 	struct python_obs_callback *cb = priv;
548 
549 	if (cb->base.removed) {
550 		signal_handler_remove_current();
551 		return;
552 	}
553 
554 	lock_callback(cb);
555 
556 	PyObject *py_cd;
557 
558 	if (libobs_to_py(calldata_t, cd, false, &py_cd)) {
559 		PyObject *args = Py_BuildValue("(O)", py_cd);
560 		PyObject *py_ret = PyObject_CallObject(cb->func, args);
561 		py_error();
562 		Py_XDECREF(py_ret);
563 		Py_XDECREF(args);
564 		Py_XDECREF(py_cd);
565 	}
566 
567 	unlock_callback();
568 }
569 
obs_python_signal_handler_disconnect(PyObject * self,PyObject * args)570 static PyObject *obs_python_signal_handler_disconnect(PyObject *self,
571 						      PyObject *args)
572 {
573 	struct obs_python_script *script = cur_python_script;
574 	PyObject *py_sh = NULL;
575 	PyObject *py_cb = NULL;
576 	const char *signal;
577 
578 	if (!script) {
579 		PyErr_SetString(PyExc_RuntimeError,
580 				"No active script, report this to Jim");
581 		return NULL;
582 	}
583 
584 	UNUSED_PARAMETER(self);
585 
586 	signal_handler_t *handler;
587 
588 	if (!parse_args(args, "OsO", &py_sh, &signal, &py_cb))
589 		return python_none();
590 
591 	if (!py_to_libobs(signal_handler_t, py_sh, &handler))
592 		return python_none();
593 	if (!py_cb || !PyFunction_Check(py_cb))
594 		return python_none();
595 
596 	struct python_obs_callback *cb =
597 		find_python_obs_callback(script, py_cb);
598 	while (cb) {
599 		signal_handler_t *cb_handler =
600 			calldata_ptr(&cb->base.extra, "handler");
601 		const char *cb_signal =
602 			calldata_string(&cb->base.extra, "signal");
603 
604 		if (cb_signal && strcmp(signal, cb_signal) == 0 &&
605 		    handler == cb_handler)
606 			break;
607 
608 		cb = find_next_python_obs_callback(script, cb, py_cb);
609 	}
610 
611 	if (cb)
612 		remove_python_obs_callback(cb);
613 	return python_none();
614 }
615 
obs_python_signal_handler_connect(PyObject * self,PyObject * args)616 static PyObject *obs_python_signal_handler_connect(PyObject *self,
617 						   PyObject *args)
618 {
619 	struct obs_python_script *script = cur_python_script;
620 	PyObject *py_sh = NULL;
621 	PyObject *py_cb = NULL;
622 	const char *signal;
623 
624 	if (!script) {
625 		PyErr_SetString(PyExc_RuntimeError,
626 				"No active script, report this to Jim");
627 		return NULL;
628 	}
629 
630 	UNUSED_PARAMETER(self);
631 
632 	signal_handler_t *handler;
633 
634 	if (!parse_args(args, "OsO", &py_sh, &signal, &py_cb))
635 		return python_none();
636 	if (!py_to_libobs(signal_handler_t, py_sh, &handler))
637 		return python_none();
638 	if (!py_cb || !PyFunction_Check(py_cb))
639 		return python_none();
640 
641 	struct python_obs_callback *cb = add_python_obs_callback(script, py_cb);
642 	calldata_set_ptr(&cb->base.extra, "handler", handler);
643 	calldata_set_string(&cb->base.extra, "signal", signal);
644 	signal_handler_connect(handler, signal, calldata_signal_callback, cb);
645 	return python_none();
646 }
647 
648 /* -------------------------------------------- */
649 
calldata_signal_callback_global(void * priv,const char * signal,calldata_t * cd)650 static void calldata_signal_callback_global(void *priv, const char *signal,
651 					    calldata_t *cd)
652 {
653 	struct python_obs_callback *cb = priv;
654 
655 	if (cb->base.removed) {
656 		signal_handler_remove_current();
657 		return;
658 	}
659 
660 	lock_callback(cb);
661 
662 	PyObject *py_cd;
663 
664 	if (libobs_to_py(calldata_t, cd, false, &py_cd)) {
665 		PyObject *args = Py_BuildValue("(sO)", signal, py_cd);
666 		PyObject *py_ret = PyObject_CallObject(cb->func, args);
667 		py_error();
668 		Py_XDECREF(py_ret);
669 		Py_XDECREF(args);
670 		Py_XDECREF(py_cd);
671 	}
672 
673 	unlock_callback();
674 }
675 
obs_python_signal_handler_disconnect_global(PyObject * self,PyObject * args)676 static PyObject *obs_python_signal_handler_disconnect_global(PyObject *self,
677 							     PyObject *args)
678 {
679 	struct obs_python_script *script = cur_python_script;
680 	PyObject *py_sh = NULL;
681 	PyObject *py_cb = NULL;
682 
683 	if (!script) {
684 		PyErr_SetString(PyExc_RuntimeError,
685 				"No active script, report this to Jim");
686 		return NULL;
687 	}
688 
689 	UNUSED_PARAMETER(self);
690 
691 	signal_handler_t *handler;
692 
693 	if (!parse_args(args, "OO", &py_sh, &py_cb))
694 		return python_none();
695 
696 	if (!py_to_libobs(signal_handler_t, py_sh, &handler))
697 		return python_none();
698 	if (!py_cb || !PyFunction_Check(py_cb))
699 		return python_none();
700 
701 	struct python_obs_callback *cb =
702 		find_python_obs_callback(script, py_cb);
703 	while (cb) {
704 		signal_handler_t *cb_handler =
705 			calldata_ptr(&cb->base.extra, "handler");
706 
707 		if (handler == cb_handler)
708 			break;
709 
710 		cb = find_next_python_obs_callback(script, cb, py_cb);
711 	}
712 
713 	if (cb)
714 		remove_python_obs_callback(cb);
715 	return python_none();
716 }
717 
obs_python_signal_handler_connect_global(PyObject * self,PyObject * args)718 static PyObject *obs_python_signal_handler_connect_global(PyObject *self,
719 							  PyObject *args)
720 {
721 	struct obs_python_script *script = cur_python_script;
722 	PyObject *py_sh = NULL;
723 	PyObject *py_cb = NULL;
724 
725 	if (!script) {
726 		PyErr_SetString(PyExc_RuntimeError,
727 				"No active script, report this to Jim");
728 		return NULL;
729 	}
730 
731 	UNUSED_PARAMETER(self);
732 
733 	signal_handler_t *handler;
734 
735 	if (!parse_args(args, "OO", &py_sh, &py_cb))
736 		return python_none();
737 
738 	if (!py_to_libobs(signal_handler_t, py_sh, &handler))
739 		return python_none();
740 	if (!py_cb || !PyFunction_Check(py_cb))
741 		return python_none();
742 
743 	struct python_obs_callback *cb = add_python_obs_callback(script, py_cb);
744 	calldata_set_ptr(&cb->base.extra, "handler", handler);
745 	signal_handler_connect_global(handler, calldata_signal_callback_global,
746 				      cb);
747 	return python_none();
748 }
749 
750 /* -------------------------------------------- */
751 
defer_hotkey_unregister(void * p_cb)752 static void defer_hotkey_unregister(void *p_cb)
753 {
754 	obs_hotkey_unregister((obs_hotkey_id)(uintptr_t)p_cb);
755 }
756 
on_remove_hotkey(void * p_cb)757 static void on_remove_hotkey(void *p_cb)
758 {
759 	struct python_obs_callback *cb = p_cb;
760 	obs_hotkey_id id = (obs_hotkey_id)calldata_int(&cb->base.extra, "id");
761 
762 	if (id != OBS_INVALID_HOTKEY_ID)
763 		defer_call_post(defer_hotkey_unregister, (void *)(uintptr_t)id);
764 }
765 
hotkey_pressed(void * p_cb,bool pressed)766 static void hotkey_pressed(void *p_cb, bool pressed)
767 {
768 	struct python_obs_callback *cb = p_cb;
769 
770 	if (cb->base.removed)
771 		return;
772 
773 	lock_callback(cb);
774 
775 	PyObject *py_pressed = PyBool_FromLong(pressed);
776 	PyObject *args = Py_BuildValue("(O)", py_pressed);
777 	PyObject *py_ret = PyObject_CallObject(cb->func, args);
778 	py_error();
779 	Py_XDECREF(py_ret);
780 	Py_XDECREF(args);
781 	Py_XDECREF(py_pressed);
782 
783 	unlock_callback();
784 }
785 
defer_hotkey_pressed(void * p_cb)786 static void defer_hotkey_pressed(void *p_cb)
787 {
788 	hotkey_pressed(p_cb, true);
789 }
790 
defer_hotkey_unpressed(void * p_cb)791 static void defer_hotkey_unpressed(void *p_cb)
792 {
793 	hotkey_pressed(p_cb, false);
794 }
795 
py_invalid_hotkey_id()796 static inline PyObject *py_invalid_hotkey_id()
797 {
798 	return PyLong_FromUnsignedLongLong(OBS_INVALID_HOTKEY_ID);
799 }
800 
hotkey_callback(void * p_cb,obs_hotkey_id id,obs_hotkey_t * hotkey,bool pressed)801 static void hotkey_callback(void *p_cb, obs_hotkey_id id, obs_hotkey_t *hotkey,
802 			    bool pressed)
803 {
804 	struct python_obs_callback *cb = p_cb;
805 
806 	if (cb->base.removed)
807 		return;
808 
809 	if (pressed)
810 		defer_call_post(defer_hotkey_pressed, cb);
811 	else
812 		defer_call_post(defer_hotkey_unpressed, cb);
813 
814 	UNUSED_PARAMETER(hotkey);
815 	UNUSED_PARAMETER(id);
816 }
817 
hotkey_unregister(PyObject * self,PyObject * args)818 static PyObject *hotkey_unregister(PyObject *self, PyObject *args)
819 {
820 	struct obs_python_script *script = cur_python_script;
821 	PyObject *py_cb = NULL;
822 
823 	if (!script) {
824 		PyErr_SetString(PyExc_RuntimeError,
825 				"No active script, report this to Jim");
826 		return NULL;
827 	}
828 
829 	if (!parse_args(args, "O", &py_cb))
830 		return python_none();
831 	if (!py_cb || !PyFunction_Check(py_cb))
832 		return python_none();
833 
834 	struct python_obs_callback *cb =
835 		find_python_obs_callback(script, py_cb);
836 	if (cb)
837 		remove_python_obs_callback(cb);
838 
839 	UNUSED_PARAMETER(self);
840 	return python_none();
841 }
842 
hotkey_register_frontend(PyObject * self,PyObject * args)843 static PyObject *hotkey_register_frontend(PyObject *self, PyObject *args)
844 {
845 	struct obs_python_script *script = cur_python_script;
846 	const char *name;
847 	const char *desc;
848 	obs_hotkey_id id;
849 	PyObject *py_cb;
850 
851 	if (!parse_args(args, "ssO", &name, &desc, &py_cb))
852 		return py_invalid_hotkey_id();
853 	if (!py_cb || !PyFunction_Check(py_cb))
854 		return py_invalid_hotkey_id();
855 
856 	struct python_obs_callback *cb = add_python_obs_callback(script, py_cb);
857 	cb->base.on_remove = on_remove_hotkey;
858 	id = obs_hotkey_register_frontend(name, desc, hotkey_callback, cb);
859 	calldata_set_int(&cb->base.extra, "id", id);
860 
861 	if (id == OBS_INVALID_HOTKEY_ID)
862 		remove_python_obs_callback(cb);
863 
864 	UNUSED_PARAMETER(self);
865 	return PyLong_FromUnsignedLongLong(id);
866 }
867 
868 /* -------------------------------------------- */
869 
button_prop_clicked(obs_properties_t * props,obs_property_t * p,void * p_cb)870 static bool button_prop_clicked(obs_properties_t *props, obs_property_t *p,
871 				void *p_cb)
872 {
873 	struct python_obs_callback *cb = p_cb;
874 	bool ret = false;
875 
876 	if (cb->base.removed)
877 		return false;
878 
879 	lock_callback(cb);
880 
881 	PyObject *py_props = NULL;
882 	PyObject *py_p = NULL;
883 
884 	if (libobs_to_py(obs_properties_t, props, false, &py_props) &&
885 	    libobs_to_py(obs_property_t, p, false, &py_p)) {
886 
887 		PyObject *args = Py_BuildValue("(OO)", py_props, py_p);
888 		PyObject *py_ret = PyObject_CallObject(cb->func, args);
889 		if (!py_error())
890 			ret = py_ret == Py_True;
891 		Py_XDECREF(py_ret);
892 		Py_XDECREF(args);
893 	}
894 
895 	Py_XDECREF(py_p);
896 	Py_XDECREF(py_props);
897 
898 	unlock_callback();
899 
900 	return ret;
901 }
902 
properties_add_button(PyObject * self,PyObject * args)903 static PyObject *properties_add_button(PyObject *self, PyObject *args)
904 {
905 	struct obs_python_script *script = cur_python_script;
906 	obs_properties_t *props;
907 	obs_property_t *p;
908 	PyObject *py_props;
909 	PyObject *py_ret;
910 	const char *name;
911 	const char *text;
912 	PyObject *py_cb;
913 
914 	if (!parse_args(args, "OssO", &py_props, &name, &text, &py_cb))
915 		return python_none();
916 	if (!py_to_libobs(obs_properties_t, py_props, &props))
917 		return python_none();
918 	if (!py_cb || !PyFunction_Check(py_cb))
919 		return python_none();
920 
921 	struct python_obs_callback *cb = add_python_obs_callback(script, py_cb);
922 	p = obs_properties_add_button2(props, name, text, button_prop_clicked,
923 				       cb);
924 
925 	if (!p || !libobs_to_py(obs_property_t, p, false, &py_ret))
926 		return python_none();
927 
928 	UNUSED_PARAMETER(self);
929 	return py_ret;
930 }
931 
932 /* -------------------------------------------- */
933 
modified_callback(void * p_cb,obs_properties_t * props,obs_property_t * p,obs_data_t * settings)934 static bool modified_callback(void *p_cb, obs_properties_t *props,
935 			      obs_property_t *p, obs_data_t *settings)
936 {
937 	struct python_obs_callback *cb = p_cb;
938 	bool ret = false;
939 
940 	if (cb->base.removed)
941 		return false;
942 
943 	lock_callback(cb);
944 
945 	PyObject *py_props = NULL;
946 	PyObject *py_p = NULL;
947 	PyObject *py_settings = NULL;
948 
949 	if (libobs_to_py(obs_properties_t, props, false, &py_props) &&
950 	    libobs_to_py(obs_property_t, p, false, &py_p) &&
951 	    libobs_to_py(obs_data_t, settings, false, &py_settings)) {
952 
953 		PyObject *args =
954 			Py_BuildValue("(OOO)", py_props, py_p, py_settings);
955 		PyObject *py_ret = PyObject_CallObject(cb->func, args);
956 		if (!py_error())
957 			ret = py_ret == Py_True;
958 		Py_XDECREF(py_ret);
959 		Py_XDECREF(args);
960 	}
961 
962 	Py_XDECREF(py_settings);
963 	Py_XDECREF(py_p);
964 	Py_XDECREF(py_props);
965 
966 	unlock_callback();
967 
968 	return ret;
969 }
970 
property_set_modified_callback(PyObject * self,PyObject * args)971 static PyObject *property_set_modified_callback(PyObject *self, PyObject *args)
972 {
973 	struct obs_python_script *script = cur_python_script;
974 	PyObject *py_p;
975 	PyObject *py_cb;
976 	obs_property_t *p;
977 
978 	if (!parse_args(args, "OO", &py_p, &py_cb))
979 		return python_none();
980 	if (!py_to_libobs(obs_property_t, py_p, &p))
981 		return python_none();
982 	if (!py_cb || !PyFunction_Check(py_cb))
983 		return python_none();
984 
985 	struct python_obs_callback *cb = add_python_obs_callback(script, py_cb);
986 	obs_property_set_modified_callback2(p, modified_callback, cb);
987 
988 	UNUSED_PARAMETER(self);
989 	return python_none();
990 }
991 
992 /* -------------------------------------------- */
993 
remove_current_callback(PyObject * self,PyObject * args)994 static PyObject *remove_current_callback(PyObject *self, PyObject *args)
995 {
996 	UNUSED_PARAMETER(self);
997 	UNUSED_PARAMETER(args);
998 
999 	if (cur_python_cb)
1000 		remove_python_obs_callback(cur_python_cb);
1001 	return python_none();
1002 }
1003 
1004 /* -------------------------------------------- */
1005 
calldata_source(PyObject * self,PyObject * args)1006 static PyObject *calldata_source(PyObject *self, PyObject *args)
1007 {
1008 	PyObject *py_ret = NULL;
1009 	PyObject *py_cd = NULL;
1010 
1011 	calldata_t *cd;
1012 	const char *name;
1013 
1014 	UNUSED_PARAMETER(self);
1015 
1016 	if (!parse_args(args, "Os", &py_cd, &name))
1017 		goto fail;
1018 	if (!py_to_libobs(calldata_t, py_cd, &cd))
1019 		goto fail;
1020 
1021 	obs_source_t *source = calldata_ptr(cd, name);
1022 	libobs_to_py(obs_source_t, source, false, &py_ret);
1023 
1024 fail:
1025 	return py_ret;
1026 }
1027 
calldata_sceneitem(PyObject * self,PyObject * args)1028 static PyObject *calldata_sceneitem(PyObject *self, PyObject *args)
1029 {
1030 	PyObject *py_ret = NULL;
1031 	PyObject *py_cd = NULL;
1032 
1033 	calldata_t *cd;
1034 	const char *name;
1035 
1036 	UNUSED_PARAMETER(self);
1037 
1038 	if (!parse_args(args, "Os", &py_cd, &name))
1039 		goto fail;
1040 	if (!py_to_libobs(calldata_t, py_cd, &cd))
1041 		goto fail;
1042 
1043 	obs_sceneitem_t *item = calldata_ptr(cd, name);
1044 	libobs_to_py(obs_sceneitem_t, item, false, &py_ret);
1045 
1046 fail:
1047 	return py_ret;
1048 }
1049 
1050 /* -------------------------------------------- */
1051 
enum_sources_proc(void * param,obs_source_t * source)1052 static bool enum_sources_proc(void *param, obs_source_t *source)
1053 {
1054 	PyObject *list = param;
1055 	PyObject *py_source;
1056 
1057 	if (libobs_to_py(obs_source_t, source, false, &py_source)) {
1058 		obs_source_get_ref(source);
1059 		PyList_Append(list, py_source);
1060 		Py_DECREF(py_source);
1061 	}
1062 	return true;
1063 }
1064 
enum_sources(PyObject * self,PyObject * args)1065 static PyObject *enum_sources(PyObject *self, PyObject *args)
1066 {
1067 	UNUSED_PARAMETER(self);
1068 	UNUSED_PARAMETER(args);
1069 
1070 	PyObject *list = PyList_New(0);
1071 	obs_enum_sources(enum_sources_proc, list);
1072 	return list;
1073 }
1074 
1075 /* -------------------------------------------- */
1076 
enum_items_proc(obs_scene_t * scene,obs_sceneitem_t * item,void * param)1077 static bool enum_items_proc(obs_scene_t *scene, obs_sceneitem_t *item,
1078 			    void *param)
1079 {
1080 	PyObject *list = param;
1081 	PyObject *py_item;
1082 
1083 	UNUSED_PARAMETER(scene);
1084 
1085 	if (libobs_to_py(obs_sceneitem_t, item, false, &py_item)) {
1086 		obs_sceneitem_addref(item);
1087 		PyList_Append(list, py_item);
1088 		Py_DECREF(py_item);
1089 	}
1090 	return true;
1091 }
1092 
scene_enum_items(PyObject * self,PyObject * args)1093 static PyObject *scene_enum_items(PyObject *self, PyObject *args)
1094 {
1095 	PyObject *py_scene;
1096 	obs_scene_t *scene;
1097 
1098 	UNUSED_PARAMETER(self);
1099 
1100 	if (!parse_args(args, "O", &py_scene))
1101 		return python_none();
1102 	if (!py_to_libobs(obs_scene_t, py_scene, &scene))
1103 		return python_none();
1104 
1105 	PyObject *list = PyList_New(0);
1106 	obs_scene_enum_items(scene, enum_items_proc, list);
1107 	return list;
1108 }
1109 
1110 /* -------------------------------------------- */
1111 
source_list_release(PyObject * self,PyObject * args)1112 static PyObject *source_list_release(PyObject *self, PyObject *args)
1113 {
1114 	PyObject *list;
1115 	if (!parse_args(args, "O", &list))
1116 		return python_none();
1117 
1118 	Py_ssize_t count = PyList_Size(list);
1119 	for (Py_ssize_t i = 0; i < count; i++) {
1120 		PyObject *py_source = PyList_GetItem(list, i);
1121 		obs_source_t *source;
1122 
1123 		if (py_to_libobs(obs_source_t, py_source, &source)) {
1124 			obs_source_release(source);
1125 		}
1126 	}
1127 
1128 	UNUSED_PARAMETER(self);
1129 	return python_none();
1130 }
1131 
sceneitem_list_release(PyObject * self,PyObject * args)1132 static PyObject *sceneitem_list_release(PyObject *self, PyObject *args)
1133 {
1134 	PyObject *list;
1135 	if (!parse_args(args, "O", &list))
1136 		return python_none();
1137 
1138 	Py_ssize_t count = PyList_Size(list);
1139 	for (Py_ssize_t i = 0; i < count; i++) {
1140 		PyObject *py_item = PyList_GetItem(list, i);
1141 		obs_sceneitem_t *item;
1142 
1143 		if (py_to_libobs(obs_sceneitem_t, py_item, &item)) {
1144 			obs_sceneitem_release(item);
1145 		}
1146 	}
1147 
1148 	UNUSED_PARAMETER(self);
1149 	return python_none();
1150 }
1151 
1152 /* -------------------------------------------- */
1153 
1154 struct dstr cur_py_log_chunk = {0};
1155 
py_script_log_internal(PyObject * self,PyObject * args,bool add_endl)1156 static PyObject *py_script_log_internal(PyObject *self, PyObject *args,
1157 					bool add_endl)
1158 {
1159 	static bool calling_self = false;
1160 	int log_level;
1161 	const char *msg;
1162 
1163 	UNUSED_PARAMETER(self);
1164 
1165 	if (calling_self)
1166 		return python_none();
1167 	calling_self = true;
1168 
1169 	/* ------------------- */
1170 
1171 	if (!parse_args(args, "is", &log_level, &msg))
1172 		goto fail;
1173 	if (!msg || !*msg)
1174 		goto fail;
1175 
1176 	dstr_cat(&cur_py_log_chunk, msg);
1177 	if (add_endl)
1178 		dstr_cat(&cur_py_log_chunk, "\n");
1179 
1180 	const char *start = cur_py_log_chunk.array;
1181 	char *endl = strchr(start, '\n');
1182 
1183 	while (endl) {
1184 		*endl = 0;
1185 		if (cur_python_script)
1186 			script_log(&cur_python_script->base, log_level, "%s",
1187 				   start);
1188 		else
1189 			script_log(NULL, log_level, "%s", start);
1190 		*endl = '\n';
1191 
1192 		start = endl + 1;
1193 		endl = strchr(start, '\n');
1194 	}
1195 
1196 	if (start) {
1197 		size_t len = strlen(start);
1198 		if (len)
1199 			memmove(cur_py_log_chunk.array, start, len);
1200 		dstr_resize(&cur_py_log_chunk, len);
1201 	}
1202 
1203 	/* ------------------- */
1204 
1205 fail:
1206 	calling_self = false;
1207 	return python_none();
1208 }
1209 
py_script_log_no_endl(PyObject * self,PyObject * args)1210 static PyObject *py_script_log_no_endl(PyObject *self, PyObject *args)
1211 {
1212 	return py_script_log_internal(self, args, false);
1213 }
1214 
py_script_log(PyObject * self,PyObject * args)1215 static PyObject *py_script_log(PyObject *self, PyObject *args)
1216 {
1217 	return py_script_log_internal(self, args, true);
1218 }
1219 
1220 /* -------------------------------------------- */
1221 
add_hook_functions(PyObject * module)1222 static void add_hook_functions(PyObject *module)
1223 {
1224 	static PyMethodDef funcs[] = {
1225 #define DEF_FUNC(n, c) {n, c, METH_VARARGS, NULL}
1226 
1227 		DEF_FUNC("script_log_no_endl", py_script_log_no_endl),
1228 		DEF_FUNC("script_log", py_script_log),
1229 		DEF_FUNC("timer_remove", timer_remove),
1230 		DEF_FUNC("timer_add", timer_add),
1231 		DEF_FUNC("calldata_source", calldata_source),
1232 		DEF_FUNC("calldata_sceneitem", calldata_sceneitem),
1233 		DEF_FUNC("source_list_release", source_list_release),
1234 		DEF_FUNC("sceneitem_list_release", sceneitem_list_release),
1235 		DEF_FUNC("obs_enum_sources", enum_sources),
1236 		DEF_FUNC("obs_scene_enum_items", scene_enum_items),
1237 		DEF_FUNC("obs_remove_tick_callback",
1238 			 obs_python_remove_tick_callback),
1239 		DEF_FUNC("obs_add_tick_callback", obs_python_add_tick_callback),
1240 		DEF_FUNC("signal_handler_disconnect",
1241 			 obs_python_signal_handler_disconnect),
1242 		DEF_FUNC("signal_handler_connect",
1243 			 obs_python_signal_handler_connect),
1244 		DEF_FUNC("signal_handler_disconnect_global",
1245 			 obs_python_signal_handler_disconnect_global),
1246 		DEF_FUNC("signal_handler_connect_global",
1247 			 obs_python_signal_handler_connect_global),
1248 		DEF_FUNC("obs_hotkey_unregister", hotkey_unregister),
1249 		DEF_FUNC("obs_hotkey_register_frontend",
1250 			 hotkey_register_frontend),
1251 		DEF_FUNC("obs_properties_add_button", properties_add_button),
1252 		DEF_FUNC("obs_property_set_modified_callback",
1253 			 property_set_modified_callback),
1254 		DEF_FUNC("remove_current_callback", remove_current_callback),
1255 
1256 #undef DEF_FUNC
1257 		{0}};
1258 
1259 	add_functions_to_py_module(module, funcs);
1260 }
1261 
1262 /* -------------------------------------------- */
1263 
1264 void obs_python_script_update(obs_script_t *script, obs_data_t *settings);
1265 
obs_python_script_load(obs_script_t * s)1266 bool obs_python_script_load(obs_script_t *s)
1267 {
1268 	struct obs_python_script *data = (struct obs_python_script *)s;
1269 	if (python_loaded && !data->base.loaded) {
1270 		lock_python();
1271 		if (!data->module)
1272 			add_to_python_path(data->dir.array);
1273 		data->base.loaded = load_python_script(data);
1274 		unlock_python();
1275 
1276 		if (data->base.loaded)
1277 			obs_python_script_update(s, NULL);
1278 	}
1279 
1280 	return data->base.loaded;
1281 }
1282 
obs_python_script_create(const char * path,obs_data_t * settings)1283 obs_script_t *obs_python_script_create(const char *path, obs_data_t *settings)
1284 {
1285 	struct obs_python_script *data = bzalloc(sizeof(*data));
1286 
1287 	data->base.type = OBS_SCRIPT_LANG_PYTHON;
1288 
1289 	dstr_copy(&data->base.path, path);
1290 	dstr_replace(&data->base.path, "\\", "/");
1291 	path = data->base.path.array;
1292 
1293 	const char *slash = path && *path ? strrchr(path, '/') : NULL;
1294 	if (slash) {
1295 		slash++;
1296 		dstr_copy(&data->base.file, slash);
1297 		dstr_left(&data->dir, &data->base.path, slash - path);
1298 	} else {
1299 		dstr_copy(&data->base.file, path);
1300 	}
1301 
1302 	path = data->base.file.array;
1303 	dstr_copy_dstr(&data->name, &data->base.file);
1304 
1305 	const char *ext = strstr(path, ".py");
1306 	if (ext)
1307 		dstr_resize(&data->name, ext - path);
1308 
1309 	data->base.settings = obs_data_create();
1310 	if (settings)
1311 		obs_data_apply(data->base.settings, settings);
1312 
1313 	if (!python_loaded)
1314 		return (obs_script_t *)data;
1315 
1316 	lock_python();
1317 	add_to_python_path(data->dir.array);
1318 	data->base.loaded = load_python_script(data);
1319 	if (data->base.loaded) {
1320 		cur_python_script = data;
1321 		obs_python_script_update(&data->base, NULL);
1322 		cur_python_script = NULL;
1323 	}
1324 	unlock_python();
1325 
1326 	return (obs_script_t *)data;
1327 }
1328 
obs_python_script_unload(obs_script_t * s)1329 void obs_python_script_unload(obs_script_t *s)
1330 {
1331 	struct obs_python_script *data = (struct obs_python_script *)s;
1332 
1333 	if (!s->loaded || !python_loaded)
1334 		return;
1335 
1336 	/* ---------------------------- */
1337 	/* unhook tick function         */
1338 
1339 	if (data->p_prev_next_tick) {
1340 		pthread_mutex_lock(&tick_mutex);
1341 
1342 		struct obs_python_script *next = data->next_tick;
1343 		if (next)
1344 			next->p_prev_next_tick = data->p_prev_next_tick;
1345 		*data->p_prev_next_tick = next;
1346 
1347 		pthread_mutex_unlock(&tick_mutex);
1348 
1349 		data->p_prev_next_tick = NULL;
1350 		data->next_tick = NULL;
1351 	}
1352 
1353 	lock_python();
1354 
1355 	Py_XDECREF(data->tick);
1356 	Py_XDECREF(data->save);
1357 	Py_XDECREF(data->update);
1358 	Py_XDECREF(data->get_properties);
1359 	data->tick = NULL;
1360 	data->save = NULL;
1361 	data->update = NULL;
1362 	data->get_properties = NULL;
1363 
1364 	/* ---------------------------- */
1365 	/* remove all callbacks         */
1366 
1367 	struct script_callback *cb = data->first_callback;
1368 	while (cb) {
1369 		struct script_callback *next = cb->next;
1370 		remove_script_callback(cb);
1371 		cb = next;
1372 	}
1373 
1374 	/* ---------------------------- */
1375 	/* unload                       */
1376 
1377 	unload_python_script(data);
1378 	unlock_python();
1379 
1380 	s->loaded = false;
1381 }
1382 
obs_python_script_destroy(obs_script_t * s)1383 void obs_python_script_destroy(obs_script_t *s)
1384 {
1385 	struct obs_python_script *data = (struct obs_python_script *)s;
1386 
1387 	if (data) {
1388 		if (python_loaded) {
1389 			lock_python();
1390 			Py_XDECREF(data->module);
1391 			unlock_python();
1392 		}
1393 
1394 		dstr_free(&data->base.path);
1395 		dstr_free(&data->base.file);
1396 		dstr_free(&data->base.desc);
1397 		obs_data_release(data->base.settings);
1398 		dstr_free(&data->dir);
1399 		dstr_free(&data->name);
1400 		bfree(data);
1401 	}
1402 }
1403 
obs_python_script_update(obs_script_t * s,obs_data_t * settings)1404 void obs_python_script_update(obs_script_t *s, obs_data_t *settings)
1405 {
1406 	struct obs_python_script *data = (struct obs_python_script *)s;
1407 
1408 	if (!s->loaded || !python_loaded)
1409 		return;
1410 	if (!data->update)
1411 		return;
1412 
1413 	if (settings)
1414 		obs_data_apply(s->settings, settings);
1415 
1416 	lock_python();
1417 	cur_python_script = data;
1418 
1419 	PyObject *py_settings;
1420 	if (libobs_to_py(obs_data_t, s->settings, false, &py_settings)) {
1421 		PyObject *args = Py_BuildValue("(O)", py_settings);
1422 		PyObject *ret = PyObject_CallObject(data->update, args);
1423 		py_error();
1424 
1425 		Py_XDECREF(ret);
1426 		Py_XDECREF(args);
1427 		Py_XDECREF(py_settings);
1428 	}
1429 
1430 	cur_python_script = NULL;
1431 	unlock_python();
1432 }
1433 
obs_python_script_get_properties(obs_script_t * s)1434 obs_properties_t *obs_python_script_get_properties(obs_script_t *s)
1435 {
1436 	struct obs_python_script *data = (struct obs_python_script *)s;
1437 	obs_properties_t *props = NULL;
1438 
1439 	if (!s->loaded || !python_loaded)
1440 		return NULL;
1441 	if (!data->get_properties)
1442 		return NULL;
1443 
1444 	lock_python();
1445 	cur_python_script = data;
1446 
1447 	PyObject *ret = PyObject_CallObject(data->get_properties, NULL);
1448 	if (!py_error())
1449 		py_to_libobs(obs_properties_t, ret, &props);
1450 	Py_XDECREF(ret);
1451 
1452 	cur_python_script = NULL;
1453 	unlock_python();
1454 
1455 	return props;
1456 }
1457 
obs_python_script_save(obs_script_t * s)1458 void obs_python_script_save(obs_script_t *s)
1459 {
1460 	struct obs_python_script *data = (struct obs_python_script *)s;
1461 
1462 	if (!s->loaded || !python_loaded)
1463 		return;
1464 	if (!data->save)
1465 		return;
1466 
1467 	lock_python();
1468 	cur_python_script = data;
1469 
1470 	PyObject *py_settings;
1471 	if (libobs_to_py(obs_data_t, s->settings, false, &py_settings)) {
1472 		PyObject *args = Py_BuildValue("(O)", py_settings);
1473 		PyObject *ret = PyObject_CallObject(data->save, args);
1474 		py_error();
1475 		Py_XDECREF(ret);
1476 		Py_XDECREF(args);
1477 		Py_XDECREF(py_settings);
1478 	}
1479 
1480 	cur_python_script = NULL;
1481 	unlock_python();
1482 }
1483 
1484 /* -------------------------------------------- */
1485 
python_tick(void * param,float seconds)1486 static void python_tick(void *param, float seconds)
1487 {
1488 	struct obs_python_script *data;
1489 	bool valid;
1490 	uint64_t ts = obs_get_video_frame_time();
1491 
1492 	pthread_mutex_lock(&tick_mutex);
1493 	valid = !!first_tick_script;
1494 	pthread_mutex_unlock(&tick_mutex);
1495 
1496 	/* --------------------------------- */
1497 	/* process script_tick calls         */
1498 
1499 	if (valid) {
1500 		lock_python();
1501 
1502 		PyObject *args = Py_BuildValue("(f)", seconds);
1503 
1504 		pthread_mutex_lock(&tick_mutex);
1505 		data = first_tick_script;
1506 		while (data) {
1507 			cur_python_script = data;
1508 
1509 			PyObject *py_ret =
1510 				PyObject_CallObject(data->tick, args);
1511 			Py_XDECREF(py_ret);
1512 			py_error();
1513 
1514 			data = data->next_tick;
1515 		}
1516 
1517 		cur_python_script = NULL;
1518 
1519 		pthread_mutex_unlock(&tick_mutex);
1520 
1521 		Py_XDECREF(args);
1522 
1523 		unlock_python();
1524 	}
1525 
1526 	/* --------------------------------- */
1527 	/* process timers                    */
1528 
1529 	pthread_mutex_lock(&timer_mutex);
1530 	struct python_obs_timer *timer = first_timer;
1531 	while (timer) {
1532 		struct python_obs_timer *next = timer->next;
1533 		struct python_obs_callback *cb = python_obs_timer_cb(timer);
1534 
1535 		if (cb->base.removed) {
1536 			python_obs_timer_remove(timer);
1537 		} else {
1538 			uint64_t elapsed = ts - timer->last_ts;
1539 
1540 			if (elapsed >= timer->interval) {
1541 				lock_python();
1542 				timer_call(&cb->base);
1543 				unlock_python();
1544 
1545 				timer->last_ts += timer->interval;
1546 			}
1547 		}
1548 
1549 		timer = next;
1550 	}
1551 	pthread_mutex_unlock(&timer_mutex);
1552 
1553 	UNUSED_PARAMETER(param);
1554 }
1555 
1556 /* -------------------------------------------- */
1557 
1558 void obs_python_unload(void);
1559 
obs_scripting_python_runtime_linked(void)1560 bool obs_scripting_python_runtime_linked(void)
1561 {
1562 	return (bool)RUNTIME_LINK;
1563 }
1564 
obs_scripting_python_loaded(void)1565 bool obs_scripting_python_loaded(void)
1566 {
1567 	return python_loaded;
1568 }
1569 
obs_python_load(void)1570 void obs_python_load(void)
1571 {
1572 	da_init(python_paths);
1573 
1574 	pthread_mutex_init(&tick_mutex, NULL);
1575 	pthread_mutex_init_recursive(&timer_mutex);
1576 
1577 	mutexes_loaded = true;
1578 }
1579 
1580 extern void add_python_frontend_funcs(PyObject *module);
1581 
1582 static bool python_loaded_at_all = false;
1583 
obs_scripting_load_python(const char * python_path)1584 bool obs_scripting_load_python(const char *python_path)
1585 {
1586 	if (python_loaded)
1587 		return true;
1588 
1589 		/* Use external python on windows and mac */
1590 #if RUNTIME_LINK
1591 #if 0
1592 	struct dstr old_path  = {0};
1593 	struct dstr new_path  = {0};
1594 #endif
1595 
1596 	if (!import_python(python_path))
1597 		return false;
1598 
1599 	if (python_path && *python_path) {
1600 		os_utf8_to_wcs(python_path, 0, home_path, 1024);
1601 		Py_SetPythonHome(home_path);
1602 #if 0
1603 		dstr_copy(&old_path, getenv("PATH"));
1604 		_putenv("PYTHONPATH=");
1605 		_putenv("PATH=");
1606 #endif
1607 	}
1608 #else
1609 	UNUSED_PARAMETER(python_path);
1610 #endif
1611 
1612 	Py_Initialize();
1613 	if (!Py_IsInitialized())
1614 		return false;
1615 
1616 #if 0
1617 #ifdef _DEBUG
1618 	if (pythondir && *pythondir) {
1619 		dstr_printf(&new_path, "PATH=%s", old_path.array);
1620 		_putenv(new_path.array);
1621 	}
1622 #endif
1623 
1624 	bfree(pythondir);
1625 	dstr_free(&new_path);
1626 	dstr_free(&old_path);
1627 #endif
1628 
1629 	PyEval_InitThreads();
1630 	if (!PyEval_ThreadsInitialized())
1631 		return false;
1632 
1633 	/* ---------------------------------------------- */
1634 	/* Must set arguments for guis to work            */
1635 
1636 	wchar_t *argv[] = {L"", NULL};
1637 	int argc = sizeof(argv) / sizeof(wchar_t *) - 1;
1638 
1639 	PySys_SetArgv(argc, argv);
1640 
1641 #ifdef DEBUG_PYTHON_STARTUP
1642 	/* ---------------------------------------------- */
1643 	/* Debug logging to file if startup is failing    */
1644 
1645 	PyRun_SimpleString("import os");
1646 	PyRun_SimpleString("import sys");
1647 	PyRun_SimpleString("os.environ['PYTHONUNBUFFERED'] = '1'");
1648 	PyRun_SimpleString("sys.stdout = open('./stdOut.txt','w',1)");
1649 	PyRun_SimpleString("sys.stderr = open('./stdErr.txt','w',1)");
1650 	PyRun_SimpleString("print(sys.version)");
1651 #endif
1652 
1653 	/* ---------------------------------------------- */
1654 	/* Load main interface module                     */
1655 
1656 	char *absolute_script_path = os_get_abs_path_ptr(SCRIPT_DIR);
1657 	add_to_python_path(absolute_script_path);
1658 	bfree(absolute_script_path);
1659 
1660 #if __APPLE__
1661 	char *exec_path = os_get_executable_path_ptr("");
1662 	if (exec_path)
1663 		add_to_python_path(exec_path);
1664 	bfree(exec_path);
1665 #endif
1666 
1667 	py_obspython = PyImport_ImportModule("obspython");
1668 	bool success = !py_error();
1669 	if (!success) {
1670 		warn("Error importing obspython.py', unloading obs-python");
1671 		goto out;
1672 	}
1673 
1674 	python_loaded = PyRun_SimpleString(startup_script) == 0;
1675 	py_error();
1676 
1677 	add_hook_functions(py_obspython);
1678 	py_error();
1679 
1680 	add_python_frontend_funcs(py_obspython);
1681 	py_error();
1682 
1683 out:
1684 	/* ---------------------------------------------- */
1685 	/* Free data                                      */
1686 
1687 	PyEval_ReleaseThread(PyGILState_GetThisThreadState());
1688 
1689 	if (!success) {
1690 		warn("Failed to load python plugin");
1691 		obs_python_unload();
1692 	}
1693 
1694 	python_loaded_at_all = success;
1695 
1696 	if (python_loaded)
1697 		obs_add_tick_callback(python_tick, NULL);
1698 
1699 	return python_loaded;
1700 }
1701 
obs_python_unload(void)1702 void obs_python_unload(void)
1703 {
1704 	if (mutexes_loaded) {
1705 		pthread_mutex_destroy(&tick_mutex);
1706 		pthread_mutex_destroy(&timer_mutex);
1707 	}
1708 
1709 	if (!python_loaded_at_all)
1710 		return;
1711 
1712 	if (python_loaded && Py_IsInitialized()) {
1713 		PyGILState_Ensure();
1714 
1715 		Py_XDECREF(py_obspython);
1716 		Py_Finalize();
1717 	}
1718 
1719 	/* ---------------------- */
1720 
1721 	obs_remove_tick_callback(python_tick, NULL);
1722 
1723 	for (size_t i = 0; i < python_paths.num; i++)
1724 		bfree(python_paths.array[i]);
1725 	da_free(python_paths);
1726 
1727 	dstr_free(&cur_py_log_chunk);
1728 
1729 	python_loaded_at_all = false;
1730 }
1731