obs-scripting-python.c 40 KB

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