obs-scripting-python.c 40 KB

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