linuxvideo 0.3.5

V4L2 video capture and output library
Documentation
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! Linux video device library.
//!
//! This library provides a (hopefully) convenient and high-level wrapper around the V4L2 ioctls,
//! and allows accessing video devices (capture cards, webcams, etc.) on Linux systems.
//!
//! The main entry points to the library are [`list`], for enumerating all V4L2 devices (and opening
//! one of them by name), and [`Device::open`], for opening a specific path.

#[macro_use]
mod macros;
mod buf_type;
pub mod controls;
pub mod format;
mod pixel_format;
mod raw;
mod shared;
pub mod stream;
pub mod uvc;

use pixel_format::PixelFormat;
use std::{
    fmt,
    fs::{self, File, OpenOptions},
    io::{self, Read, Write},
    mem::{self, MaybeUninit},
    os::unix::prelude::*,
    path::{Path, PathBuf},
};

use controls::{ControlDesc, ControlIter, TextMenuIter};
use format::{Format, FormatDescIter, FrameIntervals, FrameSizes, MetaFormat, PixFormat};
use raw::controls::Cid;
use shared::{CaptureParamFlags, Memory, StreamParamCaps};
use stream::{ReadStream, WriteStream, DEFAULT_BUFFER_COUNT};

pub use buf_type::*;
pub use shared::{
    AnalogStd, CapabilityFlags, Fract, InputCapabilities, InputStatus, InputType,
    OutputCapabilities, OutputType,
};

const DEVICE_PREFIXES: &[&str] = &[
    "video",
    "vbi",
    "radio",
    "swradio",
    "v4l-touch",
    "v4l-subdev",
];

/// Returns an iterator over all connected V4L2 devices.
///
/// This will enumerate all devices in `/dev` that match one of the V4L2 device file patterns:
///
/// - **`/dev/video*`**: webcams, capture cards, video output devices, codecs, video overlays, etc.
/// - **`/dev/vbi*`**: devices for capturing and outputting raw **V**ertical **B**lanking **I**nterval data.
/// - **`/dev/radio*`**: AM and FM radio transmitters and receivers.
/// - **`/dev/swradio*`**: Software-defined radios.
/// - **`/dev/v4l-touch*`**: Touch screens and other touch devices.
/// - **`/dev/v4l-subdev*`**: A sub-device exported as part of a bigger device.
pub fn list() -> io::Result<impl Iterator<Item = io::Result<Device>>> {
    Ok(fs::read_dir("/dev")?.flat_map(|file| {
        let file = match file {
            Ok(file) => file,
            Err(e) => return Some(Err(e.into())),
        };

        let name = file.file_name();
        if !DEVICE_PREFIXES
            .iter()
            .any(|p| name.as_bytes().starts_with(p.as_bytes()))
        {
            // Doesn't match any V4L2 device patterns.
            return None;
        }

        // Sanity check that it's a char device.
        match file.file_type() {
            Ok(ty) => {
                if !ty.is_char_device() {
                    log::warn!(
                        "'{}' is not a character device: {:?}",
                        name.to_string_lossy(),
                        ty,
                    );
                    return None;
                }
            }
            Err(e) => return Some(Err(e.into())),
        }

        Some(Device::open(&file.path()))
    }))
}

/// A V4L2 device.
#[derive(Debug)]
pub struct Device {
    file: File,
    available_capabilities: CapabilityFlags,
}

impl Device {
    /// Opens a V4L2 device file from the given path.
    ///
    /// If the path does not refer to a V4L2 device node, an error will be returned.
    pub fn open<A: AsRef<Path>>(path: A) -> io::Result<Self> {
        Self::open_impl(path.as_ref())
    }

    fn open_impl(path: &Path) -> io::Result<Self> {
        let file = OpenOptions::new().read(true).write(true).open(path)?;
        let mut this = Self {
            file,
            available_capabilities: CapabilityFlags::empty(),
        };
        let caps = this.capabilities()?;
        this.available_capabilities = caps.device_capabilities();

        Ok(this)
    }

    fn fd(&self) -> RawFd {
        self.file.as_raw_fd()
    }

