syphon.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. #import <Cocoa/Cocoa.h>
  2. #import <ScriptingBridge/ScriptingBridge.h>
  3. #import "syphon-framework/Syphon.h"
  4. #include <obs-module.h>
  5. #define LOG(level, message, ...) \
  6. blog(level, "%s: " message, obs_source_get_name(s->source), \
  7. ##__VA_ARGS__)
  8. struct syphon {
  9. SYPHON_CLIENT_UNIQUE_CLASS_NAME *client;
  10. IOSurfaceRef ref;
  11. gs_samplerstate_t *sampler;
  12. gs_effect_t *effect;
  13. gs_vertbuffer_t *vertbuffer;
  14. gs_texture_t *tex;
  15. uint32_t width, height;
  16. bool crop;
  17. CGRect crop_rect;
  18. bool allow_transparency;
  19. obs_source_t *source;
  20. bool active;
  21. bool uuid_changed;
  22. id new_server_listener;
  23. id retire_listener;
  24. NSString *app_name;
  25. NSString *name;
  26. NSString *uuid;
  27. obs_data_t *inject_info;
  28. NSString *inject_app;
  29. NSString *inject_uuid;
  30. bool inject_active;
  31. id launch_listener;
  32. bool inject_server_found;
  33. float inject_wait_time;
  34. };
  35. typedef struct syphon *syphon_t;
  36. static inline void objc_release(NSObject **obj)
  37. {
  38. [*obj release];
  39. *obj = nil;
  40. }
  41. static inline void update_properties(syphon_t s)
  42. {
  43. obs_source_update_properties(s->source);
  44. }
  45. static inline void find_and_inject_target(syphon_t s, NSArray *arr, bool retry);
  46. @interface OBSSyphonKVObserver : NSObject
  47. - (void)observeValueForKeyPath:(NSString *)keyPath
  48. ofObject:(id)object
  49. change:(NSDictionary *)change
  50. context:(void *)context;
  51. @end
  52. static inline void handle_application_launch(syphon_t s, NSArray *new)
  53. {
  54. if (!s->inject_active)
  55. return;
  56. if (!new)
  57. return;
  58. find_and_inject_target(s, new, false);
  59. }
  60. @implementation OBSSyphonKVObserver
  61. - (void)observeValueForKeyPath:(NSString *)keyPath
  62. ofObject:(id)object
  63. change:(NSDictionary *)change
  64. context:(void *)context
  65. {
  66. UNUSED_PARAMETER(keyPath);
  67. UNUSED_PARAMETER(object);
  68. syphon_t s = context;
  69. if (!s)
  70. return;
  71. handle_application_launch(s, change[NSKeyValueChangeNewKey]);
  72. update_properties(s);
  73. }
  74. @end
  75. static const char *syphon_get_name(void *unused)
  76. {
  77. UNUSED_PARAMETER(unused);
  78. return obs_module_text("Syphon");
  79. }
  80. static void stop_client(syphon_t s)
  81. {
  82. obs_enter_graphics();
  83. if (s->client) {
  84. @autoreleasepool {
  85. [s->client stop];
  86. objc_release(&s->client);
  87. }
  88. }
  89. if (s->tex) {
  90. gs_texture_destroy(s->tex);
  91. s->tex = NULL;
  92. }
  93. if (s->ref) {
  94. IOSurfaceDecrementUseCount(s->ref);
  95. CFRelease(s->ref);
  96. s->ref = NULL;
  97. }
  98. s->width = 0;
  99. s->height = 0;
  100. obs_leave_graphics();
  101. }
  102. static inline NSDictionary *find_by_uuid(NSArray *arr, NSString *uuid)
  103. {
  104. for (NSDictionary *dict in arr) {
  105. if ([dict[SyphonServerDescriptionUUIDKey] isEqual:uuid])
  106. return dict;
  107. }
  108. return nil;
  109. }
  110. static inline void check_version(syphon_t s, NSDictionary *desc)
  111. {
  112. extern const NSString *SyphonServerDescriptionDictionaryVersionKey;
  113. NSNumber *version = desc[SyphonServerDescriptionDictionaryVersionKey];
  114. if (!version)
  115. return LOG(LOG_WARNING, "Server description does not contain "
  116. "VersionKey");
  117. if (version.unsignedIntValue > 0)
  118. LOG(LOG_WARNING,
  119. "Got server description version %d, "
  120. "expected 0",
  121. version.unsignedIntValue);
  122. }
  123. static inline void check_description(syphon_t s, NSDictionary *desc)
  124. {
  125. extern const NSString *SyphonSurfaceType;
  126. extern const NSString *SyphonSurfaceTypeIOSurface;
  127. extern const NSString *SyphonServerDescriptionSurfacesKey;
  128. NSArray *surfaces = desc[SyphonServerDescriptionSurfacesKey];
  129. if (!surfaces)
  130. return LOG(LOG_WARNING, "Server description does not contain "
  131. "SyphonServerDescriptionSurfacesKey");
  132. if (!surfaces.count)
  133. return LOG(LOG_WARNING, "Server description contains empty "
  134. "SyphonServerDescriptionSurfacesKey");
  135. for (NSDictionary *surface in surfaces) {
  136. NSString *type = surface[SyphonSurfaceType];
  137. if (type && [type isEqual:SyphonSurfaceTypeIOSurface])
  138. return;
  139. }
  140. NSString *surfaces_string = [NSString stringWithFormat:@"%@", surfaces];
  141. LOG(LOG_WARNING,
  142. "SyphonSurfaces does not contain"
  143. "'SyphonSurfaceTypeIOSurface': %s",
  144. surfaces_string.UTF8String);
  145. }
  146. static inline bool update_string(NSString **str, NSString *new)
  147. {
  148. if (!new)
  149. return false;
  150. [*str release];
  151. *str = [new retain];
  152. return true;
  153. }
  154. static inline void handle_new_frame(syphon_t s,
  155. SYPHON_CLIENT_UNIQUE_CLASS_NAME *client)
  156. {
  157. IOSurfaceRef ref = [client IOSurface];
  158. if (!ref)
  159. return;
  160. if (ref == s->ref) {
  161. CFRelease(ref);
  162. return;
  163. }
  164. IOSurfaceIncrementUseCount(ref);
  165. obs_enter_graphics();
  166. if (s->ref) {
  167. gs_texture_destroy(s->tex);
  168. IOSurfaceDecrementUseCount(s->ref);
  169. CFRelease(s->ref);
  170. }
  171. s->ref = ref;
  172. s->tex = gs_texture_create_from_iosurface(s->ref);
  173. s->width = gs_texture_get_width(s->tex);
  174. s->height = gs_texture_get_height(s->tex);
  175. obs_leave_graphics();
  176. }
  177. static void create_client(syphon_t s)
  178. {
  179. stop_client(s);
  180. if (!s->app_name.length && !s->name.length && !s->uuid.length)
  181. return;
  182. SyphonServerDirectory *ssd = [SyphonServerDirectory sharedDirectory];
  183. NSArray *servers = [ssd serversMatchingName:s->name
  184. appName:s->app_name];
  185. if (!servers.count)
  186. return;
  187. NSDictionary *desc = find_by_uuid(servers, s->uuid);
  188. if (!desc) {
  189. desc = servers[0];
  190. if (update_string(&s->uuid,
  191. desc[SyphonServerDescriptionUUIDKey]))
  192. s->uuid_changed = true;
  193. }
  194. check_version(s, desc);
  195. check_description(s, desc);
  196. @autoreleasepool {
  197. s->client = [[SYPHON_CLIENT_UNIQUE_CLASS_NAME alloc]
  198. initWithServerDescription:desc
  199. options:nil
  200. newFrameHandler:^(
  201. SYPHON_CLIENT_UNIQUE_CLASS_NAME
  202. *client) {
  203. handle_new_frame(s, client);
  204. }];
  205. }
  206. s->active = true;
  207. }
  208. static inline void release_settings(syphon_t s)
  209. {
  210. [s->app_name release];
  211. [s->name release];
  212. [s->uuid release];
  213. }
  214. static inline bool load_syphon_settings(syphon_t s, obs_data_t *settings)
  215. {
  216. NSString *app_name = @(obs_data_get_string(settings, "app_name"));
  217. NSString *name = @(obs_data_get_string(settings, "name"));
  218. bool equal_names = [app_name isEqual:s->app_name] &&
  219. [name isEqual:s->name];
  220. if (s->uuid_changed && equal_names)
  221. return false;
  222. NSString *uuid = @(obs_data_get_string(settings, "uuid"));
  223. if ([uuid isEqual:s->uuid] && equal_names)
  224. return false;
  225. release_settings(s);
  226. s->app_name = [app_name retain];
  227. s->name = [name retain];
  228. s->uuid = [uuid retain];
  229. s->uuid_changed = false;
  230. return true;
  231. }
  232. static inline void update_from_announce(syphon_t s, NSDictionary *info)
  233. {
  234. if (s->active)
  235. return;
  236. if (!info)
  237. return;
  238. NSString *app_name = info[SyphonServerDescriptionAppNameKey];
  239. NSString *name = info[SyphonServerDescriptionNameKey];
  240. NSString *uuid = info[SyphonServerDescriptionUUIDKey];
  241. if (![uuid isEqual:s->uuid] &&
  242. !([app_name isEqual:s->app_name] && [name isEqual:s->name]))
  243. return;
  244. update_string(&s->app_name, app_name);
  245. update_string(&s->name, name);
  246. if (update_string(&s->uuid, uuid))
  247. s->uuid_changed = true;
  248. create_client(s);
  249. }
  250. static inline void update_inject_state(syphon_t s, NSDictionary *info,
  251. bool announce)
  252. {
  253. if (!info)
  254. return;
  255. NSString *app_name = info[SyphonServerDescriptionAppNameKey];
  256. NSString *name = info[SyphonServerDescriptionNameKey];
  257. NSString *uuid = info[SyphonServerDescriptionUUIDKey];
  258. if (![uuid isEqual:s->inject_uuid] &&
  259. (![app_name isEqual:s->inject_app] ||
  260. ![name isEqual:@"InjectedSyphon"]))
  261. return;
  262. if (!(s->inject_server_found = announce)) {
  263. s->inject_wait_time = 0.f;
  264. objc_release(&s->inject_uuid);
  265. LOG(LOG_INFO,
  266. "Injected server retired: "
  267. "[%s] InjectedSyphon (%s)",
  268. s->inject_app.UTF8String, uuid.UTF8String);
  269. return;
  270. }
  271. if (s->inject_uuid) //TODO: track multiple injected instances?
  272. return;
  273. s->inject_uuid = [uuid retain];
  274. LOG(LOG_INFO, "Injected server found: [%s] %s (%s)",
  275. app_name.UTF8String, name.UTF8String, uuid.UTF8String);
  276. }
  277. static inline void handle_announce(syphon_t s, NSNotification *note)
  278. {
  279. if (!note)
  280. return;
  281. update_from_announce(s, note.object);
  282. update_inject_state(s, note.object, true);
  283. update_properties(s);
  284. }
  285. static inline void update_from_retire(syphon_t s, NSDictionary *info)
  286. {
  287. if (!info)
  288. return;
  289. NSString *uuid = info[SyphonServerDescriptionUUIDKey];
  290. if (!uuid)
  291. return;
  292. if (![uuid isEqual:s->uuid])
  293. return;
  294. s->active = false;
  295. }
  296. static inline void handle_retire(syphon_t s, NSNotification *note)
  297. {
  298. if (!note)
  299. return;
  300. update_from_retire(s, note.object);
  301. update_inject_state(s, note.object, false);
  302. update_properties(s);
  303. }
  304. static inline gs_vertbuffer_t *create_vertbuffer()
  305. {
  306. struct gs_vb_data *vb_data = gs_vbdata_create();
  307. vb_data->num = 4;
  308. vb_data->points = bzalloc(sizeof(struct vec3) * 4);
  309. if (!vb_data->points)
  310. return NULL;
  311. vb_data->num_tex = 1;
  312. vb_data->tvarray = bzalloc(sizeof(struct gs_tvertarray));
  313. if (!vb_data->tvarray)
  314. goto fail_tvarray;
  315. vb_data->tvarray[0].width = 2;
  316. vb_data->tvarray[0].array = bzalloc(sizeof(struct vec2) * 4);
  317. if (!vb_data->tvarray[0].array)
  318. goto fail_array;
  319. gs_vertbuffer_t *vbuff = gs_vertexbuffer_create(vb_data, GS_DYNAMIC);
  320. if (vbuff)
  321. return vbuff;
  322. bfree(vb_data->tvarray[0].array);
  323. fail_array:
  324. bfree(vb_data->tvarray);
  325. fail_tvarray:
  326. bfree(vb_data->points);
  327. return NULL;
  328. }
  329. static inline bool init_obs_graphics_objects(syphon_t s)
  330. {
  331. struct gs_sampler_info info = {
  332. .filter = GS_FILTER_LINEAR,
  333. .address_u = GS_ADDRESS_CLAMP,
  334. .address_v = GS_ADDRESS_CLAMP,
  335. .address_w = GS_ADDRESS_CLAMP,
  336. .max_anisotropy = 1,
  337. };
  338. obs_enter_graphics();
  339. s->sampler = gs_samplerstate_create(&info);
  340. s->vertbuffer = create_vertbuffer();
  341. obs_leave_graphics();
  342. s->effect = obs_get_base_effect(OBS_EFFECT_DEFAULT_RECT);
  343. return s->sampler != NULL && s->vertbuffer != NULL && s->effect != NULL;
  344. }
  345. static inline bool create_syphon_listeners(syphon_t s)
  346. {
  347. NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  348. s->new_server_listener = [nc
  349. addObserverForName:SyphonServerAnnounceNotification
  350. object:nil
  351. queue:[NSOperationQueue mainQueue]
  352. usingBlock:^(NSNotification *note) {
  353. handle_announce(s, note);
  354. }];
  355. s->retire_listener = [nc
  356. addObserverForName:SyphonServerRetireNotification
  357. object:nil
  358. queue:[NSOperationQueue mainQueue]
  359. usingBlock:^(NSNotification *note) {
  360. handle_retire(s, note);
  361. }];
  362. return s->new_server_listener != nil && s->retire_listener != nil;
  363. }
  364. static inline bool create_applications_observer(syphon_t s, NSWorkspace *ws)
  365. {
  366. s->launch_listener = [[OBSSyphonKVObserver alloc] init];
  367. if (!s->launch_listener)
  368. return false;
  369. [ws addObserver:s->launch_listener
  370. forKeyPath:NSStringFromSelector(@selector(runningApplications))
  371. options:NSKeyValueObservingOptionNew
  372. context:s];
  373. return true;
  374. }
  375. static inline void load_crop(syphon_t s, obs_data_t *settings)
  376. {
  377. s->crop = obs_data_get_bool(settings, "crop");
  378. #define LOAD_CROP(x) s->crop_rect.x = obs_data_get_double(settings, "crop." #x)
  379. LOAD_CROP(origin.x);
  380. LOAD_CROP(origin.y);
  381. LOAD_CROP(size.width);
  382. LOAD_CROP(size.height);
  383. #undef LOAD_CROP
  384. }
  385. static inline void syphon_destroy_internal(syphon_t s);
  386. static void *syphon_create_internal(obs_data_t *settings, obs_source_t *source)
  387. {
  388. UNUSED_PARAMETER(source);
  389. syphon_t s = bzalloc(sizeof(struct syphon));
  390. if (!s)
  391. return s;
  392. s->source = source;
  393. if (!init_obs_graphics_objects(s))
  394. goto fail;
  395. if (!load_syphon_settings(s, settings))
  396. goto fail;
  397. const char *inject_info = obs_data_get_string(settings, "application");
  398. s->inject_info = obs_data_create_from_json(inject_info);
  399. s->inject_active = obs_data_get_bool(settings, "inject");
  400. s->inject_app = @(obs_data_get_string(s->inject_info, "name"));
  401. if (s->inject_app)
  402. [s->inject_app retain];
  403. if (!create_syphon_listeners(s))
  404. goto fail;
  405. NSWorkspace *ws = [NSWorkspace sharedWorkspace];
  406. if (!create_applications_observer(s, ws))
  407. goto fail;
  408. if (s->inject_active)
  409. find_and_inject_target(s, ws.runningApplications, false);
  410. create_client(s);
  411. load_crop(s, settings);
  412. s->allow_transparency =
  413. obs_data_get_bool(settings, "allow_transparency");
  414. return s;
  415. fail:
  416. syphon_destroy_internal(s);
  417. return NULL;
  418. }
  419. static void *syphon_create(obs_data_t *settings, obs_source_t *source)
  420. {
  421. @autoreleasepool {
  422. return syphon_create_internal(settings, source);
  423. }
  424. }
  425. static inline void stop_listener(id listener)
  426. {
  427. if (!listener)
  428. return;
  429. NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  430. [nc removeObserver:listener];
  431. }
  432. static inline void syphon_destroy_internal(syphon_t s)
  433. {
  434. stop_listener(s->new_server_listener);
  435. stop_listener(s->retire_listener);
  436. NSWorkspace *ws = [NSWorkspace sharedWorkspace];
  437. [ws removeObserver:s->launch_listener
  438. forKeyPath:NSStringFromSelector(@selector
  439. (runningApplications))];
  440. objc_release(&s->launch_listener);
  441. objc_release(&s->inject_app);
  442. objc_release(&s->inject_uuid);
  443. obs_data_release(s->inject_info);
  444. release_settings(s);
  445. obs_enter_graphics();
  446. stop_client(s);
  447. if (s->sampler)
  448. gs_samplerstate_destroy(s->sampler);
  449. if (s->vertbuffer)
  450. gs_vertexbuffer_destroy(s->vertbuffer);
  451. obs_leave_graphics();
  452. bfree(s);
  453. }
  454. static void syphon_destroy(void *data)
  455. {
  456. @autoreleasepool {
  457. syphon_destroy_internal(data);
  458. }
  459. }
  460. static inline NSString *get_string(obs_data_t *settings, const char *name)
  461. {
  462. if (!settings)
  463. return nil;
  464. return @(obs_data_get_string(settings, name));
  465. }
  466. static inline void update_strings_from_context(syphon_t s, obs_data_t *settings,
  467. NSString **app, NSString **name,
  468. NSString **uuid)
  469. {
  470. if (!s || !s->uuid_changed)
  471. return;
  472. s->uuid_changed = false;
  473. *app = s->app_name;
  474. *name = s->name;
  475. *uuid = s->uuid;
  476. obs_data_set_string(settings, "app_name", s->app_name.UTF8String);
  477. obs_data_set_string(settings, "name", s->name.UTF8String);
  478. obs_data_set_string(settings, "uuid", s->uuid.UTF8String);
  479. }
  480. static inline void add_servers(syphon_t s, obs_property_t *list,
  481. obs_data_t *settings)
  482. {
  483. bool found_current = settings == NULL;
  484. NSString *set_app = get_string(settings, "app_name");
  485. NSString *set_name = get_string(settings, "name");
  486. NSString *set_uuid = get_string(settings, "uuid");
  487. update_strings_from_context(s, settings, &set_app, &set_name,
  488. &set_uuid);
  489. obs_property_list_add_string(list, "", "");
  490. NSArray *arr = [[SyphonServerDirectory sharedDirectory] servers];
  491. for (NSDictionary *server in arr) {
  492. NSString *app = server[SyphonServerDescriptionAppNameKey];
  493. NSString *name = server[SyphonServerDescriptionNameKey];
  494. NSString *uuid = server[SyphonServerDescriptionUUIDKey];
  495. NSString *serv =
  496. [NSString stringWithFormat:@"[%@] %@", app, name];
  497. obs_property_list_add_string(list, serv.UTF8String,
  498. uuid.UTF8String);
  499. if (!found_current)
  500. found_current = [uuid isEqual:set_uuid];
  501. }
  502. if (found_current || !set_uuid.length || !set_app.length)
  503. return;
  504. NSString *serv =
  505. [NSString stringWithFormat:@"[%@] %@", set_app, set_name];
  506. size_t idx = obs_property_list_add_string(list, serv.UTF8String,
  507. set_uuid.UTF8String);
  508. obs_property_list_item_disable(list, idx, true);
  509. }
  510. static bool servers_changed(obs_properties_t *props, obs_property_t *list,
  511. obs_data_t *settings)
  512. {
  513. @autoreleasepool {
  514. obs_property_list_clear(list);
  515. add_servers(obs_properties_get_param(props), list, settings);
  516. return true;
  517. }
  518. }
  519. static inline NSString *get_inject_application_path()
  520. {
  521. static NSString *ident = @"zakk.lol.SyphonInject";
  522. NSWorkspace *ws = [NSWorkspace sharedWorkspace];
  523. return [ws absolutePathForAppBundleWithIdentifier:ident];
  524. }
  525. static inline bool is_inject_available_in_lib_dir(NSFileManager *fm, NSURL *url)
  526. {
  527. if (!url.isFileURL)
  528. return false;
  529. for (NSString *path in [fm contentsOfDirectoryAtPath:url.path
  530. error:nil]) {
  531. NSURL *bundle_url = [url URLByAppendingPathComponent:path];
  532. NSBundle *bundle = [NSBundle bundleWithURL:bundle_url];
  533. if (!bundle)
  534. continue;
  535. if ([bundle.bundleIdentifier
  536. isEqual:@"zakk.lol.SASyphonInjector"])
  537. return true;
  538. }
  539. return false;
  540. }
  541. static inline bool is_inject_available()
  542. {
  543. if (get_inject_application_path())
  544. return true;
  545. NSFileManager *fm = [NSFileManager defaultManager];
  546. for (NSURL *url in [fm URLsForDirectory:NSLibraryDirectory
  547. inDomains:NSAllDomainsMask]) {
  548. NSURL *scripting = [url
  549. URLByAppendingPathComponent:@"ScriptingAdditions"
  550. isDirectory:true];
  551. if (is_inject_available_in_lib_dir(fm, scripting))
  552. return true;
  553. }
  554. return false;
  555. }
  556. static inline void launch_syphon_inject_internal()
  557. {
  558. NSString *path = get_inject_application_path();
  559. NSWorkspace *ws = [NSWorkspace sharedWorkspace];
  560. if (path)
  561. [ws launchApplication:path];
  562. }
  563. static bool launch_syphon_inject(obs_properties_t *props, obs_property_t *prop,
  564. void *data)
  565. {
  566. UNUSED_PARAMETER(props);
  567. UNUSED_PARAMETER(prop);
  568. UNUSED_PARAMETER(data);
  569. @autoreleasepool {
  570. launch_syphon_inject_internal();
  571. return false;
  572. }
  573. }
  574. static int describes_app(obs_data_t *info, NSRunningApplication *app)
  575. {
  576. int score = 0;
  577. if ([app.localizedName isEqual:get_string(info, "name")])
  578. score += 2;
  579. if ([app.bundleIdentifier isEqual:get_string(info, "bundle")])
  580. score += 2;
  581. if ([app.executableURL isEqual:get_string(info, "executable")])
  582. score += 2;
  583. if (score && app.processIdentifier == obs_data_get_int(info, "pid"))
  584. score += 1;
  585. return score;
  586. }
  587. static inline void app_to_data(NSRunningApplication *app, obs_data_t *app_data)
  588. {
  589. obs_data_set_string(app_data, "name", app.localizedName.UTF8String);
  590. obs_data_set_string(app_data, "bundle",
  591. app.bundleIdentifier.UTF8String);
  592. // Until we drop 10.8, use path.fileSystemRepsentation
  593. obs_data_set_string(app_data, "executable",
  594. app.executableURL.path.fileSystemRepresentation);
  595. obs_data_set_int(app_data, "pid", app.processIdentifier);
  596. }
  597. static inline NSDictionary *get_duplicate_names(NSArray *apps)
  598. {
  599. NSMutableDictionary *result =
  600. [NSMutableDictionary dictionaryWithCapacity:apps.count];
  601. for (NSRunningApplication *app in apps) {
  602. if (result[app.localizedName])
  603. result[app.localizedName] = @(true);
  604. else
  605. result[app.localizedName] = @(false);
  606. }
  607. return result;
  608. }
  609. static inline size_t add_app(obs_property_t *prop, NSDictionary *duplicates,
  610. NSString *name, const char *bundle,
  611. const char *json_data, bool is_duplicate,
  612. pid_t pid)
  613. {
  614. if (!is_duplicate) {
  615. NSNumber *val = duplicates[name];
  616. is_duplicate = val && val.boolValue;
  617. }
  618. if (is_duplicate)
  619. name = [NSString
  620. stringWithFormat:@"%@ (%s: %d)", name, bundle, pid];
  621. return obs_property_list_add_string(prop, name.UTF8String, json_data);
  622. }
  623. static void update_inject_list_internal(obs_properties_t *props,
  624. obs_property_t *prop,
  625. obs_data_t *settings)
  626. {
  627. UNUSED_PARAMETER(props);
  628. const char *current_str = obs_data_get_string(settings, "application");
  629. obs_data_t *current = obs_data_create_from_json(current_str);
  630. NSString *current_name = @(obs_data_get_string(current, "name"));
  631. bool current_found = !obs_data_has_user_value(current, "name");
  632. obs_property_list_clear(prop);
  633. obs_property_list_add_string(prop, "", "");
  634. NSWorkspace *ws = [NSWorkspace sharedWorkspace];
  635. NSArray *apps = ws.runningApplications;
  636. NSDictionary *duplicates = get_duplicate_names(apps);
  637. NSMapTable *candidates = [NSMapTable weakToStrongObjectsMapTable];
  638. obs_data_t *app_data = obs_data_create();
  639. for (NSRunningApplication *app in apps) {
  640. app_to_data(app, app_data);
  641. int score = describes_app(current, app);
  642. NSString *name = app.localizedName;
  643. add_app(prop, duplicates, name, app.bundleIdentifier.UTF8String,
  644. obs_data_get_json(app_data),
  645. [name isEqual:current_name] && score < 4,
  646. app.processIdentifier);
  647. if (score >= 4) {
  648. [candidates setObject:@(score) forKey:app];
  649. current_found = true;
  650. }
  651. }
  652. obs_data_release(app_data);
  653. if (!current_found) {
  654. size_t idx = add_app(prop, duplicates, current_name,
  655. obs_data_get_string(current, "bundle"),
  656. current_str,
  657. duplicates[current_name] != nil,
  658. obs_data_get_int(current, "pid"));
  659. obs_property_list_item_disable(prop, idx, true);
  660. } else if (candidates.count > 0) {
  661. NSRunningApplication *best_match = nil;
  662. NSNumber *best_match_score = @(0);
  663. for (NSRunningApplication *app in candidates.keyEnumerator) {
  664. NSNumber *score = [candidates objectForKey:app];
  665. if ([score compare:best_match_score] ==
  666. NSOrderedDescending) {
  667. best_match = app;
  668. best_match_score = score;
  669. }
  670. }
  671. // Update settings in case of PID/executable updates
  672. if (best_match_score.intValue >= 4) {
  673. app_to_data(best_match, current);
  674. obs_data_set_string(settings, "application",
  675. obs_data_get_json(current));
  676. }
  677. }
  678. obs_data_release(current);
  679. }
  680. static void toggle_inject_internal(obs_properties_t *props,
  681. obs_property_t *prop, obs_data_t *settings)
  682. {
  683. bool enabled = obs_data_get_bool(settings, "inject");
  684. obs_property_t *inject_list = obs_properties_get(props, "application");
  685. bool inject_enabled = obs_property_enabled(prop);
  686. obs_property_set_enabled(inject_list, enabled && inject_enabled);
  687. }
  688. static bool toggle_inject(obs_properties_t *props, obs_property_t *prop,
  689. obs_data_t *settings)
  690. {
  691. @autoreleasepool {
  692. toggle_inject_internal(props, prop, settings);
  693. return true;
  694. }
  695. }
  696. static bool update_inject_list(obs_properties_t *props, obs_property_t *prop,
  697. obs_data_t *settings)
  698. {
  699. @autoreleasepool {
  700. update_inject_list_internal(props, prop, settings);
  701. return true;
  702. }
  703. }
  704. static bool update_crop(obs_properties_t *props, obs_property_t *prop,
  705. obs_data_t *settings)
  706. {
  707. bool enabled = obs_data_get_bool(settings, "crop");
  708. #define LOAD_CROP(x) \
  709. prop = obs_properties_get(props, "crop." #x); \
  710. obs_property_set_enabled(prop, enabled);
  711. LOAD_CROP(origin.x);
  712. LOAD_CROP(origin.y);
  713. LOAD_CROP(size.width);
  714. LOAD_CROP(size.height);
  715. #undef LOAD_CROP
  716. return true;
  717. }
  718. static void show_syphon_license_internal(void)
  719. {
  720. char *path = obs_module_file("syphon_license.txt");
  721. if (!path)
  722. return;
  723. NSWorkspace *ws = [NSWorkspace sharedWorkspace];
  724. [ws openFile:@(path)];
  725. bfree(path);
  726. }
  727. static bool show_syphon_license(obs_properties_t *props, obs_property_t *prop,
  728. void *data)
  729. {
  730. UNUSED_PARAMETER(props);
  731. UNUSED_PARAMETER(prop);
  732. UNUSED_PARAMETER(data);
  733. @autoreleasepool {
  734. show_syphon_license_internal();
  735. return false;
  736. }
  737. }
  738. static void syphon_release(void *param)
  739. {
  740. if (!param)
  741. return;
  742. obs_source_release(((syphon_t)param)->source);
  743. }
  744. static inline obs_properties_t *syphon_properties_internal(syphon_t s)
  745. {
  746. if (s)
  747. obs_source_addref(s->source);
  748. obs_properties_t *props =
  749. obs_properties_create_param(s, syphon_release);
  750. obs_property_t *list = obs_properties_add_list(
  751. props, "uuid", obs_module_text("Source"), OBS_COMBO_TYPE_LIST,
  752. OBS_COMBO_FORMAT_STRING);
  753. obs_property_set_modified_callback(list, servers_changed);
  754. obs_properties_add_bool(props, "allow_transparency",
  755. obs_module_text("AllowTransparency"));
  756. obs_property_t *launch = obs_properties_add_button(
  757. props, "launch inject", obs_module_text("LaunchSyphonInject"),
  758. launch_syphon_inject);
  759. obs_property_t *inject = obs_properties_add_bool(
  760. props, "inject", obs_module_text("Inject"));
  761. obs_property_set_modified_callback(inject, toggle_inject);
  762. obs_property_t *inject_list = obs_properties_add_list(
  763. props, "application", obs_module_text("Application"),
  764. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  765. obs_property_set_modified_callback(inject_list, update_inject_list);
  766. if (!get_inject_application_path())
  767. obs_property_set_enabled(launch, false);
  768. if (!is_inject_available()) {
  769. obs_property_set_enabled(inject, false);
  770. obs_property_set_enabled(inject_list, false);
  771. }
  772. obs_property_t *crop =
  773. obs_properties_add_bool(props, "crop", obs_module_text("Crop"));
  774. obs_property_set_modified_callback(crop, update_crop);
  775. #define LOAD_CROP(x) \
  776. obs_properties_add_float(props, "crop." #x, \
  777. obs_module_text("Crop." #x), 0., 4096.f, \
  778. .5f);
  779. LOAD_CROP(origin.x);
  780. LOAD_CROP(origin.y);
  781. LOAD_CROP(size.width);
  782. LOAD_CROP(size.height);
  783. #undef LOAD_CROP
  784. obs_properties_add_button(props, "syphon license",
  785. obs_module_text("SyphonLicense"),
  786. show_syphon_license);
  787. return props;
  788. }
  789. static obs_properties_t *syphon_properties(void *data)
  790. {
  791. @autoreleasepool {
  792. return syphon_properties_internal(data);
  793. }
  794. }
  795. static inline void syphon_save_internal(syphon_t s, obs_data_t *settings)
  796. {
  797. if (!s->uuid_changed)
  798. return;
  799. obs_data_set_string(settings, "app_name", s->app_name.UTF8String);
  800. obs_data_set_string(settings, "name", s->name.UTF8String);
  801. obs_data_set_string(settings, "uuid", s->uuid.UTF8String);
  802. }
  803. static void syphon_save(void *data, obs_data_t *settings)
  804. {
  805. @autoreleasepool {
  806. syphon_save_internal(data, settings);
  807. }
  808. }
  809. static inline void build_sprite(struct gs_vb_data *data, float fcx, float fcy,
  810. float start_u, float end_u, float start_v,
  811. float end_v)
  812. {
  813. struct vec2 *tvarray = data->tvarray[0].array;
  814. vec3_set(data->points + 1, fcx, 0.0f, 0.0f);
  815. vec3_set(data->points + 2, 0.0f, fcy, 0.0f);
  816. vec3_set(data->points + 3, fcx, fcy, 0.0f);
  817. vec2_set(tvarray, start_u, start_v);
  818. vec2_set(tvarray + 1, end_u, start_v);
  819. vec2_set(tvarray + 2, start_u, end_v);
  820. vec2_set(tvarray + 3, end_u, end_v);
  821. }
  822. static inline void build_sprite_rect(struct gs_vb_data *data, float origin_x,
  823. float origin_y, float end_x, float end_y)
  824. {
  825. build_sprite(data, fabs(end_x - origin_x), fabs(end_y - origin_y),
  826. origin_x, end_x, origin_y, end_y);
  827. }
  828. static inline void tick_inject_state(syphon_t s, float seconds)
  829. {
  830. s->inject_wait_time -= seconds;
  831. if (s->inject_wait_time > 0.f)
  832. return;
  833. s->inject_wait_time = 1.f;
  834. NSWorkspace *ws = [NSWorkspace sharedWorkspace];
  835. find_and_inject_target(s, ws.runningApplications, true);
  836. }
  837. static void syphon_video_tick(void *data, float seconds)
  838. {
  839. UNUSED_PARAMETER(seconds);
  840. syphon_t s = data;
  841. if (s->inject_active && !s->inject_server_found)
  842. tick_inject_state(s, seconds);
  843. if (!s->tex)
  844. return;
  845. static const CGRect null_crop = {{0.f}};
  846. const CGRect *crop = &null_crop;
  847. if (s->crop)
  848. crop = &s->crop_rect;
  849. obs_enter_graphics();
  850. build_sprite_rect(gs_vertexbuffer_get_data(s->vertbuffer),
  851. crop->origin.x, s->height - crop->origin.y,
  852. s->width - crop->size.width, crop->size.height);
  853. obs_leave_graphics();
  854. }
  855. static void syphon_video_render(void *data, gs_effect_t *effect)
  856. {
  857. UNUSED_PARAMETER(effect);
  858. syphon_t s = data;
  859. if (!s->tex)
  860. return;
  861. bool disable_blending = !s->allow_transparency;
  862. if (disable_blending) {
  863. gs_enable_blending(false);
  864. gs_enable_color(true, true, true, false);
  865. }
  866. gs_vertexbuffer_flush(s->vertbuffer);
  867. gs_load_vertexbuffer(s->vertbuffer);
  868. gs_load_indexbuffer(NULL);
  869. gs_load_samplerstate(s->sampler, 0);
  870. gs_technique_t *tech = gs_effect_get_technique(s->effect, "Draw");
  871. gs_effect_set_texture(gs_effect_get_param_by_name(s->effect, "image"),
  872. s->tex);
  873. gs_technique_begin(tech);
  874. gs_technique_begin_pass(tech, 0);
  875. gs_draw(GS_TRISTRIP, 0, 4);
  876. gs_technique_end_pass(tech);
  877. gs_technique_end(tech);
  878. if (disable_blending) {
  879. gs_enable_color(true, true, true, true);
  880. gs_enable_blending(true);
  881. }
  882. }
  883. static uint32_t syphon_get_width(void *data)
  884. {
  885. syphon_t s = (syphon_t)data;
  886. if (!s->crop)
  887. return s->width;
  888. int32_t width =
  889. s->width - s->crop_rect.origin.x - s->crop_rect.size.width;
  890. return MAX(0, width);
  891. }
  892. static uint32_t syphon_get_height(void *data)
  893. {
  894. syphon_t s = (syphon_t)data;
  895. if (!s->crop)
  896. return s->height;
  897. int32_t height =
  898. s->height - s->crop_rect.origin.y - s->crop_rect.size.height;
  899. return MAX(0, height);
  900. }
  901. static inline void inject_app(syphon_t s, NSRunningApplication *app, bool retry)
  902. {
  903. SBApplication *sbapp = nil;
  904. if (app.processIdentifier != -1)
  905. sbapp = [SBApplication
  906. applicationWithProcessIdentifier:app.processIdentifier];
  907. else if (app.bundleIdentifier)
  908. sbapp = [SBApplication
  909. applicationWithBundleIdentifier:app.bundleIdentifier];
  910. if (!sbapp)
  911. return LOG(LOG_ERROR, "Could not inject %s",
  912. app.localizedName.UTF8String);
  913. sbapp.timeout = 10 * 60;
  914. sbapp.sendMode = kAEWaitReply;
  915. [sbapp sendEvent:'ascr' id:'gdut' parameters:0];
  916. sbapp.sendMode = kAENoReply;
  917. [sbapp sendEvent:'SASI' id:'injc' parameters:0];
  918. if (retry)
  919. return;
  920. LOG(LOG_INFO, "Injected '%s' (%d, '%s')", app.localizedName.UTF8String,
  921. app.processIdentifier, app.bundleIdentifier.UTF8String);
  922. }
  923. static inline void find_and_inject_target(syphon_t s, NSArray *arr, bool retry)
  924. {
  925. NSMutableArray *best_matches = [NSMutableArray arrayWithCapacity:1];
  926. int best_score = 0;
  927. for (NSRunningApplication *app in arr) {
  928. int score = describes_app(s->inject_info, app);
  929. if (!score)
  930. continue;
  931. if (score > best_score) {
  932. best_score = score;
  933. [best_matches removeAllObjects];
  934. }
  935. if (score >= best_score)
  936. [best_matches addObject:app];
  937. }
  938. for (NSRunningApplication *app in best_matches)
  939. inject_app(s, app, retry);
  940. }
  941. static inline bool inject_info_equal(obs_data_t *prev, obs_data_t *new)
  942. {
  943. if (![get_string(prev, "name") isEqual:get_string(new, "name")])
  944. return false;
  945. if (![get_string(prev, "bundle") isEqual:get_string(new, "bundle")])
  946. return false;
  947. if (![get_string(prev, "executable")
  948. isEqual:get_string(new, "executable")])
  949. return false;
  950. if (![get_string(prev, "pid") isEqual:get_string(new, "pid")])
  951. return false;
  952. return true;
  953. }
  954. static inline void update_inject(syphon_t s, obs_data_t *settings)
  955. {
  956. bool try_injecting = s->inject_active;
  957. s->inject_active = obs_data_get_bool(settings, "inject");
  958. const char *inject_str = obs_data_get_string(settings, "application");
  959. try_injecting = !try_injecting && s->inject_active;
  960. obs_data_t *prev = s->inject_info;
  961. s->inject_info = obs_data_create_from_json(inject_str);
  962. NSString *prev_app = s->inject_app;
  963. s->inject_app = [@(obs_data_get_string(s->inject_info, "name")) retain];
  964. [prev_app release];
  965. objc_release(&s->inject_uuid);
  966. SyphonServerDirectory *ssd = [SyphonServerDirectory sharedDirectory];
  967. NSArray *servers = [ssd serversMatchingName:@"InjectedSyphon"
  968. appName:s->inject_app];
  969. s->inject_server_found = false;
  970. for (NSDictionary *server in servers)
  971. update_inject_state(s, server, true);
  972. if (!try_injecting)
  973. try_injecting = s->inject_active &&
  974. !inject_info_equal(prev, s->inject_info);
  975. obs_data_release(prev);
  976. if (!try_injecting)
  977. return;
  978. NSWorkspace *ws = [NSWorkspace sharedWorkspace];
  979. find_and_inject_target(s, ws.runningApplications, false);
  980. }
  981. static inline bool update_syphon(syphon_t s, obs_data_t *settings)
  982. {
  983. NSArray *arr = [[SyphonServerDirectory sharedDirectory] servers];
  984. if (!load_syphon_settings(s, settings))
  985. return false;
  986. NSDictionary *dict = find_by_uuid(arr, s->uuid);
  987. if (dict) {
  988. NSString *app = dict[SyphonServerDescriptionAppNameKey];
  989. NSString *name = dict[SyphonServerDescriptionNameKey];
  990. obs_data_set_string(settings, "app_name", app.UTF8String);
  991. obs_data_set_string(settings, "name", name.UTF8String);
  992. load_syphon_settings(s, settings);
  993. } else if (!dict && !s->uuid.length) {
  994. obs_data_set_string(settings, "app_name", "");
  995. obs_data_set_string(settings, "name", "");
  996. load_syphon_settings(s, settings);
  997. }
  998. return true;
  999. }
  1000. static void syphon_update_internal(syphon_t s, obs_data_t *settings)
  1001. {
  1002. s->allow_transparency =
  1003. obs_data_get_bool(settings, "allow_transparency");
  1004. load_crop(s, settings);
  1005. update_inject(s, settings);
  1006. if (update_syphon(s, settings))
  1007. create_client(s);
  1008. }
  1009. static void syphon_update(void *data, obs_data_t *settings)
  1010. {
  1011. @autoreleasepool {
  1012. syphon_update_internal(data, settings);
  1013. }
  1014. }
  1015. struct obs_source_info syphon_info = {
  1016. .id = "syphon-input",
  1017. .type = OBS_SOURCE_TYPE_INPUT,
  1018. .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW |
  1019. OBS_SOURCE_DO_NOT_DUPLICATE,
  1020. .get_name = syphon_get_name,
  1021. .create = syphon_create,
  1022. .destroy = syphon_destroy,
  1023. .video_render = syphon_video_render,
  1024. .video_tick = syphon_video_tick,
  1025. .get_properties = syphon_properties,
  1026. .get_width = syphon_get_width,
  1027. .get_height = syphon_get_height,
  1028. .update = syphon_update,
  1029. .save = syphon_save,
  1030. };