Skip to main content

ncnn_rust/
layer.rs

1use crate::{error::status, sys, Error, Mat, Options, ParamDict, Result};
2use std::{ffi::CString, marker::PhantomData, rc::Rc};
3
4/// Returns the registered type index of a layer type.
5///
6/// The index identifies the type in a model and is what
7/// [`Net::register_custom_layer_by_typeindex`](crate::Net::register_custom_layer_by_typeindex)
8/// replaces. An unknown name returns [`Error::Invalid`].
9pub fn layer_type_index(name: &str) -> Result<i32> {
10    let name = CString::new(name)?;
11    let index = unsafe { sys::ncnn_layer_type_to_index(name.as_ptr()) };
12    if index < 0 {
13        return Err(Error::invalid(format!(
14            "Unknown layer type {}",
15            name.to_string_lossy()
16        )));
17    }
18    Ok(index)
19}
20
21/// A single CPU layer with automatic pipeline cleanup.
22pub struct Layer {
23    raw: sys::ncnn_layer_t,
24    options: Options,
25    pipeline: bool,
26    _thread: PhantomData<Rc<()>>,
27}
28impl Layer {
29    /// Creates a built-in CPU layer.
30    pub fn new(name: &str, options: Options) -> Result<Self> {
31        let name = CString::new(name)?;
32        let raw = unsafe { sys::ncnn_layer_create_by_type(name.as_ptr()) };
33        if raw.is_null() {
34            return Err(Error::invalid("Unknown layer type"));
35        }
36        Ok(Self {
37            raw,
38            options,
39            pipeline: false,
40            _thread: PhantomData,
41        })
42    }
43    /// Loads layer-specific parameters before pipeline creation.
44    ///
45    /// # Safety
46    /// Parameters must satisfy the selected layer's shape, type, and range contract.
47    pub unsafe fn load_param(&mut self, parameters: &ParamDict) -> Result<()> {
48        if self.pipeline {
49            return Err(Error::invalid("Load parameters before pipeline creation"));
50        }
51        status((*self.raw)
52            .load_param
53            .ok_or(Error::invalid("Missing load_param callback"))?(
54            self.raw,
55            parameters.as_raw(),
56        ))
57    }
58    /// Loads weights through an upstream ModelBin.
59    ///
60    /// # Safety
61    /// The model and its reader must be valid for this call. Borrowed weight storage
62    /// and allocator dependencies must remain valid until the layer is destroyed.
63    pub unsafe fn load_model(&mut self, model: sys::ncnn_modelbin_t) -> Result<()> {
64        if self.pipeline {
65            return Err(Error::invalid("Load weights before pipeline creation"));
66        }
67        status(sys::ncnn_rs_layer_load_model(self.raw, model))
68    }
69    /// Creates a pipeline after parameter and weight loading.
70    ///
71    /// # Safety
72    /// Required parameters and weights must be loaded according to the layer contract.
73    pub unsafe fn create_pipeline(&mut self) -> Result<()> {
74        if self.pipeline {
75            return Err(Error::invalid("Pipeline already created"));
76        }
77        // Mark before calling so partial pipeline construction is also cleaned up.
78        self.pipeline = true;
79        status((*self.raw)
80            .create_pipeline
81            .ok_or(Error::invalid("Missing create_pipeline callback"))?(
82            self.raw,
83            self.options.raw,
84        ))
85    }
86    /// Executes a one-input, one-output CPU layer.
87    ///
88    /// # Safety
89    /// The layer must support this forward form and the input's dimensions, scalar
90    /// format, and packing. The native callback must initialize the output elements.
91    pub unsafe fn forward(&mut self, input: &Mat) -> Result<Mat> {
92        if !self.pipeline {
93            return Err(Error::invalid("Create the pipeline before forward"));
94        }
95        let input = input.deep_clone()?;
96        let mut raw = std::ptr::null_mut();
97        let code = (*self.raw)
98            .forward_1
99            .ok_or(Error::invalid("Missing forward callback"))?(
100            self.raw,
101            input.raw,
102            &mut raw,
103            self.options.raw,
104        );
105        if code != 0 {
106            if !raw.is_null() {
107                sys::ncnn_mat_destroy(raw);
108            }
109            return Err(Error::Native(code));
110        }
111        Mat::owned(raw, false)?.deep_clone()
112    }
113    /// Borrows the native layer handle.
114    pub fn as_raw(&self) -> sys::ncnn_layer_t {
115        self.raw
116    }
117}
118impl Drop for Layer {
119    fn drop(&mut self) {
120        unsafe {
121            if self.pipeline {
122                if let Some(destroy) = (*self.raw).destroy_pipeline {
123                    destroy(self.raw, self.options.raw);
124                }
125            }
126            sys::ncnn_layer_destroy(self.raw);
127        }
128    }
129}
130
131/// A layer a loaded graph owns, borrowed for native calls.
132///
133/// [`Net::layer_handle`](crate::Net::layer_handle) builds one for an index the graph loaded. The
134/// native layer belongs to the network and stays valid until the graph is cleared or reloaded,
135/// while this value owns only the C handle around it, which releases on drop and never destroys the
136/// layer. The borrow of the network keeps the layer alive for as long as the handle exists. A
137/// registered custom layer keeps its userdata, so a native call that rewrites userdata breaks the
138/// registration.
139pub struct GraphLayer<'net> {
140    raw: sys::ncnn_layer_t,
141    _net: std::marker::PhantomData<&'net crate::Net>,
142}
143impl<'net> GraphLayer<'net> {
144    pub(crate) fn borrowed(raw: sys::ncnn_layer_t) -> Self {
145        Self {
146            raw,
147            _net: std::marker::PhantomData,
148        }
149    }
150    /// Borrows the native layer handle.
151    ///
152    /// The handle is the one the C API expects. Native calls that write through it, or that read a
153    /// tensor, follow the same rules as the rest of the raw module: the graph stays loaded and no
154    /// request runs on the network meanwhile.
155    pub fn as_raw(&self) -> sys::ncnn_layer_t {
156        self.raw
157    }
158}
159impl Drop for GraphLayer<'_> {
160    fn drop(&mut self) {
161        // Only the C handle is released; the layer stays with the network.
162        unsafe { sys::ncnn_rs_borrowed_layer_release(self.raw) };
163    }
164}
165
166/// A ModelBin backed by owned, deep-copied tensors.
167pub struct ModelBin {
168    raw: sys::ncnn_modelbin_t,
169    _weights: Vec<Mat>,
170    _handles: Vec<sys::ncnn_mat_t>,
171}
172impl ModelBin {
173    /// Builds a reader over owned copies of the supplied tensors.
174    pub fn from_mats(weights: &[&Mat]) -> Result<Self> {
175        let count = i32::try_from(weights.len()).map_err(|_| Error::invalid("Too many weights"))?;
176        let owned: Vec<Mat> = weights
177            .iter()
178            .map(|m| m.deep_clone())
179            .collect::<Result<_>>()?;
180        let handles: Vec<_> = owned.iter().map(Mat::as_raw).collect();
181        let raw = unsafe { sys::ncnn_rs_modelbin_from_mats(handles.as_ptr(), count) };
182        if raw.is_null() {
183            return Err(Error::Native(-100));
184        }
185        Ok(Self {
186            raw,
187            _weights: owned,
188            _handles: handles,
189        })
190    }
191    /// Borrows the native reader handle.
192    pub fn as_raw(&self) -> sys::ncnn_modelbin_t {
193        self.raw
194    }
195}
196impl Drop for ModelBin {
197    fn drop(&mut self) {
198        unsafe {
199            sys::ncnn_modelbin_destroy(self.raw);
200        }
201    }
202}