    /// Returns the path to the V4L2 device.
    ///
    /// This will invoke `readlink(2)` on `/proc/self/fd/N` to find the path, so it will not work
    /// on FreeBSD or other Unix-likes that don't expose a procfs with this functionality.
    pub fn path(&self) -> io::Result<PathBuf> {
        fs::read_link(format!("/proc/self/fd/{}", self.fd()))
    }

    /// Queries the device's [`Capabilities`].
    pub fn capabilities(&self) -> io::Result<Capabilities> {
        unsafe {
            let mut caps = MaybeUninit::uninit();
            let res = raw::VIDIOC_QUERYCAP.ioctl(self, caps.as_mut_ptr())?;
            assert_eq!(res, 0);
            Ok(Capabilities(caps.assume_init()))
        }
    }

    pub fn supported_buf_types(&self) -> BufTypes {
        BufTypes::from_capabilities(self.available_capabilities)
    }

    /// Enumerates the supported pixel formats of a stream.
    ///
    /// `buf_type` must be one of `VIDEO_CAPTURE`, `VIDEO_CAPTURE_MPLANE`, `VIDEO_OUTPUT`,
    /// `VIDEO_OUTPUT_MPLANE`, `VIDEO_OVERLAY`, `SDR_CAPTURE`, `SDR_OUTPUT`, `META_CAPTURE`, or
    /// `META_OUTPUT`.
    pub fn formats(&self, buf_type: BufType) -> FormatDescIter<'_> {
        FormatDescIter::new(self, buf_type)
    }

    /// Returns the supported frame sizes for a given pixel format.
    ///
    /// # Errors
    ///
    /// An `ENOTTY` error will be returned if `pixel_format` specifies a format that does not
    /// describe video data (for example, [`PixelFormat::UVC`] or other metadata formats).
    pub fn frame_sizes(&self, pixel_format: PixelFormat) -> io::Result<FrameSizes> {
        FrameSizes::new(self, pixel_format)
    }

    pub fn frame_intervals(
        &self,
        pixel_format: PixelFormat,
        width: u32,
        height: u32,
    ) -> io::Result<FrameIntervals> {
        FrameIntervals::new(self, pixel_format, width, height)
    }

    /// Returns an iterator over the [`Input`]s of the device.
    ///
    /// # Errors
    ///
    /// May return `ENOTTY` if the device is not an input device.
    pub fn inputs(&self) -> InputIter<'_> {
        InputIter {
            device: self,
            next_index: 0,
            finished: false,
        }
    }

    /// Returns an iterator over the [`Output`]s of the device.
    ///
    /// # Errors
    ///
    /// May return `ENOTTY` if the device is not an output device.
    pub fn outputs(&self) -> OutputIter<'_> {
        OutputIter {
            device: self,
            next_index: 0,
            finished: false,
        }
    }

    pub fn controls(&self) -> ControlIter<'_> {
        ControlIter::new(self)
    }

    /// Returns an iterator over the valid values of a menu control.
    pub fn enumerate_menu(&self, ctrl: &ControlDesc) -> TextMenuIter<'_> {
        TextMenuIter::new(self, ctrl)
    }

    pub fn read_control_raw(&self, cid: Cid) -> io::Result<i32> {
        let mut control = raw::controls::Control { id: cid, value: 0 };

        unsafe {
            raw::VIDIOC_G_CTRL.ioctl(self, &mut control)?;
        }

        Ok(control.value)
    }

    pub fn write_control_raw(&mut self, cid: Cid, value: i32) -> io::Result<()> {
        let mut control = raw::controls::Control { id: cid, value };
        unsafe {
            raw::VIDIOC_S_CTRL.ioctl(self, &mut control)?;
        }
        Ok(())
    }

    /// Reads the stream format in use by `buf_type`.
    ///
    /// The returned [`Format`] variant will match `buf_type`.
    ///
    /// If no format is set, this returns `EINVAL`.
    ///
    /// # Panics
    ///
    /// This will panic if `buf_type` corresponds to a buffer type that hasn't yet been implemented
    /// in [`Format`].
    pub fn format(&self, buf_type: BufType) -> io::Result<Format> {
        unsafe {
            let mut format = raw::Format {
                type_: buf_type,
                ..mem::zeroed()
            };
            raw::VIDIOC_G_FMT.ioctl(self, &mut format)?;
            let fmt = Format::from_raw(format)
                .unwrap_or_else(|| todo!("unsupported buffer type {:?}", buf_type));
            Ok(fmt)
        }
    }

    /// Negotiates a stream's format.
    ///
    /// The driver will adjust the values in `format` to the closest values it supports (the variant
    /// will not be changed). The modified `Format` is returned.
    fn set_format_raw(&mut self, format: Format) -> io::Result<Format> {
        unsafe {
            let mut raw_format: raw::Format = mem::zeroed();
            match format {
                Format::VideoCapture(f) => {
                    raw_format.type_ = BufType::VIDEO_CAPTURE;
                    raw_format.fmt.pix = f.to_raw();
                }
                Format::VideoOutput(f) => {
                    raw_format.type_ = BufType::VIDEO_OUTPUT;
                    raw_format.fmt.pix = f.to_raw();
                }
                Format::VideoCaptureMplane(f) => {
                    raw_format.type_ = BufType::VIDEO_CAPTURE_MPLANE;
                    raw_format.fmt.pix_mp = f.to_raw();
                }
                Format::VideoOutputMplane(f) => {
                    raw_format.type_ = BufType::VIDEO_OUTPUT_MPLANE;
                    raw_format.fmt.pix_mp = f.to_raw();
                }
                Format::VideoOverlay(f) => {
                    raw_format.type_ = BufType::VIDEO_OVERLAY;
                    raw_format.fmt.win = f.to_raw();
                }
                Format::MetaCapture(f) => {
                    raw_format.type_ = BufType::META_CAPTURE;
                    raw_format.fmt.meta = f.to_raw();
                }
                Format::MetaOutput(f) => {
                    raw_format.type_ = BufType::META_OUTPUT;
                    raw_format.fmt.meta = f.to_raw();
                }
            }
            raw::VIDIOC_S_FMT.ioctl(self, &mut raw_format)?;
            let fmt = Format::from_raw(raw_format).unwrap();
            Ok(fmt)
        }
    }

    /// Puts the device into video capture mode and negotiates a pixel format.
    ///
    /// # Format Negotiation
    ///
    /// Generally, the driver is allowed to change most properties of the [`PixFormat`], including
    /// the requested dimensions and the [`PixelFormat`], if the provided value is not supported.
    /// However, it is not required to do so and may instead return `EINVAL` if the parameters are
    /// not supported. One example where this happens is with `v4l2loopback`.
    pub fn video_capture(mut self, format: PixFormat) -> io::Result<VideoCaptureDevice> {
        let format = match self.set_format_raw(Format::VideoCapture(format))? {
            Format::VideoCapture(fmt) => fmt,
            _ => unreachable!(),
        };

        Ok(VideoCaptureDevice {
            file: self.file,
            format,
        })
    }

    /// Puts the device into video output mode and negotiates a pixel format.
    ///
    /// # Format Negotiation
    ///
    /// Generally, the driver is allowed to change most properties of the [`PixFormat`], including
    /// the requested dimensions and the [`PixelFormat`], if the provided value is not supported.
    /// However, it is not required to do so and may instead return `EINVAL` if the parameters are
    /// not supported. One example where this happens is with `v4l2loopback`.
    pub fn video_output(mut self, format: PixFormat) -> io::Result<VideoOutputDevice> {
        let format = match self.set_format_raw(Format::VideoOutput(format))? {
            Format::VideoOutput(fmt) => fmt,
            _ => unreachable!(),
        };

        Ok(VideoOutputDevice {
            file: self.file,
            format,
        })
    }

    /// Puts the device into metadata capture mode and negotiates a data format.
    pub fn meta_capture(mut self, format: MetaFormat) -> io::Result<MetaCaptureDevice> {
        let format = match self.set_format_raw(Format::MetaCapture(format))? {
            Format::MetaCapture(fmt) => fmt,
            _ => unreachable!(),
        };

        Ok(MetaCaptureDevice {
            file: self.file,
            format,
        })
    }
}

