libcamera/
control_value.rs

1use std::ptr::NonNull;
2
3use libcamera_sys::*;
4use smallvec::{smallvec, SmallVec};
5use thiserror::Error;
6
7use crate::geometry::{Point, Rectangle, Size};
8
9#[derive(Error, Debug)]
10pub enum ControlValueError {
11    /// Control value type does not match the one being read/written
12    #[error("Expected type {expected}, found {found}")]
13    InvalidType { expected: u32, found: u32 },
14    /// Control value type is not recognized
15    #[error("Unknown control type {0}")]
16    UnknownType(u32),
17    /// Control value dimensionality mismatch
18    #[error("Expected {expected} elements, found {found}")]
19    InvalidLength { expected: usize, found: usize },
20    /// Control value type is correct, but it could not be converted into enum variant
21    #[error("Unknown enum variant {0:?}")]
22    UnknownVariant(ControlValue),
23}
24
25/// A value of a control or a property.
26#[derive(Debug, Clone)]
27pub enum ControlValue {
28    None,
29    Bool(SmallVec<[bool; 1]>),
30    Byte(SmallVec<[u8; 1]>),
31    Uint16(SmallVec<[u16; 1]>),
32    Uint32(SmallVec<[u32; 1]>),
33    Int32(SmallVec<[i32; 1]>),
34    Int64(SmallVec<[i64; 1]>),
35    Float(SmallVec<[f32; 1]>),
36    String(String),
37    Rectangle(SmallVec<[Rectangle; 1]>),
38    Size(SmallVec<[Size; 1]>),
39    // bad gues
40    Point(SmallVec<[Point; 1]>),
41}
42
43macro_rules! impl_control_value {
44    ($p:path, $type:ty) => {
45        impl From<$type> for ControlValue {
46            fn from(val: $type) -> Self {
47                $p(smallvec![val])
48            }
49        }
50
51        impl TryFrom<ControlValue> for $type {
52            type Error = ControlValueError;
53
54            fn try_from(value: ControlValue) -> Result<Self, Self::Error> {
55                match value {
56                    $p(mut val) => {
57                        if val.len() == 1 {
58                            Ok(val.pop().unwrap())
59                        } else {
60                            Err(ControlValueError::InvalidLength {
61                                expected: 1,
62                                found: val.len(),
63                            })
64                        }
65                    }
66                    _ => Err(ControlValueError::InvalidType {
67                        // not really efficient, but eh, only on error
68                        expected: $p(Default::default()).ty(),
69                        found: value.ty(),
70                    }),
71                }
72            }
73        }
74    };
75}
76
77impl_control_value!(ControlValue::Bool, bool);
78impl_control_value!(ControlValue::Byte, u8);
79impl_control_value!(ControlValue::Uint16, u16);
80impl_control_value!(ControlValue::Uint32, u32);
81impl_control_value!(ControlValue::Int32, i32);
82impl_control_value!(ControlValue::Int64, i64);
83impl_control_value!(ControlValue::Float, f32);
84impl_control_value!(ControlValue::Rectangle, Rectangle);
85impl_control_value!(ControlValue::Size, Size);
86impl_control_value!(ControlValue::Point, Point);
87
88macro_rules! impl_control_value_vec {
89    ($p:path, $type:ty) => {
90        impl From<Vec<$type>> for ControlValue {
91            fn from(val: Vec<$type>) -> Self {
92                $p(SmallVec::from_vec(val))
93            }
94        }
95
96        impl TryFrom<ControlValue> for Vec<$type> {
97            type Error = ControlValueError;
98
99            fn try_from(value: ControlValue) -> Result<Self, Self::Error> {
100                match value {
101                    $p(val) => Ok(val.into_vec()),
102                    _ => Err(ControlValueError::InvalidType {
103                        // not really efficient, but eh, only on error
104                        expected: $p(Default::default()).ty(),
105                        found: value.ty(),
106                    }),
107                }
108            }
109        }
110    };
111}
112
113impl_control_value_vec!(ControlValue::Bool, bool);
114impl_control_value_vec!(ControlValue::Byte, u8);
115impl_control_value_vec!(ControlValue::Uint16, u16);
116impl_control_value_vec!(ControlValue::Uint32, u32);
117impl_control_value_vec!(ControlValue::Int32, i32);
118impl_control_value_vec!(ControlValue::Int64, i64);
119impl_control_value_vec!(ControlValue::Float, f32);
120impl_control_value_vec!(ControlValue::Rectangle, Rectangle);
121impl_control_value_vec!(ControlValue::Size, Size);
122impl_control_value_vec!(ControlValue::Point, Point);
123
124macro_rules! impl_control_value_array {
125    ($p:path, $type:ty) => {
126        impl<const N: usize> From<[$type; N]> for ControlValue {
127            fn from(val: [$type; N]) -> Self {
128                $p(SmallVec::from_slice(&val))
129            }
130        }
131
132        impl<const N: usize> TryFrom<ControlValue> for [$type; N] {
133            type Error = ControlValueError;
134
135            fn try_from(value: ControlValue) -> Result<Self, Self::Error> {
136                match value {
137                    $p(val) => {
138                        Ok(val
139                            .into_vec()
140                            .try_into()
141                            .map_err(|e: Vec<$type>| ControlValueError::InvalidLength {
142                                expected: N,
143                                found: e.len(),
144                            })?)
145                    }
146                    _ => Err(ControlValueError::InvalidType {
147                        // not really efficient, but eh, only on error
148                        expected: $p(Default::default()).ty(),
149                        found: value.ty(),
150                    }),
151                }
152            }
153        }
154
155        impl<const N: usize, const M: usize> From<[[$type; M]; N]> for ControlValue {
156            fn from(val: [[$type; M]; N]) -> Self {
157                $p(SmallVec::from_slice(&unsafe {
158                    core::slice::from_raw_parts(val.as_ptr().cast(), N * M)
159                }))
160            }
161        }
162
163        impl<const N: usize, const M: usize> TryFrom<ControlValue> for [[$type; M]; N] {
164            type Error = ControlValueError;
165
166            fn try_from(value: ControlValue) -> Result<Self, Self::Error> {
167                match value {
168                    $p(val) => {
169                        if val.len() == N * M {
170                            let mut iter = val.into_iter();
171                            Ok([[(); M]; N].map(|a| a.map(|_| iter.next().unwrap())))
172                        } else {
173                            Err(ControlValueError::InvalidLength {
174                                expected: N * M,
175                                found: val.len(),
176                            })
177                        }
178                    }
179                    _ => Err(ControlValueError::InvalidType {
180                        // not really efficient, but eh, only on error
181                        expected: $p(Default::default()).ty(),
182                        found: value.ty(),
183                    }),
184                }
185            }
186        }
187    };
188}
189
190impl_control_value_array!(ControlValue::Bool, bool);
191impl_control_value_array!(ControlValue::Byte, u8);
192impl_control_value_array!(ControlValue::Uint16, u16);
193impl_control_value_array!(ControlValue::Uint32, u32);
194impl_control_value_array!(ControlValue::Int32, i32);
195impl_control_value_array!(ControlValue::Int64, i64);
196impl_control_value_array!(ControlValue::Float, f32);
197impl_control_value_array!(ControlValue::Rectangle, Rectangle);
198impl_control_value_array!(ControlValue::Size, Size);
199impl_control_value_array!(ControlValue::Point, Point);
200
201impl From<String> for ControlValue {
202    fn from(val: String) -> Self {
203        Self::String(val)
204    }
205}
206
207impl TryFrom<ControlValue> for String {
208    type Error = ControlValueError;
209
210    fn try_from(value: ControlValue) -> Result<Self, Self::Error> {
211        match value {
212            ControlValue::String(v) => Ok(v),
213            _ => Err(ControlValueError::InvalidType {
214                expected: libcamera_control_type::LIBCAMERA_CONTROL_TYPE_STRING,
215                found: value.ty(),
216            }),
217        }
218    }
219}
220
221impl ControlValue {
222    pub(crate) unsafe fn read(val: NonNull<libcamera_control_value_t>) -> Result<Self, ControlValueError> {
223        let ty = unsafe { libcamera_control_value_type(val.as_ptr()) };
224        let num_elements = unsafe { libcamera_control_value_num_elements(val.as_ptr()) };
225        let data = unsafe { libcamera_control_value_get(val.as_ptr()) };
226
227        use libcamera_control_type::*;
228        match ty {
229            LIBCAMERA_CONTROL_TYPE_NONE => Ok(Self::None),
230            LIBCAMERA_CONTROL_TYPE_BOOL => {
231                let slice = core::slice::from_raw_parts(data as *const bool, num_elements);
232                Ok(Self::Bool(SmallVec::from_slice(slice)))
233            }
234            LIBCAMERA_CONTROL_TYPE_BYTE => {
235                let slice = core::slice::from_raw_parts(data as *const u8, num_elements);
236                Ok(Self::Byte(SmallVec::from_slice(slice)))
237            }
238            LIBCAMERA_CONTROL_TYPE_UINT16 => {
239                let slice = core::slice::from_raw_parts(data as *const u16, num_elements);
240                Ok(Self::Uint16(SmallVec::from_slice(slice)))
241            }
242            LIBCAMERA_CONTROL_TYPE_UINT32 => {
243                let slice = core::slice::from_raw_parts(data as *const u32, num_elements);
244                Ok(Self::Uint32(SmallVec::from_slice(slice)))
245            }
246            LIBCAMERA_CONTROL_TYPE_INT32 => {
247                let slice = core::slice::from_raw_parts(data as *const i32, num_elements);
248                Ok(Self::Int32(SmallVec::from_slice(slice)))
249            }
250            LIBCAMERA_CONTROL_TYPE_INT64 => {
251                let slice = core::slice::from_raw_parts(data as *const i64, num_elements);
252                Ok(Self::Int64(SmallVec::from_slice(slice)))
253            }
254            LIBCAMERA_CONTROL_TYPE_FLOAT => {
255                let slice = core::slice::from_raw_parts(data as *const f32, num_elements);
256                Ok(Self::Float(SmallVec::from_slice(slice)))
257            }
258            LIBCAMERA_CONTROL_TYPE_STRING => {
259                let slice = core::slice::from_raw_parts(data as *const u8, num_elements);
260                Ok(Self::String(core::str::from_utf8(slice).unwrap().to_string()))
261            }
262            LIBCAMERA_CONTROL_TYPE_RECTANGLE => {
263                let slice = core::slice::from_raw_parts(data as *const libcamera_rectangle_t, num_elements);
264                Ok(Self::Rectangle(SmallVec::from_iter(
265                    slice.iter().map(|r| Rectangle::from(*r)),
266                )))
267            }
268            LIBCAMERA_CONTROL_TYPE_SIZE => {
269                let slice = core::slice::from_raw_parts(data as *const libcamera_size_t, num_elements);
270                Ok(Self::Size(SmallVec::from_iter(slice.iter().map(|r| Size::from(*r)))))
271            }
272            LIBCAMERA_CONTROL_TYPE_POINT => {
273                let slice = core::slice::from_raw_parts(data as *const libcamera_point_t, num_elements);
274                Ok(Self::Point(SmallVec::from_iter(slice.iter().map(|r| Point::from(*r)))))
275            }
276            _ => Err(ControlValueError::UnknownType(ty)),
277        }
278    }
279
280    pub(crate) unsafe fn write(&self, val: NonNull<libcamera_control_value_t>) {
281        let (data, len) = match self {
282            ControlValue::None => (core::ptr::null(), 0),
283            ControlValue::Bool(v) => (v.as_ptr().cast(), v.len()),
284            ControlValue::Byte(v) => (v.as_ptr().cast(), v.len()),
285            ControlValue::Uint16(v) => (v.as_ptr().cast(), v.len()),
286            ControlValue::Uint32(v) => (v.as_ptr().cast(), v.len()),
287            ControlValue::Int32(v) => (v.as_ptr().cast(), v.len()),
288            ControlValue::Int64(v) => (v.as_ptr().cast(), v.len()),
289            ControlValue::Float(v) => (v.as_ptr().cast(), v.len()),
290            ControlValue::String(v) => (v.as_ptr().cast(), v.len()),
291            ControlValue::Rectangle(v) => (v.as_ptr().cast(), v.len()),
292            ControlValue::Size(v) => (v.as_ptr().cast(), v.len()),
293            ControlValue::Point(v) => (v.as_ptr().cast(), v.len()),
294        };
295
296        let ty = self.ty();
297        let is_array = if ty == libcamera_control_type::LIBCAMERA_CONTROL_TYPE_STRING {
298            true
299        } else {
300            len != 1
301        };
302
303        libcamera_control_value_set(val.as_ptr(), self.ty(), data, is_array, len as _);
304    }
305
306    pub fn ty(&self) -> u32 {
307        use libcamera_control_type::*;
308        match self {
309            ControlValue::None => LIBCAMERA_CONTROL_TYPE_NONE,
310            ControlValue::Bool(_) => LIBCAMERA_CONTROL_TYPE_BOOL,
311            ControlValue::Byte(_) => LIBCAMERA_CONTROL_TYPE_BYTE,
312            ControlValue::Uint16(_) => LIBCAMERA_CONTROL_TYPE_UINT16,
313            ControlValue::Uint32(_) => LIBCAMERA_CONTROL_TYPE_UINT32,
314            ControlValue::Int32(_) => LIBCAMERA_CONTROL_TYPE_INT32,
315            ControlValue::Int64(_) => LIBCAMERA_CONTROL_TYPE_INT64,
316            ControlValue::Float(_) => LIBCAMERA_CONTROL_TYPE_FLOAT,
317            ControlValue::String(_) => LIBCAMERA_CONTROL_TYPE_STRING,
318            ControlValue::Rectangle(_) => LIBCAMERA_CONTROL_TYPE_RECTANGLE,
319            ControlValue::Size(_) => LIBCAMERA_CONTROL_TYPE_SIZE,
320            ControlValue::Point(_) => LIBCAMERA_CONTROL_TYPE_POINT,
321        }
322    }
323}