Debian Codegraph @

src/desktop/camera.rs

raw
1 //! Check if a camera is available, request access to it and open a PipeWire
2 //! remote stream.
3 //!
4 //! ### Examples
5 //!
6 //! ```rust,no_run
7 //! use ashpd::desktop::camera::Camera;
8 //!
9 //! pub async fn run() -> ashpd::Result<()> {
10 //! let camera = Camera::new().await?;
11 //! if camera.is_present().await? {
12 //! camera.request_access(Default::default()).await?;
13 //! let remote_fd = camera.open_pipe_wire_remote(Default::default()).await?;
14 //! // pass the remote fd to GStreamer for example
15 //! }
16 //! Ok(())
17 //! }
18 //! ```
19 //! An example on how to connect with Pipewire can be found [here](https://github.com/bilelmoussaoui/ashpd/blob/main/examples/screen_cast_pw.rs), and with GStreamer [here](https://github.com/bilelmoussaoui/ashpd/blob/main/examples/screen_cast_gstreamer.rs).
20 //! Although the examples are primary focus is screen casting, stream connection
21 //! logic remains the same -- with one accessibility change:
22 //! ```rust,ignore
23 //! let stream = pw::stream::Stream::new(
24 //! &core,
25 //! "video-test",
26 //! properties! {
27 //! *pw::keys::MEDIA_TYPE => "Video",
28 //! *pw::keys::MEDIA_CATEGORY => "Capture",
29 //! *pw::keys::MEDIA_ROLE => "Screen", // <-- make this 'Camera'
30 //! },
31 //! )?;
32 //! ```
33
34 #[cfg(feature = "pipewire")]
35 use std::collections::HashMap;
36 use std::os::fd::OwnedFd;
37
38 use serde::Serialize;
39 use zbus::zvariant::{self, Type, as_value};
40
41 use super::{HandleToken, Request};
42 use crate::{Error, proxy::Proxy};
43
44 #[derive(Serialize, Type, Debug, Default)]
45 #[zvariant(signature = "dict")]
46 /// Specified options for a [`Camera::request_access`] request.
47 pub struct CameraAccessOptions {
48 #[serde(with = "as_value")]
49 handle_token: HandleToken,
50 }
51
52 #[derive(Serialize, Type, Debug, Default)]
53 #[zvariant(signature = "dict")]
54 /// Specified options for a [`Camera::open_pipe_wire_remote`] request.
55 pub struct OpenPipeWireRemoteOptions {}
56
57 /// The interface lets sandboxed applications access camera devices, such as web
58 /// cams.
59 ///
60 /// Wrapper of the DBus interface: [`org.freedesktop.portal.Camera`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Camera.html).
61 #[derive(Debug)]
62 #[doc(alias = "org.freedesktop.portal.Camera")]
63 pub struct Camera(Proxy<'static>);
64
65 impl Camera {
66 /// Create a new instance of [`Camera`].
67 pub async fn new() -> Result<Camera, Error> {
68 let proxy = Proxy::new_desktop("org.freedesktop.portal.Camera").await?;
69 Ok(Self(proxy))
70 }
71
72 /// Create a new instance of [`Camera`].
73 pub async fn with_connection(connection: zbus::Connection) -> Result<Camera, Error> {
74 let proxy =
75 Proxy::new_desktop_with_connection(connection, "org.freedesktop.portal.Camera").await?;
76 Ok(Self(proxy))
77 }
78
79 /// Returns the version of the portal interface.
80 pub fn version(&self) -> u32 {
81 self.0.version()
82 }
83
84 /// Requests an access to the camera.
85 ///
86 /// # Specifications
87 ///
88 /// See also [`AccessCamera`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Camera.html#org-freedesktop-portal-camera-accesscamera).
89 #[doc(alias = "AccessCamera")]
90 #[doc(alias = "xdp_portal_access_camera")]
91 pub async fn request_access(&self, options: CameraAccessOptions) -> Result<Request<()>, Error> {
92 self.0
93 .empty_request(&options.handle_token, "AccessCamera", &options)
94 .await
95 }
96
97 /// Open a file descriptor to the PipeWire remote where the camera nodes are
98 /// available.
99 ///
100 /// # Returns
101 ///
102 /// File descriptor of an open PipeWire remote.
103 ///
104 /// # Specifications
105 ///
106 /// See also [`OpenPipeWireRemote`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Camera.html#org-freedesktop-portal-camera-openpipewireremote).
107 #[doc(alias = "OpenPipeWireRemote")]
108 #[doc(alias = "xdp_portal_open_pipewire_remote_for_camera")]
109 pub async fn open_pipe_wire_remote(
110 &self,
111 options: OpenPipeWireRemoteOptions,
112 ) -> Result<OwnedFd, Error> {
113 let fd = self
114 .0
115 .call::<zvariant::OwnedFd>("OpenPipeWireRemote", &options)
116 .await?;
117 Ok(fd.into())
118 }
119
120 /// A boolean stating whether there is any cameras available.
121 ///
122 /// # Specifications
123 ///
124 /// See also [`IsCameraPresent`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Camera.html#org-freedesktop-portal-camera-iscamerapresent).
125 #[doc(alias = "IsCameraPresent")]
126 #[doc(alias = "xdp_portal_is_camera_present")]
127 pub async fn is_present(&self) -> Result<bool, Error> {
128 self.0.property("IsCameraPresent").await
129 }
130 }
131
132 impl std::ops::Deref for Camera {
133 type Target = zbus::Proxy<'static>;
134
135 fn deref(&self) -> &Self::Target {
136 &self.0
137 }
138 }
139
140 #[cfg(feature = "pipewire")]
141 /// A PipeWire camera stream returned by [`pipewire_streams`].
142 #[derive(Debug)]
143 pub struct Stream {
144 node_id: u32,
145 properties: HashMap<String, String>,
146 }
147
148 #[cfg(feature = "pipewire")]
149 impl Stream {
150 /// The id of the PipeWire node.
151 pub fn node_id(&self) -> u32 {
152 self.node_id
153 }
154
155 /// The node properties.
156 pub fn properties(&self) -> HashMap<String, String> {
157 self.properties.clone()
158 }
159 }
160
161 #[cfg(feature = "pipewire")]
162 fn pipewire_streams_inner<F: Fn(Stream) + Clone + 'static, G: FnOnce() + Clone + 'static>(
163 fd: OwnedFd,
164 callback: F,
165 done_callback: G,
166 ) -> Result<(), pipewire::Error> {
167 let mainloop = pipewire::main_loop::MainLoopRc::new(None)?;
168 let context = pipewire::context::ContextRc::new(&mainloop, None)?;
169 let core = context.connect_fd(fd, None)?;
170 let registry = core.get_registry()?;
171
172 let pending = core.sync(0).expect("sync failed");
173
174 let loop_clone = mainloop.clone();
175 let _listener_reg = registry
176 .add_listener_local()
177 .global(move |global| {
178 if let Some(props) = &global.props
179 && props.get("media.role") == Some("Camera")
180 {
181 #[cfg(feature = "tracing")]
182 tracing::info!("found camera: {:#?}", props);
183
184 let mut properties = HashMap::new();
185 for (key, value) in props.iter() {
186 properties.insert(key.to_string(), value.to_string());
187 }
188 let node_id = global.id;
189
190 let stream = Stream {
191 node_id,
192 properties,
193 };
194 callback.clone()(stream);
195 }
196 })
197 .register();
198 let _listener_core = core
199 .add_listener_local()
200 .done(move |id, seq| {
201 if id == pipewire::core::PW_ID_CORE && seq == pending {
202 loop_clone.quit();
203 done_callback.clone()();
204 }
205 })
206 .register();
207
208 mainloop.run();
209
210 Ok(())
211 }
212
213 /// A helper to get a list of PipeWire streams to use with the camera file
214 /// descriptor returned by [`Camera::open_pipe_wire_remote`].
215 ///
216 /// Currently, the camera portal only gives us a file descriptor. Not passing a
217 /// node id may cause the media session controller to auto-connect the client to
218 /// an incorrect node.
219 ///
220 /// The method looks for the available output streams of a `media.role` type of
221 /// `Camera` and return a list of `Stream`s.
222 ///
223 /// *Note* The socket referenced by `fd` must not be used while this function is
224 /// running.
225 #[cfg(feature = "pipewire")]
226 #[cfg_attr(docsrs, doc(cfg(feature = "pipewire")))]
227 pub async fn pipewire_streams(fd: OwnedFd) -> Result<Vec<Stream>, pipewire::Error> {
228 let (sender, receiver) = futures_channel::oneshot::channel();
229 let (streams_sender, mut streams_receiver) = futures_channel::mpsc::unbounded();
230
231 let sender = std::sync::Arc::new(std::sync::Mutex::new(Some(sender)));
232 let streams_sender = std::sync::Arc::new(std::sync::Mutex::new(streams_sender));
233
234 std::thread::spawn(move || {
235 let inner_sender = sender.clone();
236
237 if let Err(err) = pipewire_streams_inner(
238 fd,
239 move |stream| {
240 let inner_streams_sender = streams_sender.clone();
241 if let Ok(mut sender) = inner_streams_sender.lock() {
242 let _result = sender.start_send(stream);
243 };
244 },
245 move || {
246 if let Ok(mut guard) = inner_sender.lock()
247 && let Some(inner_sender) = guard.take()
248 {
249 let _result = inner_sender.send(Ok(()));
250 }
251 },
252 ) {
253 #[cfg(feature = "tracing")]
254 tracing::error!("Failed to get pipewire streams {:#?}", err);
255 let mut guard = sender.lock().unwrap();
256 if let Some(sender) = guard.take() {
257 let _ = sender.send(Err(err));
258 }
259 }
260 });
261
262 receiver.await.unwrap()?;
263
264 let mut streams = vec![];
265 let mut seen_node_ids = std::collections::HashSet::new();
266 while let Ok(stream) = streams_receiver.try_recv() {
267 if seen_node_ids.insert(stream.node_id) {
268 streams.push(stream);
269 }
270 }
271
272 Ok(streams)
273 }
274
275 #[cfg(not(feature = "pipewire"))]
276 #[cfg_attr(docsrs, doc(cfg(not(feature = "pipewire"))))]
277 /// Request access to the camera and return a file descriptor if one is
278 /// available.
279 pub async fn request() -> Result<Option<OwnedFd>, Error> {
280 let proxy = Camera::new().await?;
281 proxy.request_access(Default::default()).await?;
282 if proxy.is_present().await? {
283 Ok(Some(proxy.open_pipe_wire_remote(Default::default()).await?))
284 } else {
285 Ok(None)
286 }
287 }
288
289 #[cfg(feature = "pipewire")]
290 #[cfg_attr(docsrs, doc(cfg(feature = "pipewire")))]
291 /// Request access to the camera and return a file descriptor and a list of the
292 /// available streams, one per camera.
293 pub async fn request() -> Result<Option<(OwnedFd, Vec<Stream>)>, Error> {
294 let proxy = Camera::new().await?;
295 proxy.request_access(Default::default()).await?;
296 if proxy.is_present().await? {
297 let fd = proxy.open_pipe_wire_remote(Default::default()).await?;
298 let streams = pipewire_streams(fd.try_clone()?).await?;
299 Ok(Some((fd, streams)))
300 } else {
301 Ok(None)
302 }
303 }