1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
use std::convert::TryFrom;
use std::path::{Path, PathBuf};
use std::{fs, io, mem};

use crate::control;
use crate::v4l2;
use crate::v4l_sys::*;
use crate::{
    capability::Capabilities, fourcc::FourCC, frameinterval::FrameInterval, framesize::FrameSize,
};

pub use crate::buffer::BufferType as Type;

/// Manage buffers for a device
pub trait Device {
    /// Returns the raw fd of the device
    fn fd(&self) -> std::os::raw::c_int;

    /// Type of the device (capture, overlay, output)
    fn typ(&self) -> Type;
}

/// Query device properties such as supported formats and controls
pub trait QueryDevice {
    /// Returns a vector of all frame intervals that the device supports for the given pixel format
    /// and frame size
    fn enum_frameintervals(
        &self,
        fourcc: FourCC,
        width: u32,
        height: u32,
    ) -> io::Result<Vec<FrameInterval>>;

    /// Returns a vector of valid framesizes that the device supports for the given pixel format
    fn enum_framesizes(&self, fourcc: FourCC) -> io::Result<Vec<FrameSize>>;

    /// Returns video4linux framework defined information such as card, driver, etc.
    fn query_caps(&self) -> io::Result<Capabilities>;

    /// Returns the supported controls for a device such as gain, focus, white balance, etc.
    fn query_controls(&self) -> io::Result<Vec<control::Description>>;
}

impl<T: Device> QueryDevice for T {
    fn enum_frameintervals(
        &self,
        fourcc: FourCC,
        width: u32,
        height: u32,
    ) -> io::Result<Vec<FrameInterval>> {
        let mut frameintervals = Vec::new();
        let mut v4l2_struct: v4l2_frmivalenum = unsafe { mem::zeroed() };

        v4l2_struct.index = 0;
        v4l2_struct.pixel_format = fourcc.into();
        v4l2_struct.width = width;
        v4l2_struct.height = height;

        loop {
            let ret = unsafe {
                v4l2::ioctl(
                    self.fd(),
                    v4l2::vidioc::VIDIOC_ENUM_FRAMEINTERVALS,
                    &mut v4l2_struct as *mut _ as *mut std::os::raw::c_void,
                )
            };

            if ret.is_err() {
                if v4l2_struct.index == 0 {
                    return Err(ret.err().unwrap());
                } else {
                    return Ok(frameintervals);
                }
            }

            if let Ok(frame_interval) = FrameInterval::try_from(v4l2_struct) {
                frameintervals.push(frame_interval);
            }

            v4l2_struct.index += 1;
        }
    }

    fn enum_framesizes(&self, fourcc: FourCC) -> io::Result<Vec<FrameSize>> {
        let mut framesizes = Vec::new();
        let mut v4l2_struct: v4l2_frmsizeenum = unsafe { mem::zeroed() };

        v4l2_struct.index = 0;
        v4l2_struct.pixel_format = fourcc.into();

        loop {
            let ret = unsafe {
                v4l2::ioctl(
                    self.fd(),
                    v4l2::vidioc::VIDIOC_ENUM_FRAMESIZES,
                    &mut v4l2_struct as *mut _ as *mut std::os::raw::c_void,
                )
            };

            if ret.is_err() {
                if v4l2_struct.index == 0 {
                    return Err(ret.err().unwrap());
                } else {
                    return Ok(framesizes);
                }
            }

            if let Ok(frame_size) = FrameSize::try_from(v4l2_struct) {
                framesizes.push(frame_size);
            }

            v4l2_struct.index += 1;
        }
    }

    fn query_caps(&self) -> io::Result<Capabilities> {
        unsafe {
            let mut v4l2_caps: v4l2_capability = mem::zeroed();
            v4l2::ioctl(
                self.fd(),
                v4l2::vidioc::VIDIOC_QUERYCAP,
                &mut v4l2_caps as *mut _ as *mut std::os::raw::c_void,
            )?;

            Ok(Capabilities::from(v4l2_caps))
        }
    }

