Skip to main content

libobs_wrapper\utils/
path.rs

1use std::{
2    env,
3    path::{Path, PathBuf},
4};
5
6use super::ObsString;
7
8/// Builds into an `ObsString` that represents a path used
9/// by libobs.
10///
11/// Note that only this path only supports UTF-8 for the
12/// entire absolute path because libobs only supports
13/// UTF-8.
14#[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
15pub struct ObsPath {
16    path: PathBuf,
17}
18
19impl ObsPath {
20    /// Creates a new `ObsPath` strictly using the path
21    /// `path_str` without any modifications.
22    ///
23    /// If you want to create a relative path, use
24    /// `ObsPath::from_relative`.
25    pub fn new(path_str: &str) -> Self {
26        Self {
27            path: Path::new(path_str).into(),
28        }
29    }
30
31    /// Creates a new `ObsPath` with `path_str`
32    /// appended to the directory the OBS runtime is expected in.
33    ///
34    /// This is the directory which the executable file is in. When the executable is a Cargo
35    /// test binary (which Cargo places in `target/<profile>/deps` or, since Cargo 1.100, in
36    /// `target/<profile>/build/<pkg>/<hash>/out`) and the runtime isn't next to it, the Cargo
37    /// profile directory (`target/<profile>`) is used instead if it contains the runtime.
38    ///
39    /// If you want to create an absolute path, use
40    /// `ObsPath::new`.
41    pub fn from_relative(path_str: &str) -> Self {
42        let obs_path = Self {
43            path: runtime_base_dir(),
44        };
45
46        let path_str = path_str.trim_matches('/');
47
48        obs_path.push(path_str)
49    }
50
51    /// Modifies the path to point to the path
52    /// `path_str` appended to the current path which
53    /// `ObsPath` is pointing to.
54    pub fn push(mut self, value: &str) -> Self {
55        let split = value.split(['/', '\\'].as_ref());
56
57        for item in split {
58            if !item.is_empty() {
59                self.path.push(item);
60            }
61        }
62
63        self
64    }
65
66    /// Modifies the path to point to its current
67    /// parent. This is analogous to `Obs::push(".")`.
68    pub fn pop(mut self) -> Self {
69        self.path.pop();
70        self
71    }
72
73    /// Consumes the `ObsPath` to create a new
74    /// immutable ObsString that encodes a UTF-8
75    /// C-type string which describes the path that
76    /// the `ObsPath` is pointing to.
77    ///
78    /// Note that this function is lossy in that
79    /// any non-Unicode data is completely removed
80    /// from the string. This is because libobs
81    /// does not support non-Unicode characters in
82    /// its path.
83    pub fn build(self) -> ObsString {
84        let mut bytes = self.path.display().to_string().replace("\\", "/");
85
86        if self.path.is_dir() {
87            bytes += "/";
88        }
89        let obs_string = ObsString::from(bytes.as_str());
90
91        drop(self);
92        obs_string
93    }
94}
95
96impl From<ObsPath> for ObsString {
97    fn from(val: ObsPath) -> Self {
98        val.build()
99    }
100}
101
102impl From<ObsPath> for PathBuf {
103    fn from(val: ObsPath) -> Self {
104        val.path
105    }
106}
107
108/// The directory containing the current executable.
109pub(crate) fn executable_dir() -> PathBuf {
110    match env::current_exe() {
111        Ok(mut path) => {
112            path.pop();
113            path
114        }
115        Err(err) => {
116            log::warn!("Could not resolve current executable for relative OBS path: {err}");
117            env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
118        }
119    }
120}
121
122/// If `exe_dir` is a directory Cargo places test binaries in, returns the Cargo profile
123/// directory (`target/<profile>`), which is where `cargo obs-build` installs the runtime.
124///
125/// Recognizes `target/<profile>/deps` (legacy layout) and
126/// `target/<profile>/build/<pkg>/<hash>/out` (Cargo's build-dir layout, default since 1.100).
127pub(crate) fn cargo_profile_dir(exe_dir: &Path) -> Option<PathBuf> {
128    let name = exe_dir.file_name()?;
129    if name == "deps" {
130        return exe_dir.parent().map(Path::to_path_buf);
131    }
132
133    if name != "out" {
134        return None;
135    }
136
137    let build_dir = exe_dir.parent()?.parent()?.parent()?;
138    if build_dir.file_name()? != "build" {
139        return None;
140    }
141
142    build_dir.parent().map(Path::to_path_buf)
143}
144
145/// The directory exe-relative OBS runtime paths are resolved against.
146pub(crate) fn runtime_base_dir() -> PathBuf {
147    resolve_runtime_base_dir(&executable_dir())
148}
149
150const RUNTIME_MARKER: &str = "data/libobs";
151
152pub(crate) fn resolve_runtime_base_dir(exe_dir: &Path) -> PathBuf {
153    if exe_dir.join(RUNTIME_MARKER).is_dir() {
154        return exe_dir.to_path_buf();
155    }
156
157    match cargo_profile_dir(exe_dir) {
158        Some(profile_dir) if profile_dir.join(RUNTIME_MARKER).is_dir() => profile_dir,
159        _ => exe_dir.to_path_buf(),
160    }
161}
162
163/// OBS spawns helper executables (e.g. `obs-ffmpeg-mux`) from the directory of the *current
164/// executable*. When the executable is a Cargo test binary that lives in its own hashed
165/// directory, link the helpers from the Cargo profile directory next to it.
166#[cfg(any(windows, target_os = "macos"))]
167pub(crate) fn provide_runtime_helpers_next_to_executable() {
168    #[cfg(windows)]
169    const HELPERS: &[&str] = &["obs-ffmpeg-mux.exe", "obs-nvenc-test.exe"];
170    #[cfg(target_os = "macos")]
171    const HELPERS: &[&str] = &["obs-ffmpeg-mux"];
172
173    let exe_dir = executable_dir();
174    let Some(profile_dir) = cargo_profile_dir(&exe_dir) else {
175        return;
176    };
177
178    for helper in HELPERS {
179        let destination = exe_dir.join(helper);
180        let source = profile_dir.join(helper);
181        if destination.exists() || !source.is_file() {
182            continue;
183        }
184
185        #[cfg(windows)]
186        let result = std::fs::hard_link(&source, &destination)
187            .or_else(|_| std::fs::copy(&source, &destination).map(|_| ()));
188        #[cfg(target_os = "macos")]
189        let result = std::os::unix::fs::symlink(&source, &destination);
190
191        match result {
192            Ok(()) => log::debug!(
193                "[libobs-wrapper]: Linked OBS helper '{}' next to the executable",
194                source.display()
195            ),
196            Err(error) => log::warn!(
197                "[libobs-wrapper]: Failed to provide OBS helper '{}' at '{}': {error}",
198                source.display(),
199                destination.display()
200            ),
201        }
202    }
203}