impl AsRawFd for Device {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.file.as_raw_fd()
    }
}

impl AsFd for Device {
    #[inline]
    fn as_fd(&self) -> BorrowedFd<'_> {
        unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
    }
}

/// A video device configured for video capture.
///
/// Returned by [`Device::video_capture`].
pub struct VideoCaptureDevice {
    file: File,
    format: PixFormat,
}

impl VideoCaptureDevice {
    /// Returns the pixel format the driver chose for capturing.
    ///
    /// This may (and usually will) differ from the format passed to [`Device::video_capture`].
    pub fn format(&self) -> &PixFormat {
        &self.format
    }

    /// Requests a change to the frame interval.
    ///
    /// Returns the actual frame interval chosen by the driver.
    ///
    /// Supported frame intervals depend on the pixel format and video resolution and can be
    /// enumerated with [`Device::frame_intervals`].
    pub fn set_frame_interval(&self, interval: Fract) -> io::Result<Fract> {
        unsafe {
            let mut parm = raw::StreamParm {
                type_: BufType::VIDEO_CAPTURE,
                union: raw::StreamParmUnion {
                    capture: raw::CaptureParm {
                        timeperframe: interval,
                        capability: StreamParamCaps::TIMEPERFRAME,
                        capturemode: CaptureParamFlags::empty(),
                        extendedmode: 0,
                        readbuffers: 0,
                        reserved: [0; 4],
                    },
                },
            };
            raw::VIDIOC_S_PARM.ioctl(self, &mut parm)?;
            Ok(parm.union.capture.timeperframe)
        }
    }