    fn query_controls(&self) -> io::Result<Vec<control::Description>> {
        let mut controls = Vec::new();
        unsafe {
            let mut v4l2_ctrl: v4l2_queryctrl = mem::zeroed();

            loop {
                v4l2_ctrl.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
                v4l2_ctrl.id |= V4L2_CTRL_FLAG_NEXT_COMPOUND;
                match v4l2::ioctl(
                    self.fd(),
                    v4l2::vidioc::VIDIOC_QUERYCTRL,
                    &mut v4l2_ctrl as *mut _ as *mut std::os::raw::c_void,
                ) {
                    Ok(_) => {
                        // get the basic control information
                        let mut control = control::Description::from(v4l2_ctrl);

                        // if this is a menu control, enumerate its items
                        if control.typ == control::Type::Menu
                            || control.typ == control::Type::IntegerMenu
                        {
                            let mut items = Vec::new();

                            let mut v4l2_menu: v4l2_querymenu = mem::zeroed();
                            v4l2_menu.id = v4l2_ctrl.id;

                            for i in (v4l2_ctrl.minimum..=v4l2_ctrl.maximum)
                                .step_by(v4l2_ctrl.step as usize)
                            {
                                v4l2_menu.index = i as u32;
                                let res = v4l2::ioctl(
                                    self.fd(),
                                    v4l2::vidioc::VIDIOC_QUERYMENU,
                                    &mut v4l2_menu as *mut _ as *mut std::os::raw::c_void,
                                );

                                // BEWARE OF DRAGONS!
                                // The API docs [1] state VIDIOC_QUERYMENU should may return EINVAL
                                // for some indices between minimum and maximum when an item is not
                                // supported by a driver.
                                //
                                // I have no idea why it is advertised in the first place then, but
                                // have seen this happen with a Logitech C920 HD Pro webcam.
                                // In case of errors, let's just skip the offending index.
                                //
                                // [1] https://github.com/torvalds/linux/blob/master/Documentation/userspace-api/media/v4l/vidioc-queryctrl.rst#description
                                if res.is_err() {
                                    continue;
                                }

                                let item =
                                    control::MenuItem::try_from((control.typ, v4l2_menu)).unwrap();
                                items.push((v4l2_menu.index, item));
                            }

                            control.items = Some(items);
                        }

                        controls.push(control);
                    }
                    Err(e) => {
                        if controls.is_empty() || e.kind() != io::ErrorKind::InvalidInput {
                            return Err(e);
                        } else {
                            break;
                        }
                    }
                }
            }
        }

        Ok(controls)
    }
}

/// Represents a video4linux device node
pub struct Info {
    /// Device node path
    path: PathBuf,
}

impl Info {
    /// Returns a device node observer by path
    ///
    /// The device is opened in read only mode.
    ///
    /// # Arguments
    ///
    /// * `path` - Node path (usually a character device or sysfs entry)
    ///
    /// # Example
    ///
    /// ```
    /// use v4l::device::Info;
    /// let node = Info::new("/dev/video0");
    /// ```
    pub fn new<P: AsRef<Path>>(path: P) -> Self {
        Info {
            path: PathBuf::from(path.as_ref()),
        }
    }

    /// Returns the absolute path of the device node
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Returns the index of the device node
    pub fn index(&self) -> Option<usize> {
        let file_name = self.path.file_name()?;

        let mut index_str = String::new();
        for c in file_name
            .to_str()?
            .chars()
            .rev()
            .collect::<String>()
            .chars()
        {
            if !c.is_digit(10) {
                break;
            }

            index_str.push(c);
        }

        let index = index_str.parse::<usize>();
        if index.is_err() {
            return None;
        }

        Some(index.unwrap())
    }

    /// Returns name of the device by parsing its sysfs entry
    pub fn name(&self) -> Option<String> {
        let index = self.index()?;
        let path = format!("{}{}{}", "/sys/class/video4linux/video", index, "/name");
        let name = fs::read_to_string(path);
        match name {
            Ok(name) => Some(name.trim().to_string()),
            Err(_) => None,
        }
    }
}

/// Represents an iterable list of valid devices
#[derive(Default)]
pub struct List {
    /// Position in the list
    pos: usize,
    /// All paths representing potential video4linux devices
    paths: Vec<PathBuf>,
}

impl List {
    /// Returns a list of devices currently known to the system
    ///
    /// # Example
    ///
    /// ```
    /// use v4l::device::List;
    /// let list = List::new();
    /// for dev in list {
    ///     print!("{}{}", dev.index().unwrap(), dev.name().unwrap());
    /// }
    /// ```
    pub fn new() -> Self {
        let mut list = List {
            pos: 0,
            paths: Vec::new(),
        };

        let nodes = fs::read_dir("/dev");
        if let Ok(nodes) = nodes {
            for node in nodes {
                if node.is_err() {
                    continue;
                }
                let node = node.unwrap();
                let file_name = node.file_name();
                let file_name = file_name.to_str().unwrap();

                if file_name.starts_with("video") {
                    list.paths.push(node.path());
                }
            }
        }

        list.paths.sort();
        list
    }
}

impl Iterator for List {
    type Item = Info;

    fn next(&mut self) -> Option<Info> {
        let pos = self.pos;
        if pos == self.paths.len() {
            return None;
        }

        self.pos += 1;
        Some(Info::new(&self.paths[pos]))
    }
}