obs-scripting-python.c 41 KB

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