pipewire/context/
mod.rs

1// Copyright The pipewire-rs Contributors.
2// SPDX-License-Identifier: MIT
3
4use std::{
5    os::fd::{IntoRawFd, OwnedFd},
6    ptr,
7};
8
9use crate::{
10    core::CoreBox,
11    properties::{Properties, PropertiesBox},
12    Error,
13};
14
15mod box_;
16pub use box_::*;
17mod rc;
18pub use rc::*;
19
20#[repr(transparent)]
21pub struct Context(pw_sys::pw_context);
22
23impl Context {
24    pub fn as_raw(&self) -> &pw_sys::pw_context {
25        &self.0
26    }
27
28    pub fn as_raw_ptr(&self) -> *mut pw_sys::pw_context {
29        std::ptr::addr_of!(self.0).cast_mut()
30    }
31
32    pub fn properties(&self) -> &Properties {
33        unsafe {
34            let props = pw_sys::pw_context_get_properties(self.as_raw_ptr());
35            let props = ptr::NonNull::new(props.cast_mut()).expect("context properties is NULL");
36            props.cast().as_ref()
37        }
38    }
39
40    pub fn update_properties(&self, properties: &spa::utils::dict::DictRef) {
41        unsafe {
42            pw_sys::pw_context_update_properties(self.as_raw_ptr(), properties.as_raw_ptr());
43        }
44    }
45
46    pub fn connect(&self, properties: Option<PropertiesBox>) -> Result<CoreBox<'_>, Error> {
47        let properties = properties.map_or(ptr::null_mut(), |p| p.into_raw());
48
49        unsafe {
50            let core = pw_sys::pw_context_connect(self.as_raw_ptr(), properties, 0);
51            let ptr = ptr::NonNull::new(core).ok_or(Error::CreationFailed)?;
52
53            Ok(CoreBox::from_raw(ptr))
54        }
55    }
56
57    pub fn connect_fd(
58        &self,
59        fd: OwnedFd,
60        properties: Option<PropertiesBox>,
61    ) -> Result<CoreBox<'_>, Error> {
62        let properties = properties.map_or(ptr::null_mut(), |p| p.into_raw());
63
64        unsafe {
65            let raw_fd = fd.into_raw_fd();
66            let core = pw_sys::pw_context_connect_fd(self.as_raw_ptr(), raw_fd, properties, 0);
67            let ptr = ptr::NonNull::new(core).ok_or(Error::CreationFailed)?;
68
69            Ok(CoreBox::from_raw(ptr))
70        }
71    }
72}