obs-scripting-python.c 42 KB

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