obs-scripting-python.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821
  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,
  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 Lain");
  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 Lain");
  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 Lain");
  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 Lain");
  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 Lain");
  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 Lain");
  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 Lain");
  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. static PyObject *sceneitem_group_enum_items(PyObject *self, PyObject *args)
  875. {
  876. PyObject *py_sceneitem;
  877. obs_sceneitem_t *sceneitem;
  878. UNUSED_PARAMETER(self);
  879. if (!parse_args(args, "O", &py_sceneitem))
  880. return python_none();
  881. if (!py_to_libobs(obs_sceneitem_t, py_sceneitem, &sceneitem))
  882. return python_none();
  883. PyObject *list = PyList_New(0);
  884. obs_sceneitem_group_enum_items(sceneitem, enum_items_proc, list);
  885. return list;
  886. }
  887. /* -------------------------------------------- */
  888. static PyObject *source_list_release(PyObject *self, PyObject *args)
  889. {
  890. PyObject *list;
  891. if (!parse_args(args, "O", &list))
  892. return python_none();
  893. Py_ssize_t count = PyList_Size(list);
  894. for (Py_ssize_t i = 0; i < count; i++) {
  895. PyObject *py_source = PyList_GetItem(list, i);
  896. obs_source_t *source;
  897. if (py_to_libobs(obs_source_t, py_source, &source)) {
  898. obs_source_release(source);
  899. }
  900. }
  901. UNUSED_PARAMETER(self);
  902. return python_none();
  903. }
  904. static PyObject *sceneitem_list_release(PyObject *self, PyObject *args)
  905. {
  906. PyObject *list;
  907. if (!parse_args(args, "O", &list))
  908. return python_none();
  909. Py_ssize_t count = PyList_Size(list);
  910. for (Py_ssize_t i = 0; i < count; i++) {
  911. PyObject *py_item = PyList_GetItem(list, i);
  912. obs_sceneitem_t *item;
  913. if (py_to_libobs(obs_sceneitem_t, py_item, &item)) {
  914. obs_sceneitem_release(item);
  915. }
  916. }
  917. UNUSED_PARAMETER(self);
  918. return python_none();
  919. }
  920. /* -------------------------------------------- */
  921. struct dstr cur_py_log_chunk = {0};
  922. static PyObject *py_script_log_internal(PyObject *self, PyObject *args,
  923. bool add_endl)
  924. {
  925. static bool calling_self = false;
  926. int log_level;
  927. const char *msg;
  928. UNUSED_PARAMETER(self);
  929. if (calling_self)
  930. return python_none();
  931. calling_self = true;
  932. /* ------------------- */
  933. if (!parse_args(args, "is", &log_level, &msg))
  934. goto fail;
  935. if (!msg || !*msg)
  936. goto fail;
  937. dstr_cat(&cur_py_log_chunk, msg);
  938. if (add_endl)
  939. dstr_cat(&cur_py_log_chunk, "\n");
  940. const char *start = cur_py_log_chunk.array;
  941. char *endl = strchr(start, '\n');
  942. while (endl) {
  943. *endl = 0;
  944. if (cur_python_script)
  945. script_log(&cur_python_script->base, log_level, "%s",
  946. start);
  947. else
  948. script_log(NULL, log_level, "%s", start);
  949. *endl = '\n';
  950. start = endl + 1;
  951. endl = strchr(start, '\n');
  952. }
  953. if (start) {
  954. size_t len = strlen(start);
  955. if (len)
  956. memmove(cur_py_log_chunk.array, start, len);
  957. dstr_resize(&cur_py_log_chunk, len);
  958. }
  959. /* ------------------- */
  960. fail:
  961. calling_self = false;
  962. return python_none();
  963. }
  964. static PyObject *py_script_log_no_endl(PyObject *self, PyObject *args)
  965. {
  966. return py_script_log_internal(self, args, false);
  967. }
  968. static PyObject *py_script_log(PyObject *self, PyObject *args)
  969. {
  970. return py_script_log_internal(self, args, true);
  971. }
  972. /* -------------------------------------------- */
  973. static void add_hook_functions(PyObject *module)
  974. {
  975. static PyMethodDef funcs[] = {
  976. #define DEF_FUNC(n, c) {n, c, METH_VARARGS, NULL}
  977. DEF_FUNC("script_log_no_endl", py_script_log_no_endl),
  978. DEF_FUNC("script_log", py_script_log),
  979. DEF_FUNC("timer_remove", timer_remove),
  980. DEF_FUNC("timer_add", timer_add),
  981. DEF_FUNC("calldata_source", calldata_source),
  982. DEF_FUNC("calldata_sceneitem", calldata_sceneitem),
  983. DEF_FUNC("source_list_release", source_list_release),
  984. DEF_FUNC("sceneitem_list_release", sceneitem_list_release),
  985. DEF_FUNC("obs_enum_sources", enum_sources),
  986. DEF_FUNC("obs_scene_enum_items", scene_enum_items),
  987. DEF_FUNC("obs_sceneitem_group_enum_items",
  988. sceneitem_group_enum_items),
  989. DEF_FUNC("obs_remove_tick_callback",
  990. obs_python_remove_tick_callback),
  991. DEF_FUNC("obs_add_tick_callback", obs_python_add_tick_callback),
  992. DEF_FUNC("signal_handler_disconnect",
  993. obs_python_signal_handler_disconnect),
  994. DEF_FUNC("signal_handler_connect",
  995. obs_python_signal_handler_connect),
  996. DEF_FUNC("signal_handler_disconnect_global",
  997. obs_python_signal_handler_disconnect_global),
  998. DEF_FUNC("signal_handler_connect_global",
  999. obs_python_signal_handler_connect_global),
  1000. DEF_FUNC("obs_hotkey_unregister", hotkey_unregister),
  1001. DEF_FUNC("obs_hotkey_register_frontend",
  1002. hotkey_register_frontend),
  1003. DEF_FUNC("obs_properties_add_button", properties_add_button),
  1004. DEF_FUNC("obs_property_set_modified_callback",
  1005. property_set_modified_callback),
  1006. DEF_FUNC("remove_current_callback", remove_current_callback),
  1007. #undef DEF_FUNC
  1008. {0}};
  1009. add_functions_to_py_module(module, funcs);
  1010. }
  1011. /* -------------------------------------------- */
  1012. void obs_python_script_update(obs_script_t *script, obs_data_t *settings);
  1013. bool obs_python_script_load(obs_script_t *s)
  1014. {
  1015. struct obs_python_script *data = (struct obs_python_script *)s;
  1016. if (python_loaded && !data->base.loaded) {
  1017. lock_python();
  1018. if (!data->module)
  1019. add_to_python_path(data->dir.array);
  1020. data->base.loaded = load_python_script(data);
  1021. unlock_python();
  1022. if (data->base.loaded) {
  1023. blog(LOG_INFO,
  1024. "[obs-scripting]: Loaded python script: %s",
  1025. data->base.file.array);
  1026. obs_python_script_update(s, NULL);
  1027. }
  1028. }
  1029. return data->base.loaded;
  1030. }
  1031. obs_script_t *obs_python_script_create(const char *path, obs_data_t *settings)
  1032. {
  1033. struct obs_python_script *data = bzalloc(sizeof(*data));
  1034. data->base.type = OBS_SCRIPT_LANG_PYTHON;
  1035. dstr_copy(&data->base.path, path);
  1036. dstr_replace(&data->base.path, "\\", "/");
  1037. path = data->base.path.array;
  1038. const char *slash = path && *path ? strrchr(path, '/') : NULL;
  1039. if (slash) {
  1040. slash++;
  1041. dstr_copy(&data->base.file, slash);
  1042. dstr_left(&data->dir, &data->base.path, slash - path);
  1043. } else {
  1044. dstr_copy(&data->base.file, path);
  1045. }
  1046. path = data->base.file.array;
  1047. dstr_copy_dstr(&data->name, &data->base.file);
  1048. const char *ext = strstr(path, ".py");
  1049. if (ext)
  1050. dstr_resize(&data->name, ext - path);
  1051. data->base.settings = obs_data_create();
  1052. if (settings)
  1053. obs_data_apply(data->base.settings, settings);
  1054. if (!python_loaded)
  1055. return (obs_script_t *)data;
  1056. lock_python();
  1057. add_to_python_path(data->dir.array);
  1058. data->base.loaded = load_python_script(data);
  1059. if (data->base.loaded) {
  1060. blog(LOG_INFO, "[obs-scripting]: Loaded python script: %s",
  1061. data->base.file.array);
  1062. cur_python_script = data;
  1063. obs_python_script_update(&data->base, NULL);
  1064. cur_python_script = NULL;
  1065. }
  1066. unlock_python();
  1067. return (obs_script_t *)data;
  1068. }
  1069. void obs_python_script_unload(obs_script_t *s)
  1070. {
  1071. struct obs_python_script *data = (struct obs_python_script *)s;
  1072. if (!s->loaded || !python_loaded)
  1073. return;
  1074. /* ---------------------------- */
  1075. /* mark callbacks as removed */
  1076. lock_python();
  1077. /* XXX: scripts can potentially make callbacks when this happens, so
  1078. * this probably still isn't ideal as we can't predict how the
  1079. * processor or operating system is going to schedule things. a more
  1080. * ideal method would be to reference count the script objects and
  1081. * atomically share ownership with callbacks when they're called. */
  1082. struct script_callback *cb = data->first_callback;
  1083. while (cb) {
  1084. os_atomic_set_bool(&cb->removed, true);
  1085. cb = cb->next;
  1086. }
  1087. unlock_python();
  1088. /* ---------------------------- */
  1089. /* unhook tick function */
  1090. if (data->p_prev_next_tick) {
  1091. pthread_mutex_lock(&tick_mutex);
  1092. struct obs_python_script *next = data->next_tick;
  1093. if (next)
  1094. next->p_prev_next_tick = data->p_prev_next_tick;
  1095. *data->p_prev_next_tick = next;
  1096. pthread_mutex_unlock(&tick_mutex);
  1097. data->p_prev_next_tick = NULL;
  1098. data->next_tick = NULL;
  1099. }
  1100. relock_python();
  1101. Py_XDECREF(data->tick);
  1102. Py_XDECREF(data->save);
  1103. Py_XDECREF(data->update);
  1104. Py_XDECREF(data->get_properties);
  1105. data->tick = NULL;
  1106. data->save = NULL;
  1107. data->update = NULL;
  1108. data->get_properties = NULL;
  1109. /* ---------------------------- */
  1110. /* remove all callbacks */
  1111. cb = data->first_callback;
  1112. while (cb) {
  1113. struct script_callback *next = cb->next;
  1114. remove_script_callback(cb);
  1115. cb = next;
  1116. }
  1117. /* ---------------------------- */
  1118. /* unload */
  1119. unload_python_script(data);
  1120. unlock_python();
  1121. s->loaded = false;
  1122. blog(LOG_INFO, "[obs-scripting]: Unloaded python script: %s",
  1123. data->base.file.array);
  1124. }
  1125. void obs_python_script_destroy(obs_script_t *s)
  1126. {
  1127. struct obs_python_script *data = (struct obs_python_script *)s;
  1128. if (data) {
  1129. if (python_loaded) {
  1130. lock_python();
  1131. Py_XDECREF(data->module);
  1132. unlock_python();
  1133. }
  1134. dstr_free(&data->base.path);
  1135. dstr_free(&data->base.file);
  1136. dstr_free(&data->base.desc);
  1137. obs_data_release(data->base.settings);
  1138. dstr_free(&data->dir);
  1139. dstr_free(&data->name);
  1140. bfree(data);
  1141. }
  1142. }
  1143. void obs_python_script_update(obs_script_t *s, obs_data_t *settings)
  1144. {
  1145. struct obs_python_script *data = (struct obs_python_script *)s;
  1146. if (!s->loaded || !python_loaded)
  1147. return;
  1148. if (!data->update)
  1149. return;
  1150. if (settings)
  1151. obs_data_apply(s->settings, settings);
  1152. lock_python();
  1153. cur_python_script = data;
  1154. PyObject *py_settings;
  1155. if (libobs_to_py(obs_data_t, s->settings, false, &py_settings)) {
  1156. PyObject *args = Py_BuildValue("(O)", py_settings);
  1157. PyObject *ret = PyObject_CallObject(data->update, args);
  1158. py_error();
  1159. Py_XDECREF(ret);
  1160. Py_XDECREF(args);
  1161. Py_XDECREF(py_settings);
  1162. }
  1163. cur_python_script = NULL;
  1164. unlock_python();
  1165. }
  1166. obs_properties_t *obs_python_script_get_properties(obs_script_t *s)
  1167. {
  1168. struct obs_python_script *data = (struct obs_python_script *)s;
  1169. obs_properties_t *props = NULL;
  1170. if (!s->loaded || !python_loaded)
  1171. return NULL;
  1172. if (!data->get_properties)
  1173. return NULL;
  1174. lock_python();
  1175. cur_python_script = data;
  1176. PyObject *ret = PyObject_CallObject(data->get_properties, NULL);
  1177. if (!py_error())
  1178. py_to_libobs(obs_properties_t, ret, &props);
  1179. Py_XDECREF(ret);
  1180. cur_python_script = NULL;
  1181. unlock_python();
  1182. return props;
  1183. }
  1184. void obs_python_script_save(obs_script_t *s)
  1185. {
  1186. struct obs_python_script *data = (struct obs_python_script *)s;
  1187. if (!s->loaded || !python_loaded)
  1188. return;
  1189. if (!data->save)
  1190. return;
  1191. lock_python();
  1192. cur_python_script = data;
  1193. PyObject *py_settings;
  1194. if (libobs_to_py(obs_data_t, s->settings, false, &py_settings)) {
  1195. PyObject *args = Py_BuildValue("(O)", py_settings);
  1196. PyObject *ret = PyObject_CallObject(data->save, args);
  1197. py_error();
  1198. Py_XDECREF(ret);
  1199. Py_XDECREF(args);
  1200. Py_XDECREF(py_settings);
  1201. }
  1202. cur_python_script = NULL;
  1203. unlock_python();
  1204. }
  1205. /* -------------------------------------------- */
  1206. static void python_tick(void *param, float seconds)
  1207. {
  1208. struct obs_python_script *data;
  1209. /* When loading a new Python script, the GIL might be released while
  1210. * importing the module, allowing the tick to run and change and reset
  1211. * the cur_python_script state variable. Use the busy_script variable
  1212. * to save and restore the value if not null.
  1213. */
  1214. struct obs_python_script *busy_script = NULL;
  1215. bool valid;
  1216. uint64_t ts = obs_get_video_frame_time();
  1217. pthread_mutex_lock(&tick_mutex);
  1218. valid = !!first_tick_script;
  1219. pthread_mutex_unlock(&tick_mutex);
  1220. /* --------------------------------- */
  1221. /* process script_tick calls */
  1222. if (valid) {
  1223. lock_python();
  1224. PyObject *args = Py_BuildValue("(f)", seconds);
  1225. pthread_mutex_lock(&tick_mutex);
  1226. data = first_tick_script;
  1227. if (cur_python_script)
  1228. busy_script = cur_python_script;
  1229. while (data) {
  1230. cur_python_script = data;
  1231. PyObject *py_ret =
  1232. PyObject_CallObject(data->tick, args);
  1233. Py_XDECREF(py_ret);
  1234. py_error();
  1235. data = data->next_tick;
  1236. }
  1237. cur_python_script = NULL;
  1238. if (busy_script) {
  1239. cur_python_script = busy_script;
  1240. busy_script = NULL;
  1241. }
  1242. pthread_mutex_unlock(&tick_mutex);
  1243. Py_XDECREF(args);
  1244. unlock_python();
  1245. }
  1246. /* --------------------------------- */
  1247. /* process timers */
  1248. pthread_mutex_lock(&timer_mutex);
  1249. struct python_obs_timer *timer = first_timer;
  1250. while (timer) {
  1251. struct python_obs_timer *next = timer->next;
  1252. struct python_obs_callback *cb = python_obs_timer_cb(timer);
  1253. if (script_callback_removed(&cb->base)) {
  1254. python_obs_timer_remove(timer);
  1255. } else {
  1256. uint64_t elapsed = ts - timer->last_ts;
  1257. if (elapsed >= timer->interval) {
  1258. lock_python();
  1259. timer_call(&cb->base);
  1260. unlock_python();
  1261. timer->last_ts += timer->interval;
  1262. }
  1263. }
  1264. timer = next;
  1265. }
  1266. pthread_mutex_unlock(&timer_mutex);
  1267. UNUSED_PARAMETER(param);
  1268. }
  1269. /* -------------------------------------------- */
  1270. void obs_python_unload(void);
  1271. bool obs_scripting_python_runtime_linked(void)
  1272. {
  1273. return (bool)RUNTIME_LINK;
  1274. }
  1275. void obs_scripting_python_version(char *version, size_t version_length)
  1276. {
  1277. #if RUNTIME_LINK
  1278. snprintf(version, version_length, "%d.%d", python_version.major,
  1279. python_version.minor);
  1280. #else
  1281. snprintf(version, version_length, "%d.%d", PY_MAJOR_VERSION,
  1282. PY_MINOR_VERSION);
  1283. #endif
  1284. }
  1285. bool obs_scripting_python_loaded(void)
  1286. {
  1287. return python_loaded;
  1288. }
  1289. void obs_python_load(void)
  1290. {
  1291. da_init(python_paths);
  1292. pthread_mutex_init(&tick_mutex, NULL);
  1293. pthread_mutex_init_recursive(&timer_mutex);
  1294. mutexes_loaded = true;
  1295. }
  1296. extern void add_python_frontend_funcs(PyObject *module);
  1297. static bool python_loaded_at_all = false;
  1298. bool obs_scripting_load_python(const char *python_path)
  1299. {
  1300. if (python_loaded)
  1301. return true;
  1302. /* Use external python on windows and mac */
  1303. #if RUNTIME_LINK
  1304. if (!import_python(python_path, &python_version))
  1305. return false;
  1306. if (python_path && *python_path) {
  1307. #ifdef __APPLE__
  1308. char temp[PATH_MAX];
  1309. snprintf(temp, sizeof(temp),
  1310. "%s/Python.framework/Versions/Current", python_path);
  1311. os_utf8_to_wcs(temp, 0, home_path, PATH_MAX);
  1312. Py_SetPythonHome(home_path);
  1313. #else
  1314. os_utf8_to_wcs(python_path, 0, home_path, 1024);
  1315. Py_SetPythonHome(home_path);
  1316. #endif
  1317. }
  1318. #else
  1319. UNUSED_PARAMETER(python_path);
  1320. #endif
  1321. Py_Initialize();
  1322. if (!Py_IsInitialized())
  1323. return false;
  1324. #if RUNTIME_LINK
  1325. if (python_version.major == 3 && python_version.minor < 7) {
  1326. PyEval_InitThreads();
  1327. if (!PyEval_ThreadsInitialized())
  1328. return false;
  1329. }
  1330. #elif PY_VERSION_HEX < 0x03070000
  1331. PyEval_InitThreads();
  1332. if (!PyEval_ThreadsInitialized())
  1333. return false;
  1334. #endif
  1335. /* ---------------------------------------------- */
  1336. /* Must set arguments for guis to work */
  1337. wchar_t *argv[] = {L"", NULL};
  1338. int argc = sizeof(argv) / sizeof(wchar_t *) - 1;
  1339. PRAGMA_WARN_PUSH
  1340. PRAGMA_WARN_DEPRECATION
  1341. PySys_SetArgv(argc, argv);
  1342. PRAGMA_WARN_POP
  1343. #ifdef __APPLE__
  1344. PyRun_SimpleString("import sys");
  1345. PyRun_SimpleString("sys.dont_write_bytecode = True");
  1346. #endif
  1347. #ifdef DEBUG_PYTHON_STARTUP
  1348. /* ---------------------------------------------- */
  1349. /* Debug logging to file if startup is failing */
  1350. PyRun_SimpleString("import os");
  1351. PyRun_SimpleString("import sys");
  1352. PyRun_SimpleString("os.environ['PYTHONUNBUFFERED'] = '1'");
  1353. PyRun_SimpleString("sys.stdout = open('./stdOut.txt','w',1)");
  1354. PyRun_SimpleString("sys.stderr = open('./stdErr.txt','w',1)");
  1355. PyRun_SimpleString("print(sys.version)");
  1356. #endif
  1357. /* ---------------------------------------------- */
  1358. /* Load main interface module */
  1359. #ifdef __APPLE__
  1360. struct dstr plugin_path;
  1361. struct dstr resource_path;
  1362. dstr_init_move_array(&plugin_path, os_get_executable_path_ptr(""));
  1363. dstr_init_copy(&resource_path, plugin_path.array);
  1364. dstr_cat(&plugin_path, "../PlugIns");
  1365. dstr_cat(&resource_path, "../Resources");
  1366. char *absolute_plugin_path = os_get_abs_path_ptr(plugin_path.array);
  1367. char *absolute_resource_path = os_get_abs_path_ptr(resource_path.array);
  1368. if (absolute_plugin_path != NULL) {
  1369. add_to_python_path(absolute_plugin_path);
  1370. bfree(absolute_plugin_path);
  1371. }
  1372. dstr_free(&plugin_path);
  1373. if (absolute_resource_path != NULL) {
  1374. add_to_python_path(absolute_resource_path);
  1375. bfree(absolute_resource_path);
  1376. }
  1377. dstr_free(&resource_path);
  1378. #else
  1379. char *absolute_script_path = os_get_abs_path_ptr(SCRIPT_DIR);
  1380. add_to_python_path(absolute_script_path);
  1381. bfree(absolute_script_path);
  1382. #endif
  1383. py_obspython = PyImport_ImportModule("obspython");
  1384. bool success = !py_error();
  1385. if (!success) {
  1386. warn("Error importing obspython.py', unloading obs-python");
  1387. goto out;
  1388. }
  1389. python_loaded = PyRun_SimpleString(startup_script) == 0;
  1390. py_error();
  1391. add_hook_functions(py_obspython);
  1392. py_error();
  1393. add_python_frontend_funcs(py_obspython);
  1394. py_error();
  1395. out:
  1396. /* ---------------------------------------------- */
  1397. /* Free data */
  1398. PyEval_ReleaseThread(PyGILState_GetThisThreadState());
  1399. if (!success) {
  1400. warn("Failed to load python plugin");
  1401. obs_python_unload();
  1402. }
  1403. python_loaded_at_all = success;
  1404. if (python_loaded)
  1405. obs_add_tick_callback(python_tick, NULL);
  1406. return python_loaded;
  1407. }
  1408. void obs_python_unload(void)
  1409. {
  1410. if (mutexes_loaded) {
  1411. pthread_mutex_destroy(&tick_mutex);
  1412. pthread_mutex_destroy(&timer_mutex);
  1413. }
  1414. if (!python_loaded_at_all)
  1415. return;
  1416. if (python_loaded && Py_IsInitialized()) {
  1417. PyGILState_Ensure();
  1418. Py_XDECREF(py_obspython);
  1419. Py_Finalize();
  1420. }
  1421. /* ---------------------- */
  1422. obs_remove_tick_callback(python_tick, NULL);
  1423. for (size_t i = 0; i < python_paths.num; i++)
  1424. bfree(python_paths.array[i]);
  1425. da_free(python_paths);
  1426. dstr_free(&cur_py_log_chunk);
  1427. python_loaded_at_all = false;
  1428. }