    /// Initializes streaming I/O mode.
    pub fn into_stream(self) -> io::Result<ReadStream> {
        Ok(ReadStream::new(
            self.file,
            BufType::VIDEO_CAPTURE,
            Memory::MMAP,
            DEFAULT_BUFFER_COUNT,
        )?)
    }
}

/// Performs a direct `read()` from the video device.
///
/// This will only succeed if the device advertises the `READWRITE` capability, otherwise an
/// error will be returned and you have to use the streaming API instead.
impl Read for VideoCaptureDevice {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.file.read(buf)
    }
}

impl AsRawFd for VideoCaptureDevice {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.file.as_raw_fd()
    }
}

impl AsFd for VideoCaptureDevice {
    #[inline]
    fn as_fd(&self) -> BorrowedFd<'_> {
        unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
    }
}

/// A video device configured for video output.
///
/// Returned by [`Device::video_output`].
pub struct VideoOutputDevice {
    file: File,
    format: PixFormat,
}

impl VideoOutputDevice {
    /// Returns the video format chosen by the driver.
    pub fn format(&self) -> &PixFormat {
        &self.format
    }

    /// Initializes streaming I/O mode.
    pub fn into_stream(self) -> io::Result<WriteStream> {
        Ok(WriteStream::new(
            self.file,
            BufType::VIDEO_CAPTURE,
            Memory::MMAP,
            DEFAULT_BUFFER_COUNT,
        )?)
    }
}

/// Performs a direct `write()` on the video device file, writing a video frame to it.
///
/// This will only succeed if the device advertises the `READWRITE` capability, otherwise an
/// error will be returned and you have to use the streaming API instead.
///
/// Note that some applications, like guvcview, do not support the read/write methods, so using this
/// on a v4l2loopback device will not work with such applications.
impl Write for VideoOutputDevice {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.file.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.file.flush()
    }
}

impl AsRawFd for VideoOutputDevice {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.file.as_raw_fd()
    }
}

impl AsFd for VideoOutputDevice {
    #[inline]
    fn as_fd(&self) -> BorrowedFd<'_> {
        unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
    }
}

/// A device configured for metadata capture.
///
/// Returned by [`Device::meta_capture`].
pub struct MetaCaptureDevice {
    file: File,
    format: MetaFormat,
}

impl MetaCaptureDevice {
    /// Returns the metadata format the driver chose.
    pub fn format(&self) -> &MetaFormat {
        &self.format
    }

