1
0

obs-scripting-python.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  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. script_log(&cur_python_script->base, log_level, "%s", start);
  944. *endl = '\n';
  945. start = endl + 1;
  946. endl = strchr(start, '\n');
  947. }
  948. if (start) {
  949. size_t len = strlen(start);
  950. if (len) memmove(cur_py_log_chunk.array, start, len);
  951. dstr_resize(&cur_py_log_chunk, len);
  952. }
  953. /* ------------------- */
  954. fail:
  955. calling_self = false;
  956. return python_none();
  957. }
  958. static PyObject *py_script_log_no_endl(PyObject *self, PyObject *args)
  959. {
  960. return py_script_log_internal(self, args, false);
  961. }
  962. static PyObject *py_script_log(PyObject *self, PyObject *args)
  963. {
  964. return py_script_log_internal(self, args, true);
  965. }
  966. /* -------------------------------------------- */
  967. static void add_hook_functions(PyObject *module)
  968. {
  969. static PyMethodDef funcs[] = {
  970. #define DEF_FUNC(n, c) {n, c, METH_VARARGS, NULL}
  971. DEF_FUNC("script_log_no_endl", py_script_log_no_endl),
  972. DEF_FUNC("script_log", py_script_log),
  973. DEF_FUNC("timer_remove", timer_remove),
  974. DEF_FUNC("timer_add", timer_add),
  975. DEF_FUNC("calldata_source", calldata_source),
  976. DEF_FUNC("calldata_sceneitem", calldata_sceneitem),
  977. DEF_FUNC("source_list_release", source_list_release),
  978. DEF_FUNC("sceneitem_list_release", sceneitem_list_release),
  979. DEF_FUNC("obs_enum_sources", enum_sources),
  980. DEF_FUNC("obs_scene_enum_items", scene_enum_items),
  981. DEF_FUNC("obs_remove_tick_callback",
  982. obs_python_remove_tick_callback),
  983. DEF_FUNC("obs_add_tick_callback",
  984. obs_python_add_tick_callback),
  985. DEF_FUNC("signal_handler_disconnect",
  986. obs_python_signal_handler_disconnect),
  987. DEF_FUNC("signal_handler_connect",
  988. obs_python_signal_handler_connect),
  989. DEF_FUNC("signal_handler_disconnect_global",
  990. obs_python_signal_handler_disconnect_global),
  991. DEF_FUNC("signal_handler_connect_global",
  992. obs_python_signal_handler_connect_global),
  993. DEF_FUNC("obs_hotkey_unregister",
  994. hotkey_unregister),
  995. DEF_FUNC("obs_hotkey_register_frontend",
  996. hotkey_register_frontend),
  997. DEF_FUNC("obs_properties_add_button",
  998. properties_add_button),
  999. DEF_FUNC("obs_property_set_modified_callback",
  1000. property_set_modified_callback),
  1001. DEF_FUNC("remove_current_callback",
  1002. remove_current_callback),
  1003. #undef DEF_FUNC
  1004. {0}
  1005. };
  1006. add_functions_to_py_module(module, funcs);
  1007. }
  1008. /* -------------------------------------------- */
  1009. void obs_python_script_update(obs_script_t *script, obs_data_t *settings);
  1010. bool obs_python_script_load(obs_script_t *s)
  1011. {
  1012. struct obs_python_script *data = (struct obs_python_script *)s;
  1013. if (python_loaded && !data->base.loaded) {
  1014. lock_python();
  1015. if (!data->module)
  1016. add_to_python_path(data->dir.array);
  1017. data->base.loaded = load_python_script(data);
  1018. unlock_python();
  1019. if (data->base.loaded)
  1020. obs_python_script_update(s, NULL);
  1021. }
  1022. return data->base.loaded;
  1023. }
  1024. obs_script_t *obs_python_script_create(const char *path, obs_data_t *settings)
  1025. {
  1026. struct obs_python_script *data = bzalloc(sizeof(*data));
  1027. data->base.type = OBS_SCRIPT_LANG_PYTHON;
  1028. dstr_copy(&data->base.path, path);
  1029. dstr_replace(&data->base.path, "\\", "/");
  1030. path = data->base.path.array;
  1031. const char *slash = path && *path ? strrchr(path, '/') : NULL;
  1032. if (slash) {
  1033. slash++;
  1034. dstr_copy(&data->base.file, slash);
  1035. dstr_left(&data->dir, &data->base.path, slash - path);
  1036. } else {
  1037. dstr_copy(&data->base.file, path);
  1038. }
  1039. path = data->base.file.array;
  1040. dstr_copy_dstr(&data->name, &data->base.file);
  1041. const char *ext = strstr(path, ".py");
  1042. if (ext)
  1043. dstr_resize(&data->name, ext - path);
  1044. data->base.settings = obs_data_create();
  1045. if (settings)
  1046. obs_data_apply(data->base.settings, settings);
  1047. if (!python_loaded)
  1048. return (obs_script_t *)data;
  1049. lock_python();
  1050. add_to_python_path(data->dir.array);
  1051. data->base.loaded = load_python_script(data);
  1052. if (data->base.loaded) {
  1053. cur_python_script = data;
  1054. obs_python_script_update(&data->base, NULL);
  1055. cur_python_script = NULL;
  1056. }
  1057. unlock_python();
  1058. return (obs_script_t *)data;
  1059. }
  1060. void obs_python_script_unload(obs_script_t *s)
  1061. {
  1062. struct obs_python_script *data = (struct obs_python_script *)s;
  1063. if (!s->loaded || !python_loaded)
  1064. return;
  1065. /* ---------------------------- */
  1066. /* unhook tick function */
  1067. if (data->p_prev_next_tick) {
  1068. pthread_mutex_lock(&tick_mutex);
  1069. struct obs_python_script *next = data->next_tick;
  1070. if (next) next->p_prev_next_tick = data->p_prev_next_tick;
  1071. *data->p_prev_next_tick = next;
  1072. pthread_mutex_unlock(&tick_mutex);
  1073. data->p_prev_next_tick = NULL;
  1074. data->next_tick = NULL;
  1075. }
  1076. lock_python();
  1077. Py_XDECREF(data->tick);
  1078. Py_XDECREF(data->save);
  1079. Py_XDECREF(data->update);
  1080. Py_XDECREF(data->get_properties);
  1081. data->tick = NULL;
  1082. data->save = NULL;
  1083. data->update = NULL;
  1084. data->get_properties = NULL;
  1085. /* ---------------------------- */
  1086. /* remove all callbacks */
  1087. struct script_callback *cb = data->first_callback;
  1088. while (cb) {
  1089. struct script_callback *next = cb->next;
  1090. remove_script_callback(cb);
  1091. cb = next;
  1092. }
  1093. /* ---------------------------- */
  1094. /* unload */
  1095. unload_python_script(data);
  1096. unlock_python();
  1097. s->loaded = false;
  1098. }
  1099. void obs_python_script_destroy(obs_script_t *s)
  1100. {
  1101. struct obs_python_script *data = (struct obs_python_script *)s;
  1102. if (data) {
  1103. if (python_loaded) {
  1104. lock_python();
  1105. Py_XDECREF(data->module);
  1106. unlock_python();
  1107. }
  1108. dstr_free(&data->base.path);
  1109. dstr_free(&data->base.file);
  1110. dstr_free(&data->base.desc);
  1111. obs_data_release(data->base.settings);
  1112. dstr_free(&data->dir);
  1113. dstr_free(&data->name);
  1114. bfree(data);
  1115. }
  1116. }
  1117. void obs_python_script_update(obs_script_t *s, obs_data_t *settings)
  1118. {
  1119. struct obs_python_script *data = (struct obs_python_script *)s;
  1120. if (!s->loaded || !python_loaded)
  1121. return;
  1122. if (!data->update)
  1123. return;
  1124. if (settings)
  1125. obs_data_apply(s->settings, settings);
  1126. lock_python();
  1127. cur_python_script = data;
  1128. PyObject *py_settings;
  1129. if (libobs_to_py(obs_data_t, s->settings, false, &py_settings)) {
  1130. PyObject *args = Py_BuildValue("(O)", py_settings);
  1131. PyObject *ret = PyObject_CallObject(data->update, args);
  1132. py_error();
  1133. Py_XDECREF(ret);
  1134. Py_XDECREF(args);
  1135. Py_XDECREF(py_settings);
  1136. }
  1137. cur_python_script = NULL;
  1138. unlock_python();
  1139. }
  1140. obs_properties_t *obs_python_script_get_properties(obs_script_t *s)
  1141. {
  1142. struct obs_python_script *data = (struct obs_python_script *)s;
  1143. obs_properties_t *props = NULL;
  1144. if (!s->loaded || !python_loaded)
  1145. return NULL;
  1146. if (!data->get_properties)
  1147. return NULL;
  1148. lock_python();
  1149. cur_python_script = data;
  1150. PyObject *ret = PyObject_CallObject(data->get_properties, NULL);
  1151. if (!py_error())
  1152. py_to_libobs(obs_properties_t, ret, &props);
  1153. Py_XDECREF(ret);
  1154. cur_python_script = NULL;
  1155. unlock_python();
  1156. return props;
  1157. }
  1158. void obs_python_script_save(obs_script_t *s)
  1159. {
  1160. struct obs_python_script *data = (struct obs_python_script *)s;
  1161. if (!s->loaded || !python_loaded)
  1162. return;
  1163. if (!data->save)
  1164. return;
  1165. lock_python();
  1166. cur_python_script = data;
  1167. PyObject *py_settings;
  1168. if (libobs_to_py(obs_data_t, s->settings, false, &py_settings)) {
  1169. PyObject *args = Py_BuildValue("(O)", py_settings);
  1170. PyObject *ret = PyObject_CallObject(data->save, args);
  1171. py_error();
  1172. Py_XDECREF(ret);
  1173. Py_XDECREF(args);
  1174. Py_XDECREF(py_settings);
  1175. }
  1176. cur_python_script = NULL;
  1177. unlock_python();
  1178. }
  1179. /* -------------------------------------------- */
  1180. static void python_tick(void *param, float seconds)
  1181. {
  1182. struct obs_python_script *data;
  1183. bool valid;
  1184. uint64_t ts = obs_get_video_frame_time();
  1185. pthread_mutex_lock(&tick_mutex);
  1186. valid = !!first_tick_script;
  1187. pthread_mutex_unlock(&tick_mutex);
  1188. /* --------------------------------- */
  1189. /* process script_tick calls */
  1190. if (valid) {
  1191. lock_python();
  1192. PyObject *args = Py_BuildValue("(f)", seconds);
  1193. pthread_mutex_lock(&tick_mutex);
  1194. data = first_tick_script;
  1195. while (data) {
  1196. cur_python_script = data;
  1197. PyObject *py_ret = PyObject_CallObject(data->tick, args);
  1198. Py_XDECREF(py_ret);
  1199. py_error();
  1200. data = data->next_tick;
  1201. }
  1202. cur_python_script = NULL;
  1203. pthread_mutex_unlock(&tick_mutex);
  1204. Py_XDECREF(args);
  1205. unlock_python();
  1206. }
  1207. /* --------------------------------- */
  1208. /* process timers */
  1209. pthread_mutex_lock(&timer_mutex);
  1210. struct python_obs_timer *timer = first_timer;
  1211. while (timer) {
  1212. struct python_obs_timer *next = timer->next;
  1213. struct python_obs_callback *cb = python_obs_timer_cb(timer);
  1214. if (cb->base.removed) {
  1215. python_obs_timer_remove(timer);
  1216. } else {
  1217. uint64_t elapsed = ts - timer->last_ts;
  1218. if (elapsed >= timer->interval) {
  1219. lock_python();
  1220. timer_call(&cb->base);
  1221. unlock_python();
  1222. timer->last_ts += timer->interval;
  1223. }
  1224. }
  1225. timer = next;
  1226. }
  1227. pthread_mutex_unlock(&timer_mutex);
  1228. UNUSED_PARAMETER(param);
  1229. }
  1230. /* -------------------------------------------- */
  1231. void obs_python_unload(void);
  1232. bool obs_scripting_python_runtime_linked(void)
  1233. {
  1234. return (bool)RUNTIME_LINK;
  1235. }
  1236. bool obs_scripting_python_loaded(void)
  1237. {
  1238. return python_loaded;
  1239. }
  1240. void obs_python_load(void)
  1241. {
  1242. da_init(python_paths);
  1243. pthread_mutexattr_t attr;
  1244. pthread_mutexattr_init(&attr);
  1245. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  1246. pthread_mutex_init(&tick_mutex, NULL);
  1247. pthread_mutex_init(&timer_mutex, &attr);
  1248. }
  1249. extern void add_python_frontend_funcs(PyObject *module);
  1250. bool obs_scripting_load_python(const char *python_path)
  1251. {
  1252. if (python_loaded)
  1253. return true;
  1254. /* Use external python on windows and mac */
  1255. #if RUNTIME_LINK
  1256. # if 0
  1257. struct dstr old_path = {0};
  1258. struct dstr new_path = {0};
  1259. # endif
  1260. if (!import_python(python_path))
  1261. return false;
  1262. if (python_path && *python_path) {
  1263. os_utf8_to_wcs(python_path, 0, home_path, 1024);
  1264. Py_SetPythonHome(home_path);
  1265. # if 0
  1266. dstr_copy(&old_path, getenv("PATH"));
  1267. _putenv("PYTHONPATH=");
  1268. _putenv("PATH=");
  1269. # endif
  1270. }
  1271. #else
  1272. UNUSED_PARAMETER(python_path);
  1273. #endif
  1274. Py_Initialize();
  1275. if (!Py_IsInitialized())
  1276. return false;
  1277. #if 0
  1278. # ifdef _DEBUG
  1279. if (pythondir && *pythondir) {
  1280. dstr_printf(&new_path, "PATH=%s", old_path.array);
  1281. _putenv(new_path.array);
  1282. }
  1283. # endif
  1284. bfree(pythondir);
  1285. dstr_free(&new_path);
  1286. dstr_free(&old_path);
  1287. #endif
  1288. PyEval_InitThreads();
  1289. if (!PyEval_ThreadsInitialized())
  1290. return false;
  1291. /* ---------------------------------------------- */
  1292. /* Must set arguments for guis to work */
  1293. wchar_t *argv[] = {L"", NULL};
  1294. int argc = sizeof(argv) / sizeof(wchar_t*) - 1;
  1295. PySys_SetArgv(argc, argv);
  1296. #ifdef DEBUG_PYTHON_STARTUP
  1297. /* ---------------------------------------------- */
  1298. /* Debug logging to file if startup is failing */
  1299. PyRun_SimpleString("import os");
  1300. PyRun_SimpleString("import sys");
  1301. PyRun_SimpleString("os.environ['PYTHONUNBUFFERED'] = '1'");
  1302. PyRun_SimpleString("sys.stdout = open('./stdOut.txt','w',1)");
  1303. PyRun_SimpleString("sys.stderr = open('./stdErr.txt','w',1)");
  1304. PyRun_SimpleString("print(sys.version)");
  1305. #endif
  1306. /* ---------------------------------------------- */
  1307. /* Load main interface module */
  1308. add_to_python_path(SCRIPT_DIR);
  1309. py_obspython = PyImport_ImportModule("obspython");
  1310. bool success = !py_error();
  1311. if (!success) {
  1312. warn("Error importing obspython.py', unloading obs-python");
  1313. goto out;
  1314. }
  1315. python_loaded = PyRun_SimpleString(startup_script) == 0;
  1316. py_error();
  1317. add_hook_functions(py_obspython);
  1318. py_error();
  1319. add_python_frontend_funcs(py_obspython);
  1320. py_error();
  1321. out:
  1322. /* ---------------------------------------------- */
  1323. /* Free data */
  1324. PyEval_ReleaseThread(PyGILState_GetThisThreadState());
  1325. if (!success) {
  1326. warn("Failed to load python plugin");
  1327. obs_python_unload();
  1328. }
  1329. if (python_loaded)
  1330. obs_add_tick_callback(python_tick, NULL);
  1331. return python_loaded;
  1332. }
  1333. void obs_python_unload(void)
  1334. {
  1335. if (python_loaded && Py_IsInitialized()) {
  1336. PyGILState_Ensure();
  1337. Py_XDECREF(py_obspython);
  1338. Py_Finalize();
  1339. }
  1340. /* ---------------------- */
  1341. obs_remove_tick_callback(python_tick, NULL);
  1342. for (size_t i = 0; i < python_paths.num; i++)
  1343. bfree(python_paths.array[i]);
  1344. da_free(python_paths);
  1345. pthread_mutex_destroy(&tick_mutex);
  1346. pthread_mutex_destroy(&timer_mutex);
  1347. dstr_free(&cur_py_log_chunk);
  1348. }