Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add macOS ONNX Runtime support and packaging
Richie McIlroycf2770c12eb5
diff --git a/.gitignore b/.gitignoreindex ae89dc865..04e4642ea 100644--- a/.gitignore+++ b/.gitignore@@ -46,6 +46,7 @@ apps/storybook/storybook-static*.tsbuildinfo.cargo/config.tomltauri.windows.conf.json+tauri.macos.conf.json.vercel# sst@@ -72,4 +73,4 @@ scripts/releases-backfill-data.txtanalysis/analysis/plans/.ralphy-tmp/\ No newline at end of file+tmp/diff --git a/Cargo.lock b/Cargo.lockindex 7074d9fcd..d755221d0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5149,6 +5149,16 @@ dependencies = ["windows-targets 0.53.3",]+[[package]]+name = "libloading"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60"+dependencies = [+ "cfg-if",+ "windows-link 0.2.0",+]+[[package]]name = "libm"version = "0.2.15"@@ -6676,6 +6686,7 @@ version = "2.0.0-rc.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d7de3af33d24a745ffb8fab904b13478438d1cd52868e6f17735ef6e1f8bf133"dependencies = [+ "libloading 0.9.0","ndarray 0.17.2","ort-sys","smallvec",diff --git a/apps/desktop/scripts/prepare.js b/apps/desktop/scripts/prepare.jsindex c1fb07ada..68a5ac887 100644--- a/apps/desktop/scripts/prepare.js+++ b/apps/desktop/scripts/prepare.js@@ -94,6 +94,19 @@ export async function createTauriPlatformConfigs(};}+ if (platform === "darwin") {+ configFileName = "tauri.macos.conf.json";+ baseConfig = {+ ...baseConfig,+ bundle: {+ resources: {+ "../../../target/native-deps/onnxruntime/lib/libonnxruntime.dylib":+ "onnxruntime/lib/libonnxruntime.dylib",+ },+ },+ };+ }+if (!configFileName) return;const mergedConfig = configOptionsdiff --git a/crates/camera-effects/Cargo.toml b/crates/camera-effects/Cargo.tomlindex ba3babfb0..c32c55a54 100644--- a/crates/camera-effects/Cargo.toml+++ b/crates/camera-effects/Cargo.toml@@ -12,10 +12,12 @@ wgpu.workspace = truetracing.workspace = truebytemuck = { version = "1.7", features = ["derive"] }ndarray = "0.16"++[target.'cfg(not(any(target_os = "macos", target_os = "windows")))'.dependencies]ort = { version = "2.0.0-rc.12", default-features = false, features = ["std", "ndarray", "download-binaries", "copy-dylibs", "tls-native"] }[target.'cfg(target_os = "macos")'.dependencies]-ort = { version = "2.0.0-rc.12", default-features = false, features = ["coreml"] }+ort = { version = "2.0.0-rc.12", default-features = false, features = ["std", "ndarray", "load-dynamic", "coreml", "api-23"] }[target.'cfg(target_os = "windows")'.dependencies]-ort = { version = "2.0.0-rc.12", default-features = false, features = ["directml"] }+ort = { version = "2.0.0-rc.12", default-features = false, features = ["std", "ndarray", "download-binaries", "copy-dylibs", "tls-native", "directml"] }diff --git a/crates/camera-effects/src/segmentation.rs b/crates/camera-effects/src/segmentation.rsindex 471fcc6c8..e2d56601f 100644--- a/crates/camera-effects/src/segmentation.rs+++ b/crates/camera-effects/src/segmentation.rs@@ -1,6 +1,8 @@use anyhow::Context;use ort::session::Session;use ort::value::Value;+#[cfg(target_os = "macos")]+use std::path::PathBuf;const MODEL_BYTES: &[u8] = include_bytes!("../assets/selfie_segmentation.onnx");const MODEL_INPUT_SIZE: usize = 256;@@ -48,6 +50,8 @@ impl SegmentationModel {}fn create_session() -> anyhow::Result<Session> {+ init_runtime()?;+let mut builder = Session::builder().context("Failed to create ONNX session builder")?;#[cfg(target_os = "macos")]@@ -81,6 +85,57 @@ fn create_session() -> anyhow::Result<Session> {Ok(session)}+#[cfg(target_os = "macos")]+fn init_runtime() -> anyhow::Result<()> {+ let path = std::env::var_os("ORT_DYLIB_PATH")+ .map(PathBuf::from)+ .or_else(|| {+ onnx_runtime_candidates()+ .into_iter()+ .find(|path| path.exists())+ })+ .context("Failed to find macOS ONNX Runtime dylib")?;++ let _ = ort::init_from(&path)+ .with_context(|| format!("Failed to load ONNX Runtime from {}", path.display()))?+ .commit();++ Ok(())+}++#[cfg(not(target_os = "macos"))]+fn init_runtime() -> anyhow::Result<()> {+ Ok(())+}++#[cfg(target_os = "macos")]+fn onnx_runtime_candidates() -> Vec<PathBuf> {+ let mut candidates = Vec::new();++ if let Ok(exe) = std::env::current_exe()+ && let Some(exe_dir) = exe.parent()+ {+ candidates.push(exe_dir.join("libonnxruntime.dylib"));++ if let Some(contents_dir) = exe_dir.parent() {+ candidates.push(+ contents_dir+ .join("Resources")+ .join("onnxruntime")+ .join("lib")+ .join("libonnxruntime.dylib"),+ );+ }+ }++ candidates.push(+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("../../target/native-deps/onnxruntime/lib/libonnxruntime.dylib"),+ );++ candidates+}+#[cfg(target_os = "macos")]fn try_register_coreml(builder: ort::session::builder::SessionBuilder,diff --git a/scripts/setup.js b/scripts/setup.jsindex c72e0f14c..b67333846 100644--- a/scripts/setup.js+++ b/scripts/setup.js@@ -28,10 +28,11 @@ async function main() {await fs.mkdir(targetDir, { recursive: true });let cargoConfigContents = BASE_CARGO_TOML;+ let cargoBuildContents = "";const sccachePath = await findExecutable("sccache");if (sccachePath) {- cargoConfigContents += `\n[build]\nrustc-wrapper = "${sccachePath.replaceAll("\\", "/")}"\n`;+ cargoBuildContents += `\n[build]\nrustc-wrapper = "${sccachePath.replaceAll("\\", "/")}"\n`;console.log(`Using sccache at ${sccachePath}`);} else console.log("sccache not found, using rustc directly");@@ -106,6 +107,12 @@ async function main() {}console.log("Copied ffmpeg dylibs to target/debug");} else console.log("Using cached macOS native deps setup");++ const onnxRuntimePath = await setupMacOSOnnxRuntime();+ cargoConfigContents += `ORT_DYLIB_PATH = { relative = true, force = true, value = "${path.relative(+ __root,+ onnxRuntimePath,+ )}" }\n`;} else if (process.platform === "win32") {const FFMPEG_VERSION = "7.1";const FFMPEG_ZIP_NAME = `ffmpeg-${FFMPEG_VERSION}-full_build-shared`;@@ -188,7 +195,7 @@ async function main() {await fs.mkdir(path.join(__root, ".cargo"), { recursive: true });await fs.writeFile(path.join(__root, ".cargo/config.toml"),- cargoConfigContents,+ cargoConfigContents + cargoBuildContents,);}@@ -261,6 +268,60 @@ async function signMacOSFrameworkLibs(frameworkDir) {);}+async function setupMacOSOnnxRuntime() {+ const asset =+ arch === "aarch64"+ ? {+ version: "1.24.2",+ name: "onnxruntime-osx-arm64-1.24.2.tgz",+ }+ : {+ version: "1.23.2",+ name: "onnxruntime-osx-x86_64-1.23.2.tgz",+ };+ const url = `https://github.com/microsoft/onnxruntime/releases/download/v${asset.version}/${asset.name}`;+ const archivePath = path.join(targetDir, asset.name);+ const extractDir = path.join(targetDir, asset.name.replace(/\.tgz$/, ""));+ const outputDir = path.join(targetDir, "native-deps", "onnxruntime", "lib");+ const outputPath = path.join(outputDir, "libonnxruntime.dylib");+ const markerPath = path.join(outputDir, "asset.txt");+ const marker = await fs+ .readFile(markerPath, "utf-8")+ .then((value) => value.trim())+ .catch(() => null);++ if (!(await fileExists(archivePath))) {+ console.log(`Downloading ${asset.name}`);+ const bytes = await fetch(url)+ .then((r) => r.blob())+ .then((b) => b.arrayBuffer());+ await fs.writeFile(archivePath, Buffer.from(bytes));+ console.log(`Downloaded ${asset.name}`);+ } else console.log(`Using cached ${asset.name}`);++ if (!(await fileExists(outputPath)) || marker !== asset.name) {+ await fs.rm(extractDir, { recursive: true, force: true }).catch(() => {});+ await execFile("tar", ["xf", archivePath, "-C", targetDir]);+ await fs.mkdir(outputDir, { recursive: true });+ await fs.copyFile(+ path.join(extractDir, "lib", "libonnxruntime.dylib"),+ outputPath,+ );+ await signMacOSDylib(outputPath);+ await fs.writeFile(markerPath, asset.name);+ console.log("Prepared ONNX Runtime dylib");+ } else console.log("Using cached ONNX Runtime dylib");++ return outputPath;+}++async function signMacOSDylib(filePath) {+ const signId = env.APPLE_SIGNING_IDENTITY || "-";+ const keychain = env.APPLE_KEYCHAIN ? `--keychain ${env.APPLE_KEYCHAIN}` : "";++ await exec(`codesign ${keychain} -s "${signId}" -f "${filePath}"`);+}+async function fileExists(path) {return await fs.access(path)