    /// Initializes streaming I/O mode.
    pub fn into_stream(self) -> io::Result<ReadStream> {
        Ok(ReadStream::new(
            self.file,
            BufType::META_CAPTURE,
            Memory::MMAP,
            DEFAULT_BUFFER_COUNT,
        )?)
    }
}

/// Performs a direct `read()` from the video device.
///
/// This will only succeed if the device advertises the `READWRITE` capability, otherwise an
/// error will be returned and you have to use the streaming API instead.
impl Read for MetaCaptureDevice {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.file.read(buf)
    }
}

impl AsRawFd for MetaCaptureDevice {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.file.as_raw_fd()
    }
}

impl AsFd for MetaCaptureDevice {
    #[inline]
    fn as_fd(&self) -> BorrowedFd<'_> {
        unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
    }
}

/// Stores generic device information.
///
/// Returned by [`Device::capabilities`].
pub struct Capabilities(raw::Capabilities);

impl Capabilities {
    /// Returns the identifier of the V4L2 driver that provides this device.
    ///
    /// Examples:
    /// - `uvcvideo`
    /// - `v4l2 loopback`
    pub fn driver(&self) -> &str {
        byte_array_to_str(&self.0.driver)
    }

    /// Returns the card or device name.
    ///
    /// For `v4l2loopback` devices, the reported card name can be configured by passing the
    /// `card_label` parameter when loading the module (or via `modprobe.d`).
    pub fn card(&self) -> &str {
        byte_array_to_str(&self.0.card)
    }

    /// Returns a description of where on the system the device is attached.
    ///
    /// Examples:
    /// - `usb-0000:0a:00.3-2.1`
    /// - `platform:v4l2loopback-002`
    pub fn bus_info(&self) -> &str {
        byte_array_to_str(&self.0.bus_info)
    }

    /// Returns all capabilities the underlying hardware device exposes.
    ///
    /// Some capabilities might be inaccessible through the opened device node and require opening a
    /// different one.
    pub fn all_capabilities(&self) -> CapabilityFlags {
        self.0.capabilities
    }

    /// Returns the capabilities available through the currently opened device node.
    pub fn device_capabilities(&self) -> CapabilityFlags {
        if self.0.capabilities.contains(CapabilityFlags::DEVICE_CAPS) {
            self.0.device_caps
        } else {
            self.0.capabilities
        }
    }
}

impl fmt::Debug for Capabilities {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Capabilities")
            .field("driver", &self.driver())
            .field("card", &self.card())
            .field("bus_info", &self.bus_info())
            .field("capabilities", &self.0.capabilities)
            .field("device_caps", &self.0.device_caps)
            .finish()
    }
}

/// Iterator over the [`Output`]s of a [`Device`].
pub struct OutputIter<'a> {
    device: &'a Device,
    next_index: u32,
    finished: bool,
}

impl Iterator for OutputIter<'_> {
    type Item = io::Result<Output>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None;
        }

        unsafe {
            let mut raw = raw::Output {
                index: self.next_index,
                ..mem::zeroed()
            };
            match raw::VIDIOC_ENUMOUTPUT.ioctl(self.device, &mut raw) {
                Ok(_) => {}
                Err(e) => {
                    self.finished = true;
                    if e.raw_os_error() == Some(libc::EINVAL as _) {
                        // `EINVAL` indicates the end of the list.
                        return None;
                    } else {
                        return Some(Err(e));
                    }
                }
            }

            self.next_index += 1;

            Some(Ok(Output(raw)))
        }
    }
}

/// Iterator over the [`Input`]s of a [`Device`].
pub struct InputIter<'a> {
    device: &'a Device,
    next_index: u32,
    finished: bool,
}

