obs-scripting-python.c 43 KB

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