camera-portal.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. /* camera-portal.c
  2. *
  3. * Copyright 2021 Georges Basile Stavracas Neto <[email protected]>
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * SPDX-License-Identifier: GPL-2.0-or-later
  19. */
  20. #include "pipewire.h"
  21. #include "formats.h"
  22. #include "portal.h"
  23. #include <util/dstr.h>
  24. #include <fcntl.h>
  25. #include <unistd.h>
  26. #include <gio/gio.h>
  27. #include <gio/gunixfdlist.h>
  28. #include <spa/node/keys.h>
  29. #include <spa/pod/iter.h>
  30. #include <spa/pod/parser.h>
  31. #include <spa/param/props.h>
  32. #include <spa/utils/defs.h>
  33. #include <spa/utils/keys.h>
  34. #include <spa/utils/result.h>
  35. struct camera_portal_source {
  36. obs_source_t *source;
  37. obs_data_t *settings;
  38. obs_pipewire_stream *obs_pw_stream;
  39. char *device_id;
  40. struct {
  41. struct spa_rectangle rect;
  42. bool set;
  43. } resolution;
  44. struct {
  45. struct spa_fraction fraction;
  46. bool set;
  47. } framerate;
  48. };
  49. /* ------------------------------------------------- */
  50. struct pw_portal_connection {
  51. obs_pipewire *obs_pw;
  52. GHashTable *devices;
  53. GCancellable *cancellable;
  54. GPtrArray *sources;
  55. bool initializing;
  56. };
  57. struct pw_portal_connection *connection = NULL;
  58. static void pw_portal_connection_free(struct pw_portal_connection *connection)
  59. {
  60. if (!connection)
  61. return;
  62. g_cancellable_cancel(connection->cancellable);
  63. g_clear_pointer(&connection->devices, g_hash_table_destroy);
  64. g_clear_pointer(&connection->obs_pw, obs_pipewire_destroy);
  65. g_clear_pointer(&connection->sources, g_ptr_array_unref);
  66. g_clear_object(&connection->cancellable);
  67. bfree(connection);
  68. }
  69. static GDBusProxy *camera_proxy = NULL;
  70. static void ensure_camera_portal_proxy(void)
  71. {
  72. g_autoptr(GError) error = NULL;
  73. if (!camera_proxy) {
  74. camera_proxy = g_dbus_proxy_new_sync(portal_get_dbus_connection(), G_DBUS_PROXY_FLAGS_NONE, NULL,
  75. "org.freedesktop.portal.Desktop",
  76. "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Camera",
  77. NULL, &error);
  78. if (error) {
  79. blog(LOG_WARNING, "[portals] Error retrieving D-Bus proxy: %s", error->message);
  80. return;
  81. }
  82. }
  83. }
  84. static GDBusProxy *get_camera_portal_proxy(void)
  85. {
  86. ensure_camera_portal_proxy();
  87. return camera_proxy;
  88. }
  89. /* ------------------------------------------------- */
  90. struct camera_device {
  91. uint32_t id;
  92. struct pw_properties *properties;
  93. struct pw_proxy *proxy;
  94. struct spa_hook proxy_listener;
  95. struct pw_node *node;
  96. struct spa_hook node_listener;
  97. struct pw_node_info *info;
  98. uint32_t changed;
  99. struct spa_list pending_list;
  100. struct spa_list param_list;
  101. int pending_sync;
  102. };
  103. struct param {
  104. uint32_t id;
  105. int32_t seq;
  106. struct spa_list link;
  107. struct spa_pod *param;
  108. };
  109. static uint32_t clear_params(struct spa_list *param_list, uint32_t id)
  110. {
  111. struct param *p, *t;
  112. uint32_t count = 0;
  113. spa_list_for_each_safe(p, t, param_list, link)
  114. {
  115. if (id == SPA_ID_INVALID || p->id == id) {
  116. spa_list_remove(&p->link);
  117. free(p);
  118. count++;
  119. }
  120. }
  121. return count;
  122. }
  123. static struct param *add_param(struct spa_list *params, int seq, uint32_t id, const struct spa_pod *param)
  124. {
  125. struct param *p;
  126. if (id == SPA_ID_INVALID) {
  127. if (param == NULL || !spa_pod_is_object(param)) {
  128. errno = EINVAL;
  129. return NULL;
  130. }
  131. id = SPA_POD_OBJECT_ID(param);
  132. }
  133. p = malloc(sizeof(*p) + (param != NULL ? SPA_POD_SIZE(param) : 0));
  134. if (p == NULL)
  135. return NULL;
  136. p->id = id;
  137. p->seq = seq;
  138. if (param != NULL) {
  139. p->param = SPA_PTROFF(p, sizeof(*p), struct spa_pod);
  140. memcpy(p->param, param, SPA_POD_SIZE(param));
  141. } else {
  142. clear_params(params, id);
  143. p->param = NULL;
  144. }
  145. spa_list_append(params, &p->link);
  146. return p;
  147. }
  148. static void object_update_params(struct spa_list *param_list, struct spa_list *pending_list, uint32_t n_params,
  149. struct spa_param_info *params)
  150. {
  151. struct param *p, *t;
  152. uint32_t i;
  153. for (i = 0; i < n_params; i++) {
  154. spa_list_for_each_safe(p, t, pending_list, link)
  155. {
  156. if (p->id == params[i].id && p->seq != params[i].seq && p->param != NULL) {
  157. spa_list_remove(&p->link);
  158. free(p);
  159. }
  160. }
  161. }
  162. spa_list_consume(p, pending_list, link)
  163. {
  164. spa_list_remove(&p->link);
  165. if (p->param == NULL) {
  166. clear_params(param_list, p->id);
  167. free(p);
  168. } else {
  169. spa_list_append(param_list, &p->link);
  170. }
  171. }
  172. }
  173. static struct camera_device *camera_device_new(uint32_t id, const struct spa_dict *properties)
  174. {
  175. struct camera_device *device = bzalloc(sizeof(struct camera_device));
  176. device->id = id;
  177. device->properties = properties ? pw_properties_new_dict(properties) : NULL;
  178. spa_list_init(&device->pending_list);
  179. spa_list_init(&device->param_list);
  180. return device;
  181. }
  182. static void camera_device_free(struct camera_device *device)
  183. {
  184. if (!device)
  185. return;
  186. clear_params(&device->pending_list, SPA_ID_INVALID);
  187. clear_params(&device->param_list, SPA_ID_INVALID);
  188. g_clear_pointer(&device->proxy, pw_proxy_destroy);
  189. g_clear_pointer(&device->properties, pw_properties_free);
  190. bfree(device);
  191. }
  192. /* ------------------------------------------------- */
  193. static bool update_device_id(struct camera_portal_source *camera_source, const char *new_device_id)
  194. {
  195. if (strcmp(camera_source->device_id, new_device_id) == 0)
  196. return false;
  197. g_clear_pointer(&camera_source->device_id, bfree);
  198. camera_source->device_id = bstrdup(new_device_id);
  199. return true;
  200. }
  201. static void stream_camera(struct camera_portal_source *camera_source)
  202. {
  203. struct obs_pipwire_connect_stream_info connect_info;
  204. const struct spa_rectangle *resolution = NULL;
  205. const struct spa_fraction *framerate = NULL;
  206. struct camera_device *device;
  207. g_clear_pointer(&camera_source->obs_pw_stream, obs_pipewire_stream_destroy);
  208. device = g_hash_table_lookup(connection->devices, camera_source->device_id);
  209. if (!device)
  210. return;
  211. blog(LOG_INFO, "[camera-portal] streaming camera '%s'", camera_source->device_id);
  212. if (camera_source->resolution.set)
  213. resolution = &camera_source->resolution.rect;
  214. if (camera_source->framerate.set)
  215. framerate = &camera_source->framerate.fraction;
  216. connect_info = (struct obs_pipwire_connect_stream_info){
  217. .stream_name = "OBS PipeWire Camera",
  218. .stream_properties = pw_properties_new(PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture",
  219. PW_KEY_MEDIA_ROLE, "Camera", NULL),
  220. .video = {
  221. .resolution = resolution,
  222. .framerate = framerate,
  223. }};
  224. camera_source->obs_pw_stream =
  225. obs_pipewire_connect_stream(connection->obs_pw, camera_source->source, device->id, &connect_info);
  226. }
  227. static void camera_format_list(struct camera_device *dev, obs_property_t *prop)
  228. {
  229. struct param *p;
  230. enum video_format last_format = VIDEO_FORMAT_NONE;
  231. obs_property_list_clear(prop);
  232. spa_list_for_each(p, &dev->param_list, link)
  233. {
  234. struct obs_pw_video_format obs_pw_video_format;
  235. uint32_t media_type, media_subtype, format;
  236. if (p->id != SPA_PARAM_EnumFormat || p->param == NULL)
  237. continue;
  238. if (spa_format_parse(p->param, &media_type, &media_subtype) < 0)
  239. continue;
  240. if (media_type != SPA_MEDIA_TYPE_video)
  241. continue;
  242. if (media_subtype == SPA_MEDIA_SUBTYPE_raw) {
  243. if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_format,
  244. SPA_POD_Id(&format)) < 0)
  245. continue;
  246. } else {
  247. format = SPA_VIDEO_FORMAT_ENCODED;
  248. }
  249. if (!obs_pw_video_format_from_spa_format(format, &obs_pw_video_format))
  250. continue;
  251. if (obs_pw_video_format.video_format == last_format)
  252. continue;
  253. last_format = obs_pw_video_format.video_format;
  254. obs_property_list_add_int(prop, obs_pw_video_format.pretty_name, format);
  255. }
  256. }
  257. static bool control_changed(void *data, obs_properties_t *props, obs_property_t *prop, obs_data_t *settings)
  258. {
  259. UNUSED_PARAMETER(props);
  260. struct camera_device *dev;
  261. const char *device_id;
  262. uint32_t id;
  263. char buf[1024];
  264. struct spa_pod_builder b = SPA_POD_BUILDER_INIT(buf, sizeof(buf));
  265. struct spa_pod_frame f[1];
  266. struct spa_pod *param;
  267. device_id = obs_data_get_string(settings, "device_id");
  268. dev = g_hash_table_lookup(connection->devices, device_id);
  269. if (dev == NULL) {
  270. blog(LOG_ERROR, "unknown device %s", device_id);
  271. return false;
  272. }
  273. id = SPA_PTR_TO_UINT32(data);
  274. spa_pod_builder_push_object(&b, &f[0], SPA_TYPE_OBJECT_Props, SPA_PARAM_Props);
  275. switch (obs_property_get_type(prop)) {
  276. case OBS_PROPERTY_BOOL: {
  277. bool val = obs_data_get_bool(settings, obs_property_name(prop));
  278. spa_pod_builder_add(&b, id, SPA_POD_Bool(val), 0);
  279. break;
  280. }
  281. case OBS_PROPERTY_FLOAT: {
  282. float val = obs_data_get_double(settings, obs_property_name(prop));
  283. spa_pod_builder_add(&b, id, SPA_POD_Float(val), 0);
  284. break;
  285. }
  286. case OBS_PROPERTY_INT:
  287. case OBS_PROPERTY_LIST: {
  288. int val = obs_data_get_int(settings, obs_property_name(prop));
  289. spa_pod_builder_add(&b, id, SPA_POD_Int(val), 0);
  290. break;
  291. }
  292. default:
  293. blog(LOG_ERROR, "unknown property type for %s", obs_property_name(prop));
  294. return false;
  295. }
  296. param = spa_pod_builder_pop(&b, &f[0]);
  297. pw_node_set_param((struct pw_node *)dev->proxy, SPA_PARAM_Props, 0, param);
  298. return true;
  299. }
  300. static inline void add_control_property(obs_properties_t *props, obs_data_t *settings, struct camera_device *dev,
  301. struct param *p)
  302. {
  303. UNUSED_PARAMETER(dev);
  304. const struct spa_pod *type, *pod, *labels = NULL;
  305. uint32_t id, n_vals, choice, container = SPA_ID_INVALID;
  306. obs_property_t *prop = NULL;
  307. const char *name;
  308. if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_PropInfo, NULL, SPA_PROP_INFO_id, SPA_POD_Id(&id),
  309. SPA_PROP_INFO_description, SPA_POD_OPT_String(&name), SPA_PROP_INFO_type,
  310. SPA_POD_PodChoice(&type), SPA_PROP_INFO_container, SPA_POD_OPT_Id(&container),
  311. SPA_PROP_INFO_labels, SPA_POD_OPT_PodStruct(&labels)) < 0)
  312. return;
  313. pod = spa_pod_get_values(type, &n_vals, &choice);
  314. container = container != SPA_ID_INVALID ? container : SPA_POD_TYPE(pod);
  315. switch (SPA_POD_TYPE(pod)) {
  316. case SPA_TYPE_Int: {
  317. int32_t *vals = SPA_POD_BODY(pod);
  318. int32_t min, max, def, step;
  319. if (n_vals < 1)
  320. return;
  321. def = vals[0];
  322. if (choice == SPA_CHOICE_Enum) {
  323. struct spa_pod_parser prs;
  324. struct spa_pod_frame f;
  325. if (labels == NULL)
  326. return;
  327. prop = obs_properties_add_list(props, (char *)name, (char *)name, OBS_COMBO_TYPE_LIST,
  328. OBS_COMBO_FORMAT_INT);
  329. spa_pod_parser_pod(&prs, (struct spa_pod *)labels);
  330. if (spa_pod_parser_push_struct(&prs, &f) < 0)
  331. return;
  332. while (1) {
  333. int32_t id;
  334. const char *desc;
  335. if (spa_pod_parser_get_int(&prs, &id) < 0 || spa_pod_parser_get_string(&prs, &desc) < 0)
  336. break;
  337. obs_property_list_add_int(prop, (char *)desc, id);
  338. }
  339. } else {
  340. min = n_vals > 1 ? vals[1] : def;
  341. max = n_vals > 2 ? vals[2] : def;
  342. step = n_vals > 3 ? vals[3] : (max - min) / 256.0f;
  343. prop = obs_properties_add_int_slider(props, (char *)name, (char *)name, min, max, step);
  344. }
  345. obs_data_set_default_int(settings, (char *)name, def);
  346. obs_property_set_modified_callback2(prop, control_changed, SPA_UINT32_TO_PTR(id));
  347. break;
  348. }
  349. case SPA_TYPE_Bool: {
  350. int32_t *vals = SPA_POD_BODY(pod);
  351. if (n_vals < 1)
  352. return;
  353. prop = obs_properties_add_bool(props, (char *)name, (char *)name);
  354. obs_data_set_default_bool(settings, (char *)name, vals[0]);
  355. obs_property_set_modified_callback2(prop, control_changed, SPA_UINT32_TO_PTR(id));
  356. break;
  357. }
  358. case SPA_TYPE_Float: {
  359. float *vals = SPA_POD_BODY(pod);
  360. float min, max, def, step;
  361. if (n_vals < 1)
  362. return;
  363. def = vals[0];
  364. min = n_vals > 1 ? vals[1] : def;
  365. max = n_vals > 2 ? vals[2] : def;
  366. step = n_vals > 3 ? vals[3] : (max - min) / 256.0f;
  367. prop = obs_properties_add_float_slider(props, (char *)name, (char *)name, min, max, step);
  368. obs_data_set_default_double(settings, (char *)name, def);
  369. obs_property_set_modified_callback2(prop, control_changed, SPA_UINT32_TO_PTR(id));
  370. break;
  371. }
  372. default:
  373. break;
  374. }
  375. }
  376. static void camera_update_controls(struct camera_device *dev, obs_properties_t *props, obs_data_t *settings)
  377. {
  378. struct param *p;
  379. spa_list_for_each(p, &dev->param_list, link)
  380. {
  381. if (p->id != SPA_PARAM_PropInfo || p->param == NULL)
  382. continue;
  383. add_control_property(props, settings, dev, p);
  384. }
  385. }
  386. static bool device_selected(void *data, obs_properties_t *props, obs_property_t *property, obs_data_t *settings)
  387. {
  388. UNUSED_PARAMETER(props);
  389. UNUSED_PARAMETER(property);
  390. struct camera_portal_source *camera_source = data;
  391. const char *device_id;
  392. struct camera_device *device;
  393. obs_properties_t *new_control_properties;
  394. device_id = obs_data_get_string(settings, "device_id");
  395. blog(LOG_INFO, "[camera-portal] selected camera '%s'", device_id);
  396. device = g_hash_table_lookup(connection->devices, device_id);
  397. if (device == NULL)
  398. return false;
  399. if (update_device_id(camera_source, device_id))
  400. stream_camera(camera_source);
  401. blog(LOG_INFO, "[camera-portal] Updating pixel formats");
  402. property = obs_properties_get(props, "pixelformat");
  403. new_control_properties = obs_properties_create();
  404. obs_properties_remove_by_name(props, "controls");
  405. camera_format_list(device, property);
  406. camera_update_controls(device, new_control_properties, settings);
  407. obs_properties_add_group(props, "controls", obs_module_text("CameraControls"), OBS_GROUP_NORMAL,
  408. new_control_properties);
  409. obs_property_modified(property, settings);
  410. return true;
  411. }
  412. static int sort_resolutions(gconstpointer a, gconstpointer b)
  413. {
  414. const struct spa_rectangle *resolution_a = a;
  415. const struct spa_rectangle *resolution_b = b;
  416. int64_t area_a = resolution_a->width * resolution_a->height;
  417. int64_t area_b = resolution_b->width * resolution_b->height;
  418. return area_a - area_b;
  419. }
  420. static void resolution_list(struct camera_device *dev, uint32_t pixelformat, obs_property_t *prop)
  421. {
  422. struct spa_rectangle last_resolution = SPA_RECTANGLE(0, 0);
  423. g_autoptr(GArray) resolutions = NULL;
  424. struct param *p;
  425. obs_data_t *data;
  426. resolutions = g_array_new(FALSE, FALSE, sizeof(struct spa_rectangle));
  427. spa_list_for_each(p, &dev->param_list, link)
  428. {
  429. struct obs_pw_video_format obs_pw_video_format;
  430. struct spa_rectangle resolution;
  431. uint32_t media_type, media_subtype, format;
  432. if (p->id != SPA_PARAM_EnumFormat || p->param == NULL)
  433. continue;
  434. if (spa_format_parse(p->param, &media_type, &media_subtype) < 0)
  435. continue;
  436. if (media_type != SPA_MEDIA_TYPE_video)
  437. continue;
  438. if (media_subtype == SPA_MEDIA_SUBTYPE_raw) {
  439. if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_format,
  440. SPA_POD_Id(&format)) < 0)
  441. continue;
  442. } else {
  443. format = SPA_VIDEO_FORMAT_ENCODED;
  444. }
  445. if (!obs_pw_video_format_from_spa_format(format, &obs_pw_video_format))
  446. continue;
  447. if (obs_pw_video_format.video_format != pixelformat)
  448. continue;
  449. if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_size,
  450. SPA_POD_OPT_Rectangle(&resolution)) < 0)
  451. continue;
  452. if (resolution.width == last_resolution.width && resolution.height == last_resolution.height)
  453. continue;
  454. last_resolution = resolution;
  455. g_array_append_val(resolutions, resolution);
  456. }
  457. g_array_sort(resolutions, sort_resolutions);
  458. obs_property_list_clear(prop);
  459. data = obs_data_create();
  460. for (size_t i = 0; i < resolutions->len; i++) {
  461. const struct spa_rectangle *resolution = &g_array_index(resolutions, struct spa_rectangle, i);
  462. struct dstr str = {};
  463. dstr_printf(&str, "%ux%u", resolution->width, resolution->height);
  464. obs_data_set_int(data, "width", resolution->width);
  465. obs_data_set_int(data, "height", resolution->height);
  466. obs_property_list_add_string(prop, str.array, obs_data_get_json(data));
  467. dstr_free(&str);
  468. }
  469. obs_data_release(data);
  470. }
  471. /*
  472. * Format selected callback
  473. */
  474. static bool format_selected(void *data, obs_properties_t *properties, obs_property_t *property, obs_data_t *settings)
  475. {
  476. UNUSED_PARAMETER(property);
  477. UNUSED_PARAMETER(settings);
  478. struct camera_portal_source *camera_source = data;
  479. struct camera_device *device;
  480. obs_property_t *resolution;
  481. blog(LOG_INFO, "[camera-portal] Selected format for '%s'", camera_source->device_id);
  482. device = g_hash_table_lookup(connection->devices, camera_source->device_id);
  483. if (device == NULL)
  484. return false;
  485. resolution = obs_properties_get(properties, "resolution");
  486. resolution_list(device, obs_data_get_int(settings, "pixelformat"), resolution);
  487. return true;
  488. }
  489. static int compare_framerates(gconstpointer a, gconstpointer b)
  490. {
  491. const struct spa_fraction *framerate_a = a;
  492. const struct spa_fraction *framerate_b = b;
  493. double da = framerate_a->num / (double)framerate_a->denom;
  494. double db = framerate_b->num / (double)framerate_b->denom;
  495. return da - db;
  496. }
  497. static void framerate_list(struct camera_device *dev, uint32_t pixelformat, const struct spa_rectangle *resolution,
  498. obs_property_t *prop)
  499. {
  500. g_autoptr(GArray) framerates = NULL;
  501. struct param *p;
  502. obs_data_t *data;
  503. framerates = g_array_new(FALSE, FALSE, sizeof(struct spa_fraction));
  504. spa_list_for_each(p, &dev->param_list, link)
  505. {
  506. const struct spa_fraction *framerate_values;
  507. struct obs_pw_video_format obs_pw_video_format;
  508. enum spa_choice_type choice;
  509. const struct spa_pod_prop *prop;
  510. struct spa_rectangle this_resolution;
  511. struct spa_pod *framerate_pod;
  512. uint32_t media_subtype;
  513. uint32_t media_type;
  514. uint32_t n_framerates;
  515. uint32_t format;
  516. if (p->id != SPA_PARAM_EnumFormat || p->param == NULL)
  517. continue;
  518. if (spa_format_parse(p->param, &media_type, &media_subtype) < 0)
  519. continue;
  520. if (media_type != SPA_MEDIA_TYPE_video)
  521. continue;
  522. if (media_subtype == SPA_MEDIA_SUBTYPE_raw) {
  523. if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_format,
  524. SPA_POD_Id(&format)) < 0)
  525. continue;
  526. } else {
  527. format = SPA_VIDEO_FORMAT_ENCODED;
  528. }
  529. if (!obs_pw_video_format_from_spa_format(format, &obs_pw_video_format))
  530. continue;
  531. if (obs_pw_video_format.video_format != pixelformat)
  532. continue;
  533. if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_size,
  534. SPA_POD_OPT_Rectangle(&this_resolution)) < 0)
  535. continue;
  536. if (this_resolution.width != resolution->width || this_resolution.height != resolution->height)
  537. continue;
  538. prop = spa_pod_find_prop(p->param, NULL, SPA_FORMAT_VIDEO_framerate);
  539. if (!prop)
  540. continue;
  541. framerate_pod = spa_pod_get_values(&prop->value, &n_framerates, &choice);
  542. if (framerate_pod->type != SPA_TYPE_Fraction) {
  543. blog(LOG_WARNING, "Framerate is not a fraction - something is wrong");
  544. continue;
  545. }
  546. framerate_values = SPA_POD_BODY(framerate_pod);
  547. switch (choice) {
  548. case SPA_CHOICE_None:
  549. g_array_append_val(framerates, framerate_values[0]);
  550. break;
  551. case SPA_CHOICE_Range:
  552. blog(LOG_WARNING, "Ranged framerates not supported");
  553. break;
  554. case SPA_CHOICE_Step:
  555. blog(LOG_WARNING, "Stepped framerates not supported");
  556. break;
  557. case SPA_CHOICE_Enum:
  558. /* i=0 is the default framerate, skip it */
  559. for (uint32_t i = 1; i < n_framerates; i++)
  560. g_array_append_val(framerates, framerate_values[i]);
  561. break;
  562. default:
  563. break;
  564. }
  565. }
  566. g_array_sort(framerates, compare_framerates);
  567. obs_property_list_clear(prop);
  568. data = obs_data_create();
  569. for (size_t i = 0; i < framerates->len; i++) {
  570. const struct spa_fraction *framerate = &g_array_index(framerates, struct spa_fraction, i);
  571. struct media_frames_per_second fps;
  572. struct dstr str = {};
  573. fps = (struct media_frames_per_second){
  574. .numerator = framerate->num,
  575. .denominator = framerate->denom,
  576. };
  577. obs_data_set_frames_per_second(data, "framerate", fps, NULL);
  578. dstr_printf(&str, "%.2f", framerate->num / (double)framerate->denom);
  579. obs_property_list_add_string(prop, str.array, obs_data_get_json(data));
  580. dstr_free(&str);
  581. }
  582. obs_data_release(data);
  583. }
  584. static bool parse_framerate(struct spa_fraction *dest, const char *json)
  585. {
  586. struct media_frames_per_second fps;
  587. obs_data_t *data = obs_data_create_from_json(json);
  588. if (!data)
  589. return false;
  590. if (!obs_data_get_frames_per_second(data, "framerate", &fps, NULL)) {
  591. obs_data_release(data);
  592. return false;
  593. }
  594. dest->num = fps.numerator;
  595. dest->denom = fps.denominator;
  596. obs_data_release(data);
  597. return true;
  598. }
  599. static bool framerate_selected(void *data, obs_properties_t *properties, obs_property_t *property, obs_data_t *settings)
  600. {
  601. UNUSED_PARAMETER(properties);
  602. UNUSED_PARAMETER(property);
  603. struct camera_portal_source *camera_source = data;
  604. struct camera_device *device;
  605. struct spa_fraction framerate;
  606. device = g_hash_table_lookup(connection->devices, camera_source->device_id);
  607. if (device == NULL)
  608. return false;
  609. if (!parse_framerate(&framerate, obs_data_get_string(settings, "framerate")))
  610. return false;
  611. if (camera_source->obs_pw_stream)
  612. obs_pipewire_stream_set_framerate(camera_source->obs_pw_stream, &framerate);
  613. return true;
  614. }
  615. /*
  616. * Resolution selected callback
  617. */
  618. static bool parse_resolution(struct spa_rectangle *dest, const char *json)
  619. {
  620. obs_data_t *data = obs_data_create_from_json(json);
  621. if (!data)
  622. return false;
  623. dest->width = obs_data_get_int(data, "width");
  624. dest->height = obs_data_get_int(data, "height");
  625. obs_data_release(data);
  626. return true;
  627. }
  628. static bool resolution_selected(void *data, obs_properties_t *properties, obs_property_t *property,
  629. obs_data_t *settings)
  630. {
  631. UNUSED_PARAMETER(properties);
  632. UNUSED_PARAMETER(property);
  633. UNUSED_PARAMETER(settings);
  634. struct camera_portal_source *camera_source = data;
  635. struct spa_rectangle resolution;
  636. struct camera_device *device;
  637. blog(LOG_INFO, "[camera-portal] Selected resolution for '%s'", camera_source->device_id);
  638. device = g_hash_table_lookup(connection->devices, camera_source->device_id);
  639. if (device == NULL)
  640. return false;
  641. if (!parse_resolution(&resolution, obs_data_get_string(settings, "resolution")))
  642. return false;
  643. if (camera_source->obs_pw_stream)
  644. obs_pipewire_stream_set_resolution(camera_source->obs_pw_stream, &resolution);
  645. property = obs_properties_get(properties, "framerate");
  646. framerate_list(device, obs_data_get_int(settings, "pixelformat"), &resolution, property);
  647. return true;
  648. }
  649. static void populate_cameras_list(struct camera_portal_source *camera_source, obs_property_t *device_list)
  650. {
  651. struct camera_device *device;
  652. GHashTableIter iter;
  653. const char *device_id;
  654. bool device_found;
  655. if (!connection)
  656. return;
  657. obs_property_list_clear(device_list);
  658. device_found = false;
  659. g_hash_table_iter_init(&iter, connection->devices);
  660. while (g_hash_table_iter_next(&iter, (gpointer *)&device_id, (gpointer *)&device)) {
  661. const char *device_name;
  662. device_name = pw_properties_get(device->properties, PW_KEY_NODE_DESCRIPTION);
  663. obs_property_list_add_string(device_list, device_name, device_id);
  664. device_found |= strcmp(device_id, camera_source->device_id) == 0;
  665. }
  666. if (!device_found && camera_source->device_id) {
  667. size_t device_index;
  668. device_index =
  669. obs_property_list_add_string(device_list, camera_source->device_id, camera_source->device_id);
  670. obs_property_list_item_disable(device_list, device_index, true);
  671. }
  672. }
  673. /* ------------------------------------------------- */
  674. static void node_info(void *data, const struct pw_node_info *info)
  675. {
  676. struct camera_device *device = data;
  677. uint32_t i, changed = 0;
  678. int res;
  679. info = device->info = pw_node_info_update(device->info, info);
  680. if (info == NULL)
  681. return;
  682. if (info->change_mask & PW_NODE_CHANGE_MASK_PARAMS) {
  683. for (i = 0; i < info->n_params; i++) {
  684. uint32_t id = info->params[i].id;
  685. if (info->params[i].user == 0)
  686. continue;
  687. info->params[i].user = 0;
  688. changed++;
  689. add_param(&device->pending_list, 0, id, NULL);
  690. if (!(info->params[i].flags & SPA_PARAM_INFO_READ))
  691. continue;
  692. res = pw_node_enum_params((struct pw_node *)device->proxy, ++info->params[i].seq, id, 0, -1,
  693. NULL);
  694. if (SPA_RESULT_IS_ASYNC(res))
  695. info->params[i].seq = res;
  696. }
  697. }
  698. if (changed) {
  699. device->changed += changed;
  700. device->pending_sync = pw_proxy_sync(device->proxy, device->pending_sync);
  701. }
  702. }
  703. static void node_param(void *data, int seq, uint32_t id, uint32_t index, uint32_t next, const struct spa_pod *param)
  704. {
  705. UNUSED_PARAMETER(index);
  706. UNUSED_PARAMETER(next);
  707. struct camera_device *device = data;
  708. add_param(&device->pending_list, seq, id, param);
  709. }
  710. static const struct pw_node_events node_events = {
  711. PW_VERSION_NODE_EVENTS,
  712. .info = node_info,
  713. .param = node_param,
  714. };
  715. static void on_proxy_removed_cb(void *data)
  716. {
  717. struct camera_device *device = data;
  718. pw_proxy_destroy(device->proxy);
  719. }
  720. static void on_destroy_proxy_cb(void *data)
  721. {
  722. struct camera_device *device = data;
  723. spa_hook_remove(&device->proxy_listener);
  724. device->proxy = NULL;
  725. }
  726. static void on_done_proxy_cb(void *data, int seq)
  727. {
  728. struct camera_device *device = data;
  729. if (device->info != NULL && device->pending_sync == seq) {
  730. object_update_params(&device->param_list, &device->pending_list, device->info->n_params,
  731. device->info->params);
  732. }
  733. }
  734. static const struct pw_proxy_events proxy_events = {
  735. PW_VERSION_PROXY_EVENTS,
  736. .removed = on_proxy_removed_cb,
  737. .destroy = on_destroy_proxy_cb,
  738. .done = on_done_proxy_cb,
  739. };
  740. static void on_registry_global_cb(void *user_data, uint32_t id, uint32_t permissions, const char *type,
  741. uint32_t version, const struct spa_dict *props)
  742. {
  743. UNUSED_PARAMETER(user_data);
  744. UNUSED_PARAMETER(permissions);
  745. UNUSED_PARAMETER(version);
  746. struct camera_device *device;
  747. struct pw_registry *registry;
  748. const char *device_id;
  749. if (strcmp(type, PW_TYPE_INTERFACE_Node) != 0)
  750. return;
  751. registry = obs_pipewire_get_registry(connection->obs_pw);
  752. device_id = spa_dict_lookup(props, SPA_KEY_NODE_NAME);
  753. blog(LOG_INFO, "[camera-portal] Found device %s", device_id);
  754. device = camera_device_new(id, props);
  755. device->proxy = pw_registry_bind(registry, id, type, version, 0);
  756. if (!device->proxy) {
  757. blog(LOG_WARNING, "[camera-portal] Failed to bind device %s", device_id);
  758. bfree(device);
  759. return;
  760. }
  761. pw_proxy_add_listener(device->proxy, &device->proxy_listener, &proxy_events, device);
  762. device->node = (struct pw_node *)device->proxy;
  763. pw_node_add_listener(device->node, &device->node_listener, &node_events, device);
  764. g_hash_table_insert(connection->devices, bstrdup(device_id), device);
  765. for (size_t i = 0; i < connection->sources->len; i++) {
  766. struct camera_portal_source *camera_source = g_ptr_array_index(connection->sources, i);
  767. obs_source_update_properties(camera_source->source);
  768. if (strcmp(camera_source->device_id, device_id) == 0)
  769. stream_camera(camera_source);
  770. }
  771. }
  772. static void on_registry_global_remove_cb(void *user_data, uint32_t id)
  773. {
  774. UNUSED_PARAMETER(user_data);
  775. struct camera_device *device;
  776. const char *device_id;
  777. GHashTableIter iter;
  778. g_hash_table_iter_init(&iter, connection->devices);
  779. while (g_hash_table_iter_next(&iter, (gpointer *)&device_id, (gpointer *)&device)) {
  780. if (device->id != id)
  781. continue;
  782. g_hash_table_iter_remove(&iter);
  783. blog(LOG_INFO, "[pipewire-camera] Removed device %s", device_id);
  784. }
  785. for (size_t i = 0; i < connection->sources->len; i++) {
  786. struct camera_portal_source *camera_source = g_ptr_array_index(connection->sources, i);
  787. obs_source_update_properties(camera_source->source);
  788. }
  789. }
  790. static const struct pw_registry_events registry_events = {
  791. PW_VERSION_REGISTRY_EVENTS,
  792. .global = on_registry_global_cb,
  793. .global_remove = on_registry_global_remove_cb,
  794. };
  795. /* ------------------------------------------------- */
  796. static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, void *user_data)
  797. {
  798. UNUSED_PARAMETER(user_data);
  799. g_autoptr(GUnixFDList) fd_list = NULL;
  800. g_autoptr(GVariant) result = NULL;
  801. g_autoptr(GError) error = NULL;
  802. int pipewire_fd;
  803. int fd_index;
  804. result = g_dbus_proxy_call_with_unix_fd_list_finish(G_DBUS_PROXY(source), &fd_list, res, &error);
  805. if (error) {
  806. if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
  807. blog(LOG_ERROR, "[camera-portal] Error retrieving PipeWire fd: %s", error->message);
  808. return;
  809. }
  810. g_variant_get(result, "(h)", &fd_index, &error);
  811. pipewire_fd = g_unix_fd_list_get(fd_list, fd_index, &error);
  812. if (error) {
  813. if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
  814. blog(LOG_ERROR, "[camera-portal] Error retrieving PipeWire fd: %s", error->message);
  815. return;
  816. }
  817. connection->obs_pw = obs_pipewire_connect_fd(pipewire_fd, &registry_events, connection);
  818. obs_pipewire_roundtrip(connection->obs_pw);
  819. }
  820. static void open_pipewire_remote(void)
  821. {
  822. GVariantBuilder builder;
  823. g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
  824. g_dbus_proxy_call_with_unix_fd_list(get_camera_portal_proxy(), "OpenPipeWireRemote",
  825. g_variant_new("(a{sv})", &builder), G_DBUS_CALL_FLAGS_NONE, -1, NULL,
  826. connection->cancellable, on_pipewire_remote_opened_cb, NULL);
  827. }
  828. /* ------------------------------------------------- */
  829. static void on_access_camera_response_received_cb(GVariant *parameters, void *user_data)
  830. {
  831. UNUSED_PARAMETER(user_data);
  832. g_autoptr(GVariant) result = NULL;
  833. uint32_t response;
  834. g_variant_get(parameters, "(u@a{sv})", &response, &result);
  835. if (response != 0) {
  836. blog(LOG_WARNING, "[camera-portal] Failed to create session, denied or cancelled by user");
  837. return;
  838. }
  839. blog(LOG_INFO, "[camera-portal] Successfully accessed cameras");
  840. open_pipewire_remote();
  841. }
  842. static void on_access_camera_finished_cb(GObject *source, GAsyncResult *res, void *user_data)
  843. {
  844. UNUSED_PARAMETER(user_data);
  845. g_autoptr(GVariant) result = NULL;
  846. g_autoptr(GError) error = NULL;
  847. result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
  848. if (error) {
  849. if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
  850. blog(LOG_ERROR, "[camera-portal] Error accessing camera: %s", error->message);
  851. return;
  852. }
  853. }
  854. static void access_camera(struct camera_portal_source *camera_source)
  855. {
  856. GVariantBuilder builder;
  857. char *request_token;
  858. char *request_path;
  859. if (connection && connection->obs_pw) {
  860. stream_camera(camera_source);
  861. return;
  862. }
  863. if (!connection) {
  864. connection = bzalloc(sizeof(struct pw_portal_connection));
  865. connection->devices =
  866. g_hash_table_new_full(g_str_hash, g_str_equal, bfree, (GDestroyNotify)camera_device_free);
  867. connection->cancellable = g_cancellable_new();
  868. connection->sources = g_ptr_array_new();
  869. connection->initializing = false;
  870. }
  871. g_ptr_array_add(connection->sources, camera_source);
  872. if (connection->initializing)
  873. return;
  874. portal_create_request_path(&request_path, &request_token);
  875. portal_signal_subscribe(request_path, NULL, on_access_camera_response_received_cb, NULL);
  876. g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
  877. g_variant_builder_add(&builder, "{sv}", "handle_token", g_variant_new_string(request_token));
  878. g_dbus_proxy_call(get_camera_portal_proxy(), "AccessCamera", g_variant_new("(a{sv})", &builder),
  879. G_DBUS_CALL_FLAGS_NONE, -1, connection->cancellable, on_access_camera_finished_cb, NULL);
  880. connection->initializing = true;
  881. bfree(request_token);
  882. bfree(request_path);
  883. }
  884. /* obs_source_info methods */
  885. static const char *pipewire_camera_get_name(void *data)
  886. {
  887. UNUSED_PARAMETER(data);
  888. return obs_module_text("PipeWireCamera");
  889. }
  890. static void *pipewire_camera_create(obs_data_t *settings, obs_source_t *source)
  891. {
  892. struct camera_portal_source *camera_source;
  893. camera_source = bzalloc(sizeof(struct camera_portal_source));
  894. camera_source->source = source;
  895. camera_source->device_id = bstrdup(obs_data_get_string(settings, "device_id"));
  896. camera_source->framerate.set =
  897. parse_framerate(&camera_source->framerate.fraction, obs_data_get_string(settings, "framerate"));
  898. camera_source->resolution.set =
  899. parse_resolution(&camera_source->resolution.rect, obs_data_get_string(settings, "resolution"));
  900. access_camera(camera_source);
  901. return camera_source;
  902. }
  903. static void pipewire_camera_destroy(void *data)
  904. {
  905. struct camera_portal_source *camera_source = data;
  906. if (connection)
  907. g_ptr_array_remove(connection->sources, camera_source);
  908. g_clear_pointer(&camera_source->obs_pw_stream, obs_pipewire_stream_destroy);
  909. g_clear_pointer(&camera_source->device_id, bfree);
  910. bfree(camera_source);
  911. }
  912. static void pipewire_camera_get_defaults(obs_data_t *settings)
  913. {
  914. obs_data_set_default_string(settings, "device_id", NULL);
  915. }
  916. static obs_properties_t *pipewire_camera_get_properties(void *data)
  917. {
  918. struct camera_portal_source *camera_source = data;
  919. obs_properties_t *controls_props;
  920. obs_properties_t *props;
  921. obs_property_t *resolution_list;
  922. obs_property_t *framerate_list;
  923. obs_property_t *device_list;
  924. obs_property_t *format_list;
  925. props = obs_properties_create();
  926. device_list = obs_properties_add_list(props, "device_id", obs_module_text("PipeWireCameraDevice"),
  927. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  928. format_list = obs_properties_add_list(props, "pixelformat", obs_module_text("VideoFormat"), OBS_COMBO_TYPE_LIST,
  929. OBS_COMBO_FORMAT_INT);
  930. resolution_list = obs_properties_add_list(props, "resolution", obs_module_text("Resolution"),
  931. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  932. framerate_list = obs_properties_add_list(props, "framerate", obs_module_text("FrameRate"), OBS_COMBO_TYPE_LIST,
  933. OBS_COMBO_FORMAT_STRING);
  934. // a group to contain the camera control
  935. controls_props = obs_properties_create();
  936. obs_properties_add_group(props, "controls", obs_module_text("CameraControls"), OBS_GROUP_NORMAL,
  937. controls_props);
  938. populate_cameras_list(camera_source, device_list);
  939. obs_property_set_modified_callback2(device_list, device_selected, camera_source);
  940. obs_property_set_modified_callback2(format_list, format_selected, camera_source);
  941. obs_property_set_modified_callback2(resolution_list, resolution_selected, camera_source);
  942. obs_property_set_modified_callback2(framerate_list, framerate_selected, camera_source);
  943. return props;
  944. }
  945. static void pipewire_camera_update(void *data, obs_data_t *settings)
  946. {
  947. struct camera_portal_source *camera_source = data;
  948. const char *device_id;
  949. device_id = obs_data_get_string(settings, "device_id");
  950. blog(LOG_INFO, "[camera-portal] Updating device %s", device_id);
  951. if (update_device_id(camera_source, device_id))
  952. stream_camera(camera_source);
  953. }
  954. static void pipewire_camera_show(void *data)
  955. {
  956. struct camera_portal_source *camera_source = data;
  957. if (camera_source->obs_pw_stream)
  958. obs_pipewire_stream_show(camera_source->obs_pw_stream);
  959. }
  960. static void pipewire_camera_hide(void *data)
  961. {
  962. struct camera_portal_source *camera_source = data;
  963. if (camera_source->obs_pw_stream)
  964. obs_pipewire_stream_hide(camera_source->obs_pw_stream);
  965. }
  966. static uint32_t pipewire_camera_get_width(void *data)
  967. {
  968. struct camera_portal_source *camera_source = data;
  969. if (camera_source->obs_pw_stream)
  970. return obs_pipewire_stream_get_width(camera_source->obs_pw_stream);
  971. else
  972. return 0;
  973. }
  974. static uint32_t pipewire_camera_get_height(void *data)
  975. {
  976. struct camera_portal_source *camera_source = data;
  977. if (camera_source->obs_pw_stream)
  978. return obs_pipewire_stream_get_height(camera_source->obs_pw_stream);
  979. else
  980. return 0;
  981. }
  982. void camera_portal_load(void)
  983. {
  984. const struct obs_source_info pipewire_camera_info = {
  985. .id = "pipewire-camera-source",
  986. .type = OBS_SOURCE_TYPE_INPUT,
  987. .output_flags = OBS_SOURCE_ASYNC_VIDEO,
  988. .get_name = pipewire_camera_get_name,
  989. .create = pipewire_camera_create,
  990. .destroy = pipewire_camera_destroy,
  991. .get_defaults = pipewire_camera_get_defaults,
  992. .get_properties = pipewire_camera_get_properties,
  993. .update = pipewire_camera_update,
  994. .show = pipewire_camera_show,
  995. .hide = pipewire_camera_hide,
  996. .get_width = pipewire_camera_get_width,
  997. .get_height = pipewire_camera_get_height,
  998. .icon_type = OBS_ICON_TYPE_CAMERA,
  999. };
  1000. obs_register_source(&pipewire_camera_info);
  1001. }
  1002. void camera_portal_unload(void)
  1003. {
  1004. g_clear_pointer(&connection, pw_portal_connection_free);
  1005. }