impl Iterator for InputIter<'_> {
    type Item = io::Result<Input>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None;
        }

        unsafe {
            let mut raw = raw::Input {
                index: self.next_index,
                ..mem::zeroed()
            };
            match raw::VIDIOC_ENUMINPUT.ioctl(self.device, &mut raw) {
                Ok(_) => {}
                Err(e) => {
                    self.finished = true;
                    if e.raw_os_error() == Some(libc::EINVAL as _) {
                        // `EINVAL` indicates the end of the list.
                        return None;
                    } else {
                        return Some(Err(e));
                    }
                }
            }

            self.next_index += 1;

            Some(Ok(Input(raw)))
        }
    }
}

/// Information about a device output.
pub struct Output(raw::Output);

impl Output {
    /// Returns the output's name.
    ///
    /// Examples:
    /// - `loopback in`
    pub fn name(&self) -> &str {
        byte_array_to_str(&self.0.name)
    }

    /// Returns what kind of device this output is.
    #[inline]
    pub fn output_type(&self) -> OutputType {
        self.0.type_
    }

    /// Returns the set of selectable audio sources when this output is active.
    ///
    /// This may return 0 even if the device supports audio inputs to indicate that the application
    /// cannot choose an audio input.
    #[inline]
    pub fn audioset(&self) -> u32 {
        self.0.audioset
    }

    /// Returns the modulator index if this input is of type [`OutputType::MODULATOR`].
    ///
    /// For non-modulator outputs, this value should be ignored.
    #[inline]
    pub fn modulator(&self) -> u32 {
        self.0.modulator
    }

    /// Returns the set of supported analog video standards.
    #[inline]
    pub fn std(&self) -> AnalogStd {
        self.0.std
    }

    /// Returns the capability flags of this output.
    #[inline]
    pub fn capabilities(&self) -> OutputCapabilities {
        self.0.capabilities
    }
}

impl fmt::Debug for Output {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Output")
            .field("index", &self.0.index)
            .field("name", &self.name())
            .field("output_type", &self.output_type())
            .field("audioset", &self.0.audioset)
            .field("modulator", &self.0.modulator)
            .field("std", &self.0.std)
            .field("capabilities", &self.0.capabilities)
            .finish()
    }
}

/// Information about a device input.
pub struct Input(raw::Input);

impl Input {
    /// Returns the name of the input.
    ///
    /// Examples:
    /// - `Camera 1`
    /// - `loopback`
    pub fn name(&self) -> &str {
        byte_array_to_str(&self.0.name)
    }

    /// Returns what kind of device this input is.
    #[inline]
    pub fn input_type(&self) -> InputType {
        self.0.type_
    }

    /// Returns the set of selectable audio sources when this input is active.
    ///
    /// This may return 0 even if the device supports audio inputs to indicate that the application
    /// cannot choose an audio input.
    #[inline]
    pub fn audioset(&self) -> u32 {
        self.0.audioset
    }

    /// Returns the tuner index if this input is of type [`InputType::TUNER`].
    ///
    /// For non-tuner inputs, this value should be ignored.
    #[inline]
    pub fn tuner(&self) -> u32 {
        self.0.tuner
    }

    /// Returns the set of supported analog video standards for this input.
    #[inline]
    pub fn std(&self) -> AnalogStd {
        self.0.std
    }

    /// Returns the current status of the input.
    ///
    /// Note that the input needs to be selected as the active input for most fields in this value
    /// to be valid.
    #[inline]
    pub fn status(&self) -> InputStatus {
        self.0.status
    }

    /// Returns the capability flags of this input.
    #[inline]
    pub fn capabilities(&self) -> InputCapabilities {
        self.0.capabilities
    }
}

impl fmt::Debug for Input {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Input")
            .field("index", &self.0.index)
            .field("name", &self.name())
            .field("input_type", &self.input_type())
            .field("audioset", &self.0.audioset)
            .field("tuner", &self.0.tuner)
            .field("std", &self.0.std)
            .field("status", &self.0.status)
            .field("capabilities", &self.0.capabilities)
            .finish()
    }
}

/// Turns a zero-padded byte array containing UTF-8 or ASCII data into a `&str`.
fn byte_array_to_str(bytes: &[u8]) -> &str {
    let len = bytes
        .iter()
        .position(|b| *b == 0)
        .expect("missing NUL terminator");
    std::str::from_utf8(&bytes[..len]).unwrap()
}