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
/* Copyright (C) 2023 Purism SPC
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

/*! General V4L2 handling */

mod uvc;

use crate::actors::camera_list::CreationKit;
use crate::actors::watcher_udev as udev;
use std::error;
use std::fmt;
use std::io;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use thiserror;
use v4l::buffer;
use v4l::io::dmabuf;

pub type Error = Box<dyn error::Error>;

pub type CameraId = String;

pub struct Config {
    pub fourcc: v4l::FourCC,
    pub width: u32,
    pub height: u32,
}

/// Information about present camera
#[derive(Clone, Debug)]
pub struct CameraInfo {
    /// Information about the device
    pub device: udev::Device,
    /// ID assigned by this library (and the relevant backend)
    pub id: CameraId,
}

impl CameraInfo {
    pub fn is_for_device(&self, d: &udev::Device) -> bool {
        self.device == *d
    }
}

#[derive(thiserror::Error, Debug)]
pub enum AcquireError {
    #[error("Camera already acquired elsewhere")]
    AlreadyAcquired,
    #[error("Other error")]
    Other(())
}

pub type StreamBorrowing = Stream<dmabuf::Stream>;
pub type StreamManual = Stream<dmabuf::StreamManual>;

/// A way to stream buffers
pub struct Stream<T> {
    /// Makes sure that the lock on the camera is being held for the lifetime of the stream,
    /// despite that the dmabuf streaming mechanism doesn't really need anything but the fd.
    /// Without this, it would be possible to acquire the same camera again even as the stream exists, as soon as the original camera goes out of scope.
    // TODO: make it clear that this impl always takes a system-wide exclusive lock over the device.
    camera: Arc<dyn CameraImpl>,
    stream: T,
}

impl StreamManual {
    pub fn finish(self, buf: dmabuf::DmaBufProtected)
        -> Result<(), (io::Error, dmabuf::DmaBufProtected, Self)>
    {
        let camera = self.camera;
        self.stream.finish(buf)
            .map_err(|(e, buf, stream)| (e, buf, Self { camera, stream}))
    }
}

impl<T> fmt::Debug for Stream<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Stream for {:?}", Arc::as_ptr(&self.camera))
    }
}

impl<T> Deref for Stream<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.stream
    }
}
impl<T> DerefMut for Stream<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.stream
    }
}

pub struct AcquiredCamera(CameraId, Arc<dyn CameraImpl>);

impl AcquiredCamera {
    /// Returns globally unique, camera ID, stable for this device and for this software version (ideally for all software versions).
    pub fn get_id(&self) -> &str {
        &self.0
    }
    
    /// Starts recording from the camera
    pub fn start<'b>(&'b mut self, config: Config, buffer_count: usize)
        -> Result<Stream<dmabuf::Stream>, io::Error>
    {
        let camera = &self.1;
        camera.configure(config)?;
        Ok(Stream {
            camera: camera.clone(),
            stream: camera.start(buffer_count)?,
        })
    }
    
    /// Starts recording from the camera with manual buffer management
    pub fn start_manual(&mut self, config: Config, buffer_count: usize)
        -> Result<Stream<dmabuf::StreamManual>, io::Error>
    {
        let camera = &self.1;
        camera.configure(config)?;
        Ok(Stream {
            camera: camera.clone(),
            stream: camera.stream_manual(buffer_count)?,
        })
    }
}

/// A detected camera device
pub struct UnacquiredCamera {
    id: String,
    device: Box<dyn UnacquiredCameraImpl>,
}

impl UnacquiredCamera {
    /// Returns globally unique, camera ID, stable for this device and for this software version (ideally for all software versions).
    pub fn get_id(&self) -> &str {
        &self.id
    }

    // This fn is not &mut because we want to allow the user to query ID regardless of camera state.
    pub fn acquire(self) -> Result<AcquiredCamera, Error> {
        let device = self.device.acquire()?;
        Ok(AcquiredCamera(self.id, device))
    }
}

/// A camera which has been detected, but not yet exclusively acquired for changing.
pub trait UnacquiredCameraImpl {
    /// Locks the camera for exlusive use, including the modification of its state.
    fn acquire(self: Box<Self>) -> Result<Arc<dyn CameraImpl>,  Error>;
}

/// An exclusive handle to a mutable camera resource.
///
/// This is the main trait to fill in by camera vendors, defining all the low-level operations on the camera apart from acquiring.
///
/// Types implementing this impl are required to hold a system-wide exclusive lock over the hardware resource for as long as the instance exists. See `::util::flock::Locked`.
/// TODO: stop streaming when dropped? This is internal API, so maybe the owner type already takes care of stopping.
pub trait CameraImpl: Send + Sync {
    /// Set configuration (TODO: the Config is nearly useless now)
    fn configure(&self, config: Config) -> Result<(), io::Error>;
    
    /// Start streaming
    fn start(&self, buffer_count: usize) -> Result<dmabuf::Stream, io::Error> {
        dmabuf::Stream::with_buffers(
            self.video_capture_device(),
            buffer::Type::VideoCapture,
            buffer_count as u32,
        )
    }
    /// Create a stream with manual buffer control.
    fn stream_manual(&self, buffer_count: usize) -> Result<dmabuf::StreamManual, io::Error> {
        dmabuf::StreamManual::new(
            self.video_capture_device(),
            buffer::Type::VideoCapture,
            buffer_count as u32,
        )
    }

    /// Return the video capture device. Private interface
    fn video_capture_device(&self) -> &v4l::Device;
}

/// This trait is only responsible for releasing the lock when dropped
pub trait Lock {}

pub type Builder = fn(camera: CameraInfo)
    -> Result<UnacquiredCamera, Error>;

pub type CheckFn = for<'a> fn(&'a udev::Device)
    -> Option<CreationKit>;

/// Put the entry function to every supported kind of camera here.
pub const PIPELINES: &'static [CheckFn] = &[
    uvc::Checker::check_match,
];