1
0

obs-scripting-python.c 43 KB

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