Skip to content

AI media harness for planning, generating, and editing locally

TypeScript
49.6 KB
Raw Blame
use libloading::Library;
use std::{
    ffi::{c_char, c_void, CStr, CString},
    path::Path,
    ptr,
};

pub enum Request {}
mod device;
mod lcs;
mod reference_video;
pub use device::{cuda_device_names, gpu_devices, has_cuda_device};
pub use reference_video::ReferenceVideoHandle;
pub enum Generation {}
#[repr(C)]
pub struct Preview {
    pub rgb: *const u8,
    pub byte_count: usize,
    pub frames: i32,
    pub width: i32,
    pub height: i32,
    pub step: i32,
    pub fps: f64,
}
pub type PreviewFn = unsafe extern "C" fn(*const Preview, *mut c_void);
type SetPreview = unsafe extern "C" fn(*mut Request, *const c_char, Option<PreviewFn>, *mut c_void) -> i32;
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VideoDecodeTimings {
    pub seconds_prepare: f64,
    pub seconds_upscale: f64,
    pub seconds_model_open: f64,
    pub seconds_weight_load: f64,
    pub seconds_compute: f64,
    pub seconds_cleanup: f64,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Plan {
    pub canvas_width: i32,
    pub canvas_height: i32,
    pub aligned_frames: i32,
    pub duration_seconds: f64,
    pub num_model_evaluations: i32,
    pub sequence_rows_without_text: i32,
    pub latent_frames: i32,
    pub latent_height: i32,
    pub latent_width: i32,
    pub num_video_rows: i32,
    pub num_audio_rows: i32,
    pub num_audio_latents: i32,
}
#[repr(C)]
pub struct Progress {
    pub stage: i32,
    pub step: i32,
    pub total_steps: i32,
    pub elapsed_seconds: f64,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Output {
    pub video: *const f32,
    pub video_float_count: usize,
    pub channels: i32,
    pub frames: i32,
    pub width: i32,
    pub height: i32,
    pub audio: *const f32,
    pub audio_float_count: usize,
    pub audio_channels: i32,
    pub audio_sample_rate: i32,
    pub audio_frames: i64,
    pub fps: f64,
    pub seconds_conditioning: f64,
    pub seconds_denoise: f64,
    pub seconds_video_decode: f64,
    pub seconds_audio_decode: f64,
    pub seconds_total: f64,
    pub steps_computed: i32,
    pub steps_skipped: i32,
}
type AddReferenceAudio = unsafe extern "C" fn(*mut Request, *const f32, usize, i32, i32) -> i32;
pub type ProgressFn = Option<unsafe extern "C" fn(*const Progress, *mut c_void)>;
type SetMotionCache =
    unsafe extern "C" fn(*mut Request, i32, f32, f32, i32, i32, f32, f32, i32, i32) -> i32;
type SetImageEditPath = unsafe extern "C" fn(*mut Request, *const c_char, i32, i32, i32, i32, f32, i32) -> i32;
type SetImageEditRgb = unsafe extern "C" fn(*mut Request, *const u8, usize, i32, i32, usize, i32, i32, i32, i32, f32, i32) -> i32;
type ExportRefmod = unsafe extern "C" fn(*const Request, *const c_char, *const c_char, *const c_char, i32) -> i32;
type UpscaleDecode = unsafe extern "C" fn(*const c_char, *const c_char, f32, *const c_char, *const c_char, i32, ProgressFn, *mut c_void, *mut *mut Generation) -> i32;

type SetImageGuidance = unsafe extern "C" fn(*mut Request, f32, *const c_char, *const i32, i32) -> i32;

pub struct Api {
    set_preview: Option<SetPreview>,
    upscale_decode: Option<UpscaleDecode>,
    save_generation_latents: Option<unsafe extern "C" fn(*const Generation, *const c_char) -> i32>,
    set_music_settings: Option<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>,
    set_vulkan_arithmetic: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,
    set_image_guidance: Option<SetImageGuidance>,
    _library: Library,
    capi_version: unsafe extern "C" fn() -> u32,
    version_string: unsafe extern "C" fn() -> *const c_char,
    last_error: unsafe extern "C" fn() -> *const c_char,
    free_string: unsafe extern "C" fn(*mut c_char),
    cuda_set_version: unsafe extern "C" fn(*const c_char) -> i32,
    cuda_loaded_major: unsafe extern "C" fn(*mut i32) -> i32,
    request_create: unsafe extern "C" fn() -> *mut Request,
    request_destroy: unsafe extern "C" fn(*mut Request),
    set_prompt: unsafe extern "C" fn(*mut Request, *const c_char) -> i32,
    set_animate: Option<unsafe extern "C" fn(*mut Request, i32, i32) -> i32>,
    set_prompt_embedding: Option<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>,
    set_resolution: unsafe extern "C" fn(*mut Request, i32, i32) -> i32,
    set_frames: unsafe extern "C" fn(*mut Request, i32) -> i32,
    set_still_image: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,
    set_image_edit_mask: Option<unsafe extern "C" fn(*mut Request, *const u8, usize, i32, i32, usize) -> i32>,
    set_image_edit_path: Option<SetImageEditPath>,
    set_image_edit_rgb: Option<SetImageEditRgb>,
    set_image_edit_invert_mask: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,
    set_outpaint_blend_overlap: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,
    set_outpaint_langevin_steps: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,
    set_save_latents: Option<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>,
    set_continuation_file: Option<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>,
    set_end_anchor_file: Option<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>,
    set_keystone_file: Option<unsafe extern "C" fn(*mut Request, *const c_char, i32, i32) -> i32>,
    set_continuation_source_init: Option<unsafe extern "C" fn(*mut Request, i32, f32) -> i32>,
    set_latent_bridge_files: Option<unsafe extern "C" fn(*mut Request, *const c_char, *const c_char, i32, i32, i32) -> i32>,
    set_continuation_lock_overlap: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,
    set_continuation_regenerate_frames: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,
    set_video_transition: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,
    set_steps: unsafe extern "C" fn(*mut Request, i32) -> i32,
    set_audio_steps: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,
    set_latent_upscaler: Option<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> i32>,
    set_sampling_settings: Option<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>,
    set_seed: unsafe extern "C" fn(*mut Request, u64) -> i32,
    set_model: unsafe extern "C" fn(*mut Request, i32, *const c_char) -> i32,
    set_model_family: Option<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>,
    add_lora: Option<unsafe extern "C" fn(*mut Request, *const c_char, f32) -> i32>,
    prepare_lora_grid: Option<unsafe extern "C" fn(*const c_char, i32, i32) -> i32>,
    add_refmod: Option<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> i32>,
    export_refmod: Option<ExportRefmod>,
    add_reference: unsafe extern "C" fn(*mut Request, *const c_char) -> i32,
    add_reference_audio: Option<AddReferenceAudio>,
    set_attention: unsafe extern "C" fn(*mut Request, *const c_char) -> i32,
    set_motion_cache: Option<SetMotionCache>,
    set_inference_backend: unsafe extern "C" fn(*mut Request, i32) -> i32,
    set_verbose: unsafe extern "C" fn(*mut Request, i32) -> i32,
    set_reuse_models: unsafe extern "C" fn(*mut Request, i32) -> i32,
    reused_models_clear: unsafe extern "C" fn() -> i32,
    resolve_plan: unsafe extern "C" fn(*const Request, *mut Plan) -> i32,
    describe_plan: unsafe extern "C" fn(*const Request, *mut *mut c_char) -> i32,
    generation_start:
        unsafe extern "C" fn(*const Request, ProgressFn, *mut c_void, *mut *mut Generation) -> i32,
    generation_cancel: unsafe extern "C" fn(*mut Generation),
    generation_wait: unsafe extern "C" fn(*mut Generation, i32) -> i32,
    generation_error: unsafe extern "C" fn(*const Generation) -> *const c_char,
    generation_output: unsafe extern "C" fn(*const Generation, *mut Output) -> i32,
    generation_video_decode_timings: Option<unsafe extern "C" fn(*const Generation, *mut VideoDecodeTimings) -> i32>,
    generation_frame_rgba8: unsafe extern "C" fn(*const Generation, i32, *mut u8, usize) -> i32,
    generation_release_samples: Option<unsafe extern "C" fn(*mut Generation) -> i32>,
    generation_destroy: unsafe extern "C" fn(*mut Generation),
}

impl Api {
    pub fn set_preview(&self, request: *mut Request, path: &Path, callback: PreviewFn, userdata: *mut c_void) -> Result<(), String> {
        let Some(set) = self.set_preview else { return Ok(()); };
        self.error(unsafe { set(request, path_cstring(path)?.as_ptr(), Some(callback), userdata) })
    }
    pub fn load(path: &Path) -> Result<Self, String> {
        // SAFETY: symbols are copied function pointers with signatures from capi.h.
        // The Library is retained in Api, so no pointer outlives the loaded module.
        unsafe {
            let library = load_library(path)
                .map_err(|error| format!("could not load {}: {error}", path.display()))?;
            macro_rules! symbol {
                ($name:literal, $ty:ty) => {
                    *library
                        .get::<$ty>(concat!($name, "\0").as_bytes())
                        .map_err(|error| format!("missing {}: {error}", $name))?
                };
            }
            Ok(Self {
                set_preview: library.get::<SetPreview>(b"slopfab_request_set_preview\0").ok().map(|f| *f),
                set_video_transition: library
                    .get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(
                        b"slopfab_request_set_video_transition\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                capi_version: symbol!("slopfab_capi_version", unsafe extern "C" fn() -> u32),
                version_string: symbol!(
                    "slopfab_capi_version_string",
                    unsafe extern "C" fn() -> *const c_char
                ),
                last_error: symbol!(
                    "slopfab_last_error",
                    unsafe extern "C" fn() -> *const c_char
                ),
                free_string: symbol!("slopfab_free_string", unsafe extern "C" fn(*mut c_char)),
                cuda_set_version: symbol!(
                    "slopfab_cuda_set_version",
                    unsafe extern "C" fn(*const c_char) -> i32
                ),
                cuda_loaded_major: symbol!(
                    "slopfab_cuda_loaded_major",
                    unsafe extern "C" fn(*mut i32) -> i32
                ),
                request_create: symbol!(
                    "slopfab_request_create",
                    unsafe extern "C" fn() -> *mut Request
                ),
                prepare_lora_grid: library
                    .get::<unsafe extern "C" fn(*const c_char, i32, i32) -> i32>(
                        b"slopfab_prepare_lora_grid\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                request_destroy: symbol!(
                    "slopfab_request_destroy",
                    unsafe extern "C" fn(*mut Request)
                ),
                set_prompt: symbol!(
                    "slopfab_request_set_prompt",
                    unsafe extern "C" fn(*mut Request, *const c_char) -> i32
                ),
                set_animate: library
                    .get::<unsafe extern "C" fn(*mut Request, i32, i32) -> i32>(
                        b"slopfab_request_set_animate\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                set_prompt_embedding: library
                    .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(
                        b"slopfab_request_set_prompt_embedding_path\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                set_resolution: symbol!(
                    "slopfab_request_set_resolution",
                    unsafe extern "C" fn(*mut Request, i32, i32) -> i32
                ),
                set_frames: symbol!(
                    "slopfab_request_set_frames",
                    unsafe extern "C" fn(*mut Request, i32) -> i32
                ),
                set_still_image: library
                    .get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(
                        b"slopfab_request_set_still_image\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                set_image_edit_mask: library.get::<unsafe extern "C" fn(*mut Request, *const u8, usize, i32, i32, usize) -> i32>(b"slopfab_request_set_image_edit_mask_u8\0").ok().map(|symbol| *symbol),
                set_image_edit_path: library.get::<SetImageEditPath>(b"slopfab_request_set_image_edit_path\0").ok().map(|symbol| *symbol),
                set_image_edit_rgb: library.get::<SetImageEditRgb>(b"slopfab_request_set_image_edit_rgb24\0").ok().map(|symbol| *symbol),
                set_image_edit_invert_mask: library.get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_image_edit_invert_mask\0").ok().map(|symbol| *symbol),
                set_outpaint_blend_overlap: library.get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_outpaint_blend_overlap\0").ok().map(|symbol| *symbol),
                set_outpaint_langevin_steps: library.get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_outpaint_langevin_steps\0").ok().map(|symbol| *symbol),
                set_steps: symbol!(
                    "slopfab_request_set_steps",
                    unsafe extern "C" fn(*mut Request, i32) -> i32
                ),
                set_latent_upscaler: library
                    .get::<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> i32>(b"slopfab_request_set_latent_upscaler\0")
                    .ok().map(|symbol| *symbol),
                set_audio_steps: library
                    .get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_audio_steps\0")
                    .ok().map(|symbol| *symbol),
                set_sampling_settings: library
                    .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(b"slopfab_request_set_sampling_settings\0")
                    .ok().map(|symbol| *symbol),
                set_seed: symbol!(
                    "slopfab_request_set_seed",
                    unsafe extern "C" fn(*mut Request, u64) -> i32
                ),
                set_image_guidance: library.get::<SetImageGuidance>(b"slopfab_request_set_image_guidance\0").ok().map(|symbol| *symbol),
                set_music_settings: library.get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(b"slopfab_request_set_music_settings\0").ok().map(|symbol| *symbol),
                set_vulkan_arithmetic: library.get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_vulkan_arithmetic\0").ok().map(|symbol| *symbol),
                set_model_family: library
                    .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(b"slopfab_request_set_model_family\0")
                    .ok().map(|symbol| *symbol),
                set_model: symbol!(
                    "slopfab_request_set_model_path",
                    unsafe extern "C" fn(*mut Request, i32, *const c_char) -> i32
                ),
                add_reference: symbol!(
                    "slopfab_request_add_reference_image",
                    unsafe extern "C" fn(*mut Request, *const c_char) -> i32
                ),
                add_lora: library
                    .get::<unsafe extern "C" fn(*mut Request, *const c_char, f32) -> i32>(
                        b"slopfab_request_add_lora\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                set_save_latents: library
                    .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(
                        b"slopfab_request_set_save_latents\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                set_latent_bridge_files: library.get::<unsafe extern "C" fn(*mut Request, *const c_char, *const c_char, i32, i32, i32) -> i32>(b"slopfab_request_set_latent_bridge_files\0").ok().map(|symbol| *symbol),
                set_continuation_file: library
                    .get::<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>(
                        b"slopfab_request_set_continuation_file\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                set_end_anchor_file: library.get::<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>(b"slopfab_request_set_end_anchor_file\0").ok().map(|symbol| *symbol),
                set_keystone_file: library.get::<unsafe extern "C" fn(*mut Request, *const c_char, i32, i32) -> i32>(b"slopfab_request_set_keystone_file\0").ok().map(|symbol| *symbol),
                set_continuation_source_init: library.get::<unsafe extern "C" fn(*mut Request, i32, f32) -> i32>(b"slopfab_request_set_continuation_source_init\0").ok().map(|symbol| *symbol),
                set_continuation_lock_overlap: library
                    .get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_continuation_lock_overlap\0")
                    .ok().map(|symbol| *symbol),
                set_continuation_regenerate_frames: library
                    .get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_continuation_regenerate_frames\0")
                    .ok().map(|symbol| *symbol),
                add_refmod: library
                    .get::<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> i32>(
                        b"slopfab_request_add_refmod\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                export_refmod: library.get::<ExportRefmod>(b"slopfab_export_refmod\0").ok().map(|symbol| *symbol),
                add_reference_audio: library
                    .get::<AddReferenceAudio>(b"slopfab_request_add_reference_audio_f32\0")
                    .ok()
                    .map(|symbol| *symbol),
                set_attention: symbol!(
                    "slopfab_request_set_attention",
                    unsafe extern "C" fn(*mut Request, *const c_char) -> i32
                ),
                set_motion_cache: library
                    .get::<SetMotionCache>(b"slopfab_request_set_motion_cache\0")
                    .ok()
                    .map(|symbol| *symbol),
                set_inference_backend: symbol!(
                    "slopfab_request_set_inference_backend",
                    unsafe extern "C" fn(*mut Request, i32) -> i32
                ),
                set_verbose: symbol!(
                    "slopfab_request_set_verbose",
                    unsafe extern "C" fn(*mut Request, i32) -> i32
                ),
                set_reuse_models: symbol!(
                    "slopfab_request_set_reuse_models",
                    unsafe extern "C" fn(*mut Request, i32) -> i32
                ),
                reused_models_clear: symbol!(
                    "slopfab_reused_models_clear",
                    unsafe extern "C" fn() -> i32
                ),
                resolve_plan: symbol!(
                    "slopfab_resolve_plan",
                    unsafe extern "C" fn(*const Request, *mut Plan) -> i32
                ),
                describe_plan: symbol!(
                    "slopfab_describe_plan",
                    unsafe extern "C" fn(*const Request, *mut *mut c_char) -> i32
                ),
                upscale_decode: library.get::<UpscaleDecode>(b"slopfab_latent_upscale_decode_file_start\0").ok().map(|f| *f),
                save_generation_latents: library.get::<unsafe extern "C" fn(*const Generation, *const c_char) -> i32>(b"slopfab_generation_save_latents\0").ok().map(|f| *f),
                generation_start: symbol!(
                    "slopfab_generation_start",
                    unsafe extern "C" fn(
                        *const Request,
                        ProgressFn,
                        *mut c_void,
                        *mut *mut Generation,
                    ) -> i32
                ),
                generation_cancel: symbol!(
                    "slopfab_generation_cancel",
                    unsafe extern "C" fn(*mut Generation)
                ),
                generation_wait: symbol!(
                    "slopfab_generation_wait",
                    unsafe extern "C" fn(*mut Generation, i32) -> i32
                ),
                generation_error: symbol!(
                    "slopfab_generation_error",
                    unsafe extern "C" fn(*const Generation) -> *const c_char
                ),
                generation_video_decode_timings: library.get::<unsafe extern "C" fn(*const Generation, *mut VideoDecodeTimings) -> i32>(b"slopfab_generation_video_decode_timings\0").ok().map(|symbol| *symbol),
                generation_output: symbol!(
                    "slopfab_generation_output",
                    unsafe extern "C" fn(*const Generation, *mut Output) -> i32
                ),
                generation_frame_rgba8: symbol!(
                    "slopfab_generation_frame_rgba8",
                    unsafe extern "C" fn(*const Generation, i32, *mut u8, usize) -> i32
                ),
                generation_destroy: symbol!(
                    "slopfab_generation_destroy",
                    unsafe extern "C" fn(*mut Generation)
                ),
                generation_release_samples: library
                    .get::<unsafe extern "C" fn(*mut Generation) -> i32>(
                        b"slopfab_generation_release_samples\0",
                    )
                    .ok()
                    .map(|symbol| *symbol),
                _library: library,
            })
        }
    }
    pub fn version(&self) -> Result<String, String> {
        unsafe {
            let packed = (self.capi_version)();
            let major = packed >> 24;
            if major != crate::slopfab::EXPECTED_CAPI_MAJOR {
                return Err(format!(
                    "Incompatible slopfab C API major {major}; expected {}.",
                    crate::slopfab::EXPECTED_CAPI_MAJOR
                ));
            }
            Ok(c_string((self.version_string)()))
        }
    }
    pub fn set_dmad_sampling(&self, r: *mut Request) -> Result<(), String> {
        const UPGRADE: &str = "DMAD requires slopfab.dll API 1.16 or later. Update the runtime.";
        if unsafe { (self.capi_version)() } < ((1 << 24) | (16 << 12)) {
            return Err(UPGRADE.into());
        }
        let set = self.set_sampling_settings.ok_or(UPGRADE)?;
        // Released DMAD adapters do not embed slopfab.sampling metadata.
        let settings = CString::new(r#"{"version":1,"sampler":"renoise","video_sigma_shift":12,"audio_sigma_shift":2,"base_sigmas":[1,0.75,0.5,0.25,0]}"#).unwrap();
        self.error(unsafe { set(r, settings.as_ptr()) })
    }
    pub fn set_pika_sampling(&self, r: *mut Request) -> Result<(), String> {
        const UPGRADE: &str = "Pika H3 Flex requires slopfab.dll API 1.16 or later. Update the runtime.";
        if unsafe { (self.capi_version)() } < ((1 << 24) | (16 << 12)) {
            return Err(UPGRADE.into());
        }
        let set = self.set_sampling_settings.ok_or(UPGRADE)?;
        // https://github.com/Pika-Labs/Pika-H3-Flex#reproducibility
        let settings = CString::new(r#"{"version":1,"sampler":"renoise","video_sigma_shift":12,"audio_sigma_shift":3,"base_sigmas":[1,0.75,0.5,0.25,0.1,0.04,0]}"#).unwrap();
        self.error(unsafe { set(r, settings.as_ptr()) })
    }
    pub fn set_sampling(&self, r: *mut Request, video: Option<f32>, audio: Option<f32>, sampler: Option<&str>, scheduler: Option<&str>) -> Result<(), String> {
        let Some(set) = self.set_sampling_settings else {
            return if video.is_none() && audio.is_none() && sampler.is_none() && scheduler.is_none() { Ok(()) }
                else { Err("Sampling settings require a newer SlopFab runtime. Update the machine running generation.".into()) };
        };
        let mut settings = serde_json::json!({ "version": 1 });
        if let Some(sampler) = sampler { settings["sampler"] = serde_json::json!(sampler); }
        if let Some(scheduler) = scheduler { settings["scheduler"] = serde_json::json!(scheduler); }
        for (key, value) in [("video_sigma_shift", video), ("audio_sigma_shift", audio)] {
            if let Some(value) = value {
                if !value.is_finite() || value <= 0.0 { return Err("Sigma shifts must be finite and positive.".into()); }
                settings[key] = serde_json::json!(value);
            }
        }
        // Replaces the previous recipe, including clearing stale shifts on reused handles.
        let settings = CString::new(settings.to_string()).map_err(|error| error.to_string())?;
        self.error(unsafe { set(r, settings.as_ptr()) })
    }
    fn error(&self, code: i32) -> Result<(), String> {
        if code == 0 {
            Ok(())
        } else {
            let message = unsafe { c_string((self.last_error)()) };
            Err(if message.is_empty() {
                format!("slopfab returned status {code}.")
            } else {
                message
            })
        }
    }
    pub fn create_request(&self) -> Result<*mut Request, String> {
        let value = unsafe { (self.request_create)() };
        if value.is_null() {
            Err(unsafe { c_string((self.last_error)()) })
        } else {
            Ok(value)
        }
    }
    pub fn destroy_request(&self, request: *mut Request) {
        unsafe { (self.request_destroy)(request) }
    }
    pub fn set_cuda_version(&self, value: &str) -> Result<(), String> {
        let value =
            CString::new(value).map_err(|_| "CUDA version contains a null byte.".to_string())?;
        self.error(unsafe { (self.cuda_set_version)(value.as_ptr()) })
    }
    pub fn cuda_loaded_major(&self) -> Result<i32, String> {
        let mut major = 0;
        self.error(unsafe { (self.cuda_loaded_major)(&mut major) })?;
        Ok(major)
    }
    pub fn set_prompt(&self, r: *mut Request, v: &str) -> Result<(), String> {
        let v = CString::new(v).map_err(|_| "Prompt contains a null byte.".to_string())?;
        self.error(unsafe { (self.set_prompt)(r, v.as_ptr()) })
    }
    #[cfg(test)]
    pub fn disable_animate_for_test(&mut self) {
        self.set_animate = None;
    }
    pub fn set_animate(&self, r: *mut Request, preserve_audio: bool) -> Result<(), String> {
        let set = self
            .set_animate
            .ok_or("Animate requires slopfab.dll API 1.10 or later. Update the runtime.")?;
        self.error(unsafe { set(r, 1, preserve_audio as i32) })
    }
    pub fn set_prompt_embedding(&self, r: *mut Request, path: &Path) -> Result<(), String> {
        let set = self
            .set_prompt_embedding
            .ok_or("This slopfab.dll does not support frozen conditioning. Update the runtime.")?;
        let path = path_cstring(path)?;
        self.error(unsafe { set(r, path.as_ptr()) })
    }
    pub fn set_resolution(&self, r: *mut Request, w: i32, h: i32) -> Result<(), String> {
        self.error(unsafe { (self.set_resolution)(r, w, h) })
    }
    pub fn set_frames(&self, r: *mut Request, v: i32) -> Result<(), String> {
        self.error(unsafe { (self.set_frames)(r, v) })
    }
    pub fn set_still_image(&self, r: *mut Request) -> Result<(), String> {
        let set = self.set_still_image.ok_or("This slopfab.dll does not support still-image generation. Update the runtime to generate images and reference icons.")?;
        self.error(unsafe { set(r, 1) })
    }
    #[cfg(test)]
    pub fn disable_image_mask_for_test(&mut self) { self.set_image_edit_mask = None; }
    pub fn set_image_edit_mask(&self, r: *mut Request, mask: &[u8], width: i32, height: i32) -> Result<(), String> {
        let set = self.set_image_edit_mask.ok_or("Lasso editing requires SlopFab API 1.32 or later. Update the generation runtime.")?;
        if !(1..=8192).contains(&width) || !(1..=8192).contains(&height) || mask.len() != width as usize * height as usize {
            return Err("The image edit mask must match the source dimensions.".into());
        }
        self.error(unsafe { set(r, mask.as_ptr(), mask.len(), width, height, width as usize) })
    }
    pub fn set_image_edit_path(&self, r: *mut Request, path: &Path, bounds: [i32; 4], strength: f32, feather: i32) -> Result<(), String> {
        let set = self.set_image_edit_path.ok_or("This slopfab.dll does not support bounding-box image editing. Update the runtime.")?;
        let path = path_cstring(path)?;
        self.error(unsafe { set(r, path.as_ptr(), bounds[0], bounds[1], bounds[2], bounds[3], strength, feather) })
    }
    pub fn set_image_edit_rgb(&self, r: *mut Request, pixels: &[u8], width: i32, height: i32, bounds: [i32; 4], strength: f32, feather: i32) -> Result<(), String> {
        let set = self.set_image_edit_rgb.ok_or("This slopfab.dll does not support sequential image editing. Update the runtime.")?;
        if width <= 0 || height <= 0 || pixels.len() != width as usize * height as usize * 3 {
            return Err("Invalid image edit RGB buffer.".into());
        }
        self.error(unsafe { set(r, pixels.as_ptr(), pixels.len(), width, height, width as usize * 3, bounds[0], bounds[1], bounds[2], bounds[3], strength, feather) })
    }
    pub fn set_outpaint_blend_overlap(&self, r: *mut Request, value: i32) -> Result<(), String> {
        let set = self.set_outpaint_blend_overlap.ok_or("Zoom edge refinement requires SlopFab API 1.28 or later. Update the generation runtime.")?;
        self.error(unsafe { set(r, value) })
    }
    pub fn set_outpaint_langevin_steps(&self, r: *mut Request, value: i32) -> Result<(), String> {
        let set = self.set_outpaint_langevin_steps.ok_or("Zoom edge refinement requires SlopFab API 1.28 or later. Update the generation runtime.")?;
        self.error(unsafe { set(r, value) })
    }
    pub fn set_image_edit_invert_mask(&self, r: *mut Request) -> Result<(), String> {
        let set = self.set_image_edit_invert_mask.ok_or("Seamless Zoom requires SlopFab API 1.20 or later. Update the generation runtime.")?;
        self.error(unsafe { set(r, 1) })
    }
    pub fn set_save_latents(&self, r: *mut Request, path: &Path) -> Result<(), String> {
        let set = self.set_save_latents.ok_or(
            "Saving generation latents requires slopfab.dll API 1.9 or later. Update the runtime.",
        )?;
        let path = path_cstring(path)?;
        self.error(unsafe { set(r, path.as_ptr()) })
    }
    pub fn set_video_transition(&self, r: *mut Request, mode: i32) -> Result<(), String> {
        let set = self.set_video_transition.ok_or(
            "Extend and Bridge require slopfab.dll API 1.14 or later. Update the runtime.",
        )?;
        self.error(unsafe { set(r, mode) })
    }
    pub fn set_latent_bridge_files(&self, r: *mut Request, left: &Path, right: &Path, left_margin: i32, right_margin: i32, context: i32) -> Result<(), String> {
        let set = self.set_latent_bridge_files.ok_or("Long Shot requires SlopFab API 1.26 or later. Update the runtime.")?;
        let left = path_cstring(left)?;
        let right = path_cstring(right)?;
        self.error(unsafe { set(r, left.as_ptr(), right.as_ptr(), left_margin, right_margin, context) })
    }
    pub fn require_end_anchor(&self) -> Result<(), String> {
        self.set_end_anchor_file.map(|_| ()).ok_or("Single Shot requires SlopFab API 1.40 or newer. Update the app and workers.".into())
    }
    pub fn set_keystone_file(&self, r: *mut Request, path: &Path, lock_after: i32) -> Result<(), String> {
        let set = self.set_keystone_file.ok_or("Context video requires SlopFab API 1.45 or newer. Update the app and workers.")?;
        let path = CString::new(path.to_string_lossy().as_bytes()).map_err(|_| "Context video path contains a null byte.")?;
        self.error(unsafe { set(r, path.as_ptr(), 1, lock_after) })
    }
    pub fn require_continuation_source_init(&self) -> Result<(), String> {
        self.set_continuation_source_init.map(|_| ()).ok_or("Single Shot continuation requires SlopFab API 1.41 or newer. Update the app and workers.".into())
    }
    pub fn set_continuation_source_init(&self, r: *mut Request, noise: f32) -> Result<(), String> {
        self.require_continuation_source_init()?;
        self.error(unsafe { self.set_continuation_source_init.unwrap()(r, 1, noise) })
    }
    pub fn set_end_anchor_file(&self, r: *mut Request, path: &Path) -> Result<(), String> {
        self.require_end_anchor()?;
        let path = CString::new(path.to_string_lossy().as_bytes()).map_err(|_| "Ending path contains a null byte.")?;
        self.error(unsafe { self.set_end_anchor_file.unwrap()(r, path.as_ptr(), 22) })
    }
    pub fn set_continuation_file(
        &self,
        r: *mut Request,
        path: &Path,
        overlap: i32,
    ) -> Result<(), String> {
        let set = self.set_continuation_file.ok_or(
            "Scene continuation requires slopfab.dll API 1.9 or later. Update the runtime.",
        )?;
        let path = path_cstring(path)?;
        self.error(unsafe { set(r, path.as_ptr(), overlap) })
    }
    pub fn set_steps(&self, r: *mut Request, v: i32) -> Result<(), String> {
        self.error(unsafe { (self.set_steps)(r, v) })
    }
    pub fn set_latent_upscaler(&self, r: *mut Request, path: Option<&Path>) -> Result<(), String> {
        let Some(set) = self.set_latent_upscaler else {
            return if path.is_some() { Err("Latent upscale requires SlopFab API 1.24 or later. Update the generation runtime.".into()) } else { Ok(()) };
        };
        let path = path_cstring(path.unwrap_or_else(|| Path::new("")))?;
        self.error(unsafe { set(r, path.as_ptr(), 2.0, 1) })
    }
    #[cfg(test)]
    pub fn disable_latent_upscaler_for_test(&mut self) {
        self.set_latent_upscaler = None;
    }
    pub fn set_audio_steps(&self, r: *mut Request, steps: i32) -> Result<(), String> {
        let Some(set) = self.set_audio_steps else {
            return if steps == 0 { Ok(()) } else { Err("Separate audio steps require SlopFab API 1.21 or later. Update the generation runtime.".into()) };
        };
        self.error(unsafe { set(r, steps) })
    }
    pub fn set_seed(&self, r: *mut Request, v: u64) -> Result<(), String> {
        self.error(unsafe { (self.set_seed)(r, v) })
    }
    pub fn set_verbose(&self, r: *mut Request, v: bool) -> Result<(), String> {
        self.error(unsafe { (self.set_verbose)(r, v as i32) })
    }
    pub fn set_reuse_models(&self, r: *mut Request, v: bool) -> Result<(), String> {
        self.error(unsafe { (self.set_reuse_models)(r, v as i32) })
    }
    pub fn clear_reused_models(&self) -> Result<(), String> {
        self.error(unsafe { (self.reused_models_clear)() })
    }
    pub fn set_attention(&self, r: *mut Request, v: &str) -> Result<(), String> {
        let v = CString::new(v).map_err(|_| "Attention mode contains a null byte.".to_string())?;
        self.error(unsafe { (self.set_attention)(r, v.as_ptr()) })
    }
    pub fn set_motion_cache(&self, r: *mut Request, enabled: bool) -> Result<(), String> {
        let Some(set) = self.set_motion_cache else {
            return if enabled {
                Err("This slopfab.dll does not support MotionCache. Update the runtime or disable MotionCache in the generator template.".into())
            } else {
                Ok(())
            };
        };
        // Defaults from slopfab/capi.h; the UI exposes only the enable switch.
        self.error(unsafe { set(r, enabled as i32, 0.15, 1.0, 4, 2, 0.15, 0.95, 8, 0) })
    }
    #[cfg(test)]
    pub fn disable_motion_cache_for_test(&mut self) {
        self.set_motion_cache = None;
    }
    pub fn set_inference_backend(&self, r: *mut Request, backend: i32) -> Result<(), String> {
        self.error(unsafe { (self.set_inference_backend)(r, backend) })
    }
    pub fn set_model(&self, r: *mut Request, id: i32, path: &Path) -> Result<(), String> {
        let v = path_cstring(path)?;
        self.error(unsafe { (self.set_model)(r, id, v.as_ptr()) })
    }
    #[cfg(test)]
    pub fn disable_image_guidance_for_test(&mut self) { self.set_image_guidance = None; }
    pub fn set_image_guidance(&self, r: *mut Request, scale: f32, negative_prompt: &str, skip_layers: &[i32]) -> Result<(), String> {
        let set = self.set_image_guidance.ok_or("Configurable CFG requires SlopFab API 1.30 or newer. Update the runtime on the machine running generation.")?;
        // MOSS uses layer 22; Krea requires no unconditional layer skipping.
        let negative = CString::new(negative_prompt).map_err(|_| "Negative prompt cannot contain null characters.")?;
        let layers = if skip_layers.is_empty() { std::ptr::null() } else { skip_layers.as_ptr() };
        self.error(unsafe { set(r, scale, negative.as_ptr(), layers, skip_layers.len() as i32) })
    }
    pub fn set_music_settings(&self, r: *mut Request, settings: &str) -> Result<(), String> {
        let set = self.set_music_settings.ok_or("Music requires SlopFab API 1.38 or newer. Update the app and workers.")?;
        let json = CString::new(settings).map_err(|e| e.to_string())?;
        self.error(unsafe { set(r, json.as_ptr()) })
    }
    pub fn set_vulkan_portable(&self, r: *mut Request) -> Result<(), String> {
        let set = self.set_vulkan_arithmetic.ok_or("Portable Vulkan requires SlopFab API 1.38 or newer.")?;
        self.error(unsafe { set(r, 1) })
    }
    pub fn set_model_family(&self, r: *mut Request, family: &str) -> Result<(), String> {
        let set = self.set_model_family.ok_or("This model requires a newer SlopFab runtime. Update the machine running generation.")?;
        let value = CString::new(family).map_err(|_| "Invalid model family.")?;
        self.error(unsafe { set(r, value.as_ptr()) })
    }
    pub fn add_reference(&self, r: *mut Request, path: &Path) -> Result<(), String> {
        let v = path_cstring(path)?;
        self.error(unsafe { (self.add_reference)(r, v.as_ptr()) })
    }
    pub fn add_lora(&self, r: *mut Request, path: &Path, strength: f32) -> Result<(), String> {
        let add = self.add_lora.ok_or("This slopfab.dll does not support LoRAs. Update the DLL or disable the selected LoRAs.")?;
        let path = path_cstring(path)?;
        self.error(unsafe { add(r, path.as_ptr(), strength) })
    }
    pub fn prepare_lora_grid(
        &self,
        path: &Path,
        width: i32,
        allow_download: bool,
    ) -> Result<(), String> {
        let prepare = self.prepare_lora_grid.ok_or(
            "LoRA preparation requires slopfab.dll API 1.13 or later. Update the runtime.",
        )?;
        let path = path_cstring(path)?;
        self.error(unsafe { prepare(path.as_ptr(), width, allow_download as i32) })
    }
    #[cfg(test)]
    pub fn disable_outpainting_for_test(&mut self) {
        self.set_image_edit_invert_mask = None;
    }
    #[cfg(test)]
    pub fn disable_outpaint_refinement_for_test(&mut self) {
        self.set_outpaint_blend_overlap = None;
        self.set_outpaint_langevin_steps = None;
    }
    pub fn set_continuation_lock_overlap(&self, r: *mut Request, enabled: bool) -> Result<(), String> {
        let Some(set) = self.set_continuation_lock_overlap else {
            return if enabled { Err("Lock Overlap requires SlopFab API 1.23 or later. Update the generation runtime.".into()) } else { Ok(()) };
        };
        self.error(unsafe { set(r, i32::from(enabled)) })
    }
    pub fn set_continuation_regenerate_frames(&self, r: *mut Request, frames: i32) -> Result<(), String> {
        let set = self.set_continuation_regenerate_frames.ok_or("Single Shot overlap replacement requires SlopFab API 1.47 or newer. Update the app and workers.")?;
        self.error(unsafe { set(r, frames) })
    }
    #[cfg(test)]
    pub fn disable_lora_preparation_for_test(&mut self) {
        self.prepare_lora_grid = None;
    }
    pub fn add_refmod(
        &self,
        r: *mut Request,
        path: &Path,
        strength: f32,
        copies: i32,
    ) -> Result<(), String> {
        let add = self.add_refmod.ok_or("This slopfab.dll does not support refmods. Install a build with the refmod API (1.8 or later).")?;
        let path = path_cstring(path)?;
        self.error(unsafe { add(r, path.as_ptr(), strength, copies) })
    }
    pub fn export_refmod(&self, r: *mut Request, output: &Path, name: &str, description: &str) -> Result<(), String> {
        let export = self.export_refmod.ok_or("Refmod export requires slopfab.dll API 1.18 or later. Update the runtime.")?;
        let output = path_cstring(output)?;
        let name = CString::new(name).map_err(|_| "Refmod name contains a null byte.".to_string())?;
        let description = CString::new(description).map_err(|_| "Refmod description contains a null byte.".to_string())?;
        let description = if description.is_empty() { ptr::null() } else { description.as_ptr() };
        // short_edge 0 selects the runtime's native 768-pixel reference size.
        self.error(unsafe { export(r, output.as_ptr(), name.as_ptr(), description, 0) })
    }
    #[cfg(test)]
    pub fn disable_refmod_export_for_test(&mut self) {
        self.export_refmod = None;
    }
    pub fn add_reference_audio(
        &self,
        r: *mut Request,
        samples: &[f32],
        channels: i32,
        sample_rate: i32,
    ) -> Result<(), String> {
        let add = self.add_reference_audio.ok_or("This slopfab.dll does not support audio references. Update the runtime.")?;
        self.error(unsafe { add(r, samples.as_ptr(), samples.len(), channels, sample_rate) })
    }
    pub fn resolve(&self, request: *mut Request) -> Result<Plan, String> {
        let mut value = Plan {
            canvas_width: 0,
            canvas_height: 0,
            aligned_frames: 0,
            duration_seconds: 0.0,
            num_model_evaluations: 0,
            sequence_rows_without_text: 0,
            latent_frames: 0,
            latent_height: 0,
            latent_width: 0,
            num_video_rows: 0,
            num_audio_rows: 0,
            num_audio_latents: 0,
        };
        self.error(unsafe { (self.resolve_plan)(request, &mut value) })?;
        Ok(value)
    }
    pub fn describe(&self, request: *mut Request) -> Result<String, String> {
        let mut value = ptr::null_mut();
        self.error(unsafe { (self.describe_plan)(request, &mut value) })?;
        let text = unsafe { c_string(value) };
        unsafe { (self.free_string)(value) };
        Ok(text)
    }
    pub fn start(
        &self,
        request: *mut Request,
        callback: ProgressFn,
        userdata: *mut c_void,
    ) -> Result<*mut Generation, String> {
        let mut value = ptr::null_mut();
        self.error(unsafe { (self.generation_start)(request, callback, userdata, &mut value) })?;
        Ok(value)
    }
    pub fn require_saved_latent_upscale(&self) -> Result<(), String> {
        if self.upscale_decode.is_none() || self.save_generation_latents.is_none() {
            return Err("Update SlopFab to C API 1.43 or later for saved latent upscaling.".into());
        }
        Ok(())
    }
    pub fn upscale_decode(&self, source: &str, checkpoint: &Path, scale: f32, video: &Path, audio: &Path, backend: i32, callback: ProgressFn, userdata: *mut c_void) -> Result<*mut Generation, String> {
        self.require_saved_latent_upscale()?;
        let strings = [source.to_owned(), checkpoint.to_string_lossy().into_owned(), video.to_string_lossy().into_owned(), audio.to_string_lossy().into_owned()]
            .map(|s| CString::new(s).map_err(|_| "Model and latent paths cannot contain null characters.".to_owned()));
        let [source, checkpoint, video, audio] = strings;
        let (source, checkpoint, video, audio) = (source?, checkpoint?, video?, audio?);
        let mut value = ptr::null_mut();
        self.error(unsafe { self.upscale_decode.unwrap()(source.as_ptr(), checkpoint.as_ptr(), scale, video.as_ptr(), audio.as_ptr(), backend, callback, userdata, &mut value) })?;
        Ok(value)
    }
    pub fn save_generation_latents(&self, generation: *mut Generation, path: &Path) -> Result<(), String> {
        let save = self.save_generation_latents.ok_or("The runtime cannot save enlarged latents.")?;
        let path = CString::new(path.to_string_lossy().as_bytes()).map_err(|_| "Invalid latent output path.")?;
        self.error(unsafe { save(generation, path.as_ptr()) })
    }
    pub fn cancel(&self, generation: *mut Generation) {
        unsafe { (self.generation_cancel)(generation) }
    }
    pub fn wait(&self, generation: *mut Generation, timeout: i32) -> i32 {
        unsafe { (self.generation_wait)(generation, timeout) }
    }
    pub fn generation_error(&self, generation: *mut Generation) -> String {
        unsafe { c_string((self.generation_error)(generation)) }
    }
    pub fn video_decode_timings(&self, generation: *mut Generation) -> Result<Option<VideoDecodeTimings>, String> {
        let Some(get) = self.generation_video_decode_timings else { return Ok(None); };
        let mut value = VideoDecodeTimings::default();
        self.error(unsafe { get(generation, &mut value) })?;
        Ok(Some(value))
    }
    pub fn output(&self, generation: *mut Generation) -> Result<Output, String> {
        let mut value = Output {
            video: ptr::null(),
            video_float_count: 0,
            channels: 0,
            frames: 0,
            width: 0,
            height: 0,
            audio: ptr::null(),
            audio_float_count: 0,
            audio_channels: 0,
            audio_sample_rate: 0,
            audio_frames: 0,
            fps: 0.0,
            seconds_conditioning: 0.0,
            seconds_denoise: 0.0,
            seconds_video_decode: 0.0,
            seconds_audio_decode: 0.0,
            seconds_total: 0.0,
            steps_computed: 0,
            steps_skipped: 0,
        };
        self.error(unsafe { (self.generation_output)(generation, &mut value) })?;
        Ok(value)
    }
    pub fn frame_rgba8(
        &self,
        generation: *mut Generation,
        index: u32,
        width: u32,
        height: u32,
    ) -> Result<Vec<u8>, String> {
        let index = i32::try_from(index)
            .map_err(|_| "Frame index does not fit the slopfab API.".to_string())?;
        let bytes = (width as usize)
            .checked_mul(height as usize)
            .and_then(|value| value.checked_mul(4))
            .ok_or_else(|| "Frame dimensions do not fit in memory.".to_string())?;
        let mut rgba = vec![0_u8; bytes];
        self.error(unsafe {
            (self.generation_frame_rgba8)(generation, index, rgba.as_mut_ptr(), rgba.len())
        })?;
        Ok(rgba)
    }
    pub fn destroy_generation(&self, generation: *mut Generation) {
        // The owner has stopped the worker and excludes all sample readers.
        // API 1.25 releases the large decoded buffers explicitly. Destruction
        // remains unconditional: it also frees retained latents and request
        // inputs, and is the complete cleanup path for older runtimes.
        if let Some(release) = self.generation_release_samples {
            unsafe { release(generation); }
        }
        unsafe { (self.generation_destroy)(generation) }
    }
}

#[cfg(test)]
#[path = "lifecycle_tests.rs"]
mod lifecycle_tests;
fn path_cstring(path: &Path) -> Result<CString, String> {
    CString::new(path.to_string_lossy().as_bytes())
        .map_err(|_| "A slopfab path contains a null byte.".into())
}

#[cfg(windows)]
unsafe fn load_library(path: &Path) -> Result<Library, libloading::Error> {
    // LOAD_WITH_ALTERED_SEARCH_PATH makes Windows resolve the runtime's
    // dynamic dependencies relative to this absolute path instead of the host exe.
    const LOAD_WITH_ALTERED_SEARCH_PATH: u32 = 0x0000_0008;
    unsafe {
        libloading::os::windows::Library::load_with_flags(path, LOAD_WITH_ALTERED_SEARCH_PATH)
            .map(Into::into)
    }
}

#[cfg(not(windows))]
unsafe fn load_library(path: &Path) -> Result<Library, libloading::Error> {
    preload_cublas();
    unsafe { Library::new(path) }
}

/// The Linux runtime links CUDA 13 cuBLAS by soname, with a search path that
/// only matches the machine it was built on. When the system linker cannot
/// find it, load it once from the usual CUDA install folders; the runtime then
/// binds to the already loaded copy. A missing cuBLAS is reported by the
/// runtime load itself.
#[cfg(not(windows))]
fn preload_cublas() {
    use std::sync::Once;
    static ONCE: Once = Once::new();
    ONCE.call_once(|| {
        const SONAME: &str = "libcublas.so.13";
        let global = libloading::os::unix::RTLD_NOW | libloading::os::unix::RTLD_GLOBAL;
        let open = |name: &std::ffi::OsStr| unsafe { libloading::os::unix::Library::open(Some(name), global) };
        if open(SONAME.as_ref()).map(std::mem::forget).is_ok() {
            return;
        }
        for directory in cuda_library_directories() {
            let candidate = directory.join(SONAME);
            if candidate.is_file() && open(candidate.as_os_str()).map(std::mem::forget).is_ok() {
                return;
            }
        }
    });
}

#[cfg(not(windows))]
fn cuda_library_directories() -> Vec<std::path::PathBuf> {
    let mut roots: Vec<std::path::PathBuf> = ["CUDA_HOME", "CUDA_PATH"].iter()
        .filter_map(|name| std::env::var_os(name).map(Into::into)).collect();
    roots.push("/usr/local/cuda".into());
    // Versioned installs, newest first: /usr/local/cuda-13.3 before cuda-13.0.
    let mut versioned: Vec<_> = std::fs::read_dir("/usr/local").into_iter().flatten().flatten()
        .map(|entry| entry.path())
        .filter(|path| path.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.starts_with("cuda-13")))
        .collect();
    versioned.sort();
    roots.extend(versioned.into_iter().rev());
    let mut directories = Vec::new();
    for root in roots {
        directories.push(root.join("lib64"));
        directories.push(root.join("targets/x86_64-linux/lib"));
    }
    directories.extend(["/usr/lib/x86_64-linux-gnu", "/usr/lib64"].map(std::path::PathBuf::from));
    directories
}
unsafe fn c_string(value: *const c_char) -> String {
    if value.is_null() {
        String::new()
    } else {
        unsafe { CStr::from_ptr(value) }
            .to_string_lossy()
            .into_owned()
    }
}