chalkydri/
cameras.rs

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
use libcamera::{
    camera::{ActiveCamera, CameraConfiguration},
    camera_manager::CameraManager,
    framebuffer::AsFrameBuffer,
    framebuffer_allocator::{FrameBuffer, FrameBufferAllocator},
    framebuffer_map::MemoryMappedFrameBuffer,
    pixel_format::PixelFormat,
    properties,
    request::{Request, ReuseFlag},
    stream::StreamRole,
};
use std::{error::Error, time::Duration};
use yuvutils_rs::{yuv420_to_rgb, YuvPlanarImage, YuvRange, YuvStandardMatrix};

pub fn load_cameras(
    frame_tx: std::sync::mpsc::Sender<Vec<u8>>,
) -> Result<(), Box<dyn Error>> {
    let man = CameraManager::new()?;

    let cameras = man.cameras();

    // TODO: this must not crash the software
    assert!(cameras.len() > 0, "connect a camera");

    let cam = cameras.get(0).unwrap();
    info!("using camera '{}'", cam.id());

    let mut cfgg = cam
        .generate_configuration(&[StreamRole::VideoRecording])
        .unwrap();
    dbg!(&cfgg);
    //       cfgg.get_mut(0).unwrap().set_pixel_format(PixelFormat::new(
    //                u32::from_le_bytes([b'R', b'G', b'B', b'8']),
    //                0,
    //            ));

    let active_cam = cam.acquire().unwrap();

    let mut cw = CamWrapper::new(active_cam, cfgg, frame_tx);
    cw.setup();
    cw.run();

    Ok(())
}

pub struct CamWrapper<'cam> {
    cam: ActiveCamera<'cam>,
    alloc: FrameBufferAllocator,
    frame_tx: std::sync::mpsc::Sender<Vec<u8>>,
    cam_tx: std::sync::mpsc::Sender<Request>,
    cam_rx: std::sync::mpsc::Receiver<Request>,
    configs: CameraConfiguration,
}
impl<'cam> CamWrapper<'cam> {
    /// Wrap an [ActiveCamera]
    pub fn new(
        mut cam: ActiveCamera<'cam>,
        mut cfgg: CameraConfiguration,
        frame_tx: std::sync::mpsc::Sender<Vec<u8>>,
    ) -> Self {
        let alloc = FrameBufferAllocator::new(&cam);
        cam.configure(&mut cfgg).unwrap();

        let (cam_tx, cam_rx) = std::sync::mpsc::channel();

        Self {
            cam,
            alloc,
            frame_tx,
            cam_tx,
            cam_rx,
            configs: cfgg,
        }
    }

    /// Set up the camera and request the first frame
    pub fn setup(&mut self) {
        use libcamera::controls::*;

        let stream = self.configs.get(0).unwrap();
        let stream = stream.stream().unwrap();

        // Allocate some buffers
        let buffers = self
            .alloc
            .alloc(&stream)
            .unwrap()
            .into_iter()
            .map(|buf| MemoryMappedFrameBuffer::new(buf).unwrap())
            .collect::<Vec<_>>();

        let reqs = buffers
            .into_iter()
            .enumerate()
            .map(|(i, buf)| -> Result<Request, Box<dyn Error>> {
                // Create the initial request
                let mut req = self.cam.create_request(Some(i as u64)).unwrap();

                // Set control values for the camera
                {
                    let ctrl = &mut req.controls_mut();

                    // Autofocus
                    (*ctrl).set(AfMode::Auto)?;
                    (*ctrl).set(AfSpeed::Fast)?;
                    (*ctrl).set(AfRange::Full)?;

                    // Autoexposure
                    (*ctrl).set(AeEnable(true))?;
                    // TODO: make autoexposure constraint an option in the config UI
                    // Maybe some logic to automatically set it based on lighting conditions?
                    (*ctrl).set(AeConstraintMode::ConstraintShadows)?;
                    (*ctrl).set(AeMeteringMode::MeteringCentreWeighted)?;
                    (*ctrl).set(FrameDuration(1000i64 / 60i64))?;
                }

                // Add buffer to the request
                req.add_buffer(&stream, buf)?;

                Ok(req)
            })
            .map(|x| x.unwrap())
            .collect::<Vec<_>>();

        let tx = self.cam_tx.clone();
        self.cam.on_request_completed(move |req| {
            tx.send(req).unwrap();
        });

        self.cam.start(None).unwrap();
        for req in reqs {
            self.cam.queue_request(req).unwrap();
        }

        let properties::Model(_model) = self.cam.properties().get::<properties::Model>().unwrap();
    }

    /// Get a frame and request another
    pub fn get_frame(&mut self) {
        let stream = self.configs.get(0).unwrap().stream().unwrap();
        let mut req = self
            .cam_rx
            .recv_timeout(Duration::from_millis(2000))
            .expect("camera request failed");
    
        let framebuffer: &MemoryMappedFrameBuffer<FrameBuffer> = req.buffer(&stream).unwrap();

        let planes = framebuffer.data();
        let plane_metadata = framebuffer.metadata().unwrap().planes();

        let y_plane = planes.get(0).unwrap();
        let u_plane = planes.get(1).unwrap();
        let v_plane = planes.get(2).unwrap();

        let image = YuvPlanarImage {
            width: 1920,
            height: 1080,
            y_plane,
            u_plane,
            v_plane,
            y_stride: 1920,
            u_stride: 960,
            v_stride: 960,
        };

        let mut buff = vec![0u8; 6_220__800];

        yuv420_to_rgb(
            &image,
            &mut buff,
            5760,
            YuvRange::Limited,
            YuvStandardMatrix::Bt601,
        )
        .unwrap();

        self.frame_tx.send(buff).unwrap();
        req.reuse(ReuseFlag::REUSE_BUFFERS);
        self.cam.queue_request(req).unwrap();
    }
    /// Continously request frames until the end of time
    pub fn run(mut self) {
        loop {
            self.get_frame();
        std::thread::sleep(Duration::from_millis(100));
        }
    }
}