summaryrefslogtreecommitdiff
path: root/src/video/mod.rs
blob: 4fbab4fc04062fea71a5d3a5bf3f60d73f53c10a (plain)
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
//! Video backend module for the Geek szitman supercamera

mod pipewire;
mod v4l2;
mod stdout;

pub use pipewire::{PipeWireBackend, PipeWireConfig};
pub use v4l2::V4L2Backend;
pub use stdout::{StdoutBackend, StdoutConfig, HeaderFormat};

use crate::error::{Result, VideoError};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::sync::Mutex;
use tracing::{info};

/// Video backend trait for different video output methods
pub trait VideoBackendTrait: Send + Sync {
    /// Initialize the video backend
    fn initialize(&mut self) -> Result<()>;
    
    /// Push a frame to the video backend
    fn push_frame(&self, frame_data: &[u8]) -> Result<()>;
    
    /// Get backend statistics
    fn get_stats(&self) -> VideoStats;
    
    /// Check if backend is ready
    fn is_ready(&self) -> bool;
    
    /// Shutdown the backend
    fn shutdown(&mut self) -> Result<()>;
}

/// Video backend types
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum VideoBackendType {
    /// PipeWire backend
    PipeWire,
    /// V4L2 backend (for future use)
    V4L2,
    /// Stdout backend for piping to other tools
    Stdout,
}

/// Video backend configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoConfig {
    pub backend_type: VideoBackendType,
    pub width: u32,
    pub height: u32,
    pub fps: u32,
    pub format: VideoFormat,
    pub device_path: Option<String>,
}

impl Default for VideoConfig {
    fn default() -> Self {
        Self {
            backend_type: VideoBackendType::PipeWire,
            width: 640,
            height: 480,
            fps: 30,
            format: VideoFormat::MJPEG,
            device_path: None,
        }
    }
}

/// Video format types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum VideoFormat {
    /// Motion JPEG
    MJPEG,
    /// YUV420
    YUV420,
    /// RGB24
    RGB24,
}

impl VideoFormat {
    /// Get the format name as a string
    pub fn as_str(&self) -> &'static str {
        match self {
            VideoFormat::MJPEG => "MJPEG",
            VideoFormat::YUV420 => "YUV420",
            VideoFormat::RGB24 => "RGB24",
        }
    }

    /// Get the bytes per pixel
    pub fn bytes_per_pixel(&self) -> usize {
        match self {
            VideoFormat::MJPEG => 0, // Variable for MJPEG
            VideoFormat::YUV420 => 1,
            VideoFormat::RGB24 => 3,
        }
    }
}

/// Video statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoStats {
    pub frames_pushed: u64,
    pub frames_dropped: u64,
    pub total_bytes: u64,
    pub fps: f64,
    pub backend_type: VideoBackendType,
    pub is_ready: bool,
}

impl Default for VideoStats {
    fn default() -> Self {
        Self {
            frames_pushed: 0,
            frames_dropped: 0,
            total_bytes: 0,
            fps: 0.0,
            backend_type: VideoBackendType::PipeWire,
            is_ready: false,
        }
    }
}

/// Video backend factory
pub struct VideoBackend;

impl VideoBackend {
    /// Create a new PipeWire backend
    pub fn new_pipewire() -> Result<Box<dyn VideoBackendTrait>> {
        Ok(Box::new(PipeWireBackend::new(PipeWireConfig::default())))
    }

    /// Create a new V4L2 backend (for future use)
    pub fn new_v4l2() -> Result<Box<dyn VideoBackendTrait>> {
        Ok(Box::new(V4L2Backend::new()?))
    }

    /// Create a new stdout backend
    pub fn new_stdout() -> Result<Box<dyn VideoBackendTrait>> {
        Ok(Box::new(StdoutBackend::new()))
    }

    /// Create a backend based on configuration
    pub fn from_config(config: &VideoConfig) -> Result<Box<dyn VideoBackendTrait>> {
        match config.backend_type {
            VideoBackendType::PipeWire => Self::new_pipewire(),
            VideoBackendType::V4L2 => Self::new_v4l2(),
            VideoBackendType::Stdout => Self::new_stdout(),
        }
    }

    /// Create a backend from type
    pub fn from_type(backend_type: VideoBackendType) -> Result<Box<dyn VideoBackendTrait>> {
        match backend_type {
            VideoBackendType::PipeWire => Self::new_pipewire(),
            VideoBackendType::V4L2 => Self::new_v4l2(),
            VideoBackendType::Stdout => Self::new_stdout(),
        }
    }
}

/// Video frame metadata
#[derive(Debug, Clone)]
pub struct VideoFrame {
    pub data: Vec<u8>,
    pub width: u32,
    pub height: u32,
    pub format: VideoFormat,
    pub timestamp: std::time::Instant,
}

impl VideoFrame {
    /// Create a new video frame
    pub fn new(data: Vec<u8>, width: u32, height: u32, format: VideoFormat) -> Self {
        Self {
            data,
            width,
            height,
            format,
            timestamp: std::time::Instant::now(),
        }
    }

    /// Get frame size in bytes
    pub fn size(&self) -> usize {
        self.data.len()
    }

    /// Get frame dimensions
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Check if frame is valid
    pub fn is_valid(&self) -> bool {
        !self.data.is_empty() && self.width > 0 && self.height > 0
    }
}

/// Video backend manager
pub struct VideoBackendManager {
    backend: Arc<Mutex<Box<dyn VideoBackendTrait>>>,
    config: VideoConfig,
    stats: Arc<Mutex<VideoStats>>,
}

impl VideoBackendManager {
    /// Create a new video backend manager
    pub fn new(config: VideoConfig) -> Result<Self> {
        let backend = VideoBackend::from_config(&config)?;
        let stats = Arc::new(Mutex::new(VideoStats::default()));
        
        let manager = Self {
            backend: Arc::new(Mutex::new(backend)),
            config,
            stats,
        };

        // Initialize the backend
        let mut backend_guard = manager.backend.lock().unwrap();
        backend_guard.initialize()?;
        drop(backend_guard);

        Ok(manager)
    }

    /// Push a frame to the video backend
    pub fn push_frame(&self, frame_data: &[u8]) -> Result<()> {
        let backend = self.backend.lock().unwrap();
        
        if !backend.is_ready() {
            return Err(VideoError::DeviceNotReady.into());
        }

        // Update statistics
        let mut stats = self.stats.lock().unwrap();
        stats.frames_pushed += 1;
        stats.total_bytes += frame_data.len() as u64;
        drop(stats);

        // Push frame to backend
        backend.push_frame(frame_data)?;
        
        Ok(())
    }

    /// Get current statistics
    pub fn get_stats(&self) -> VideoStats {
        let stats = self.stats.lock().unwrap();
        stats.clone()
    }

    /// Switch video backend
    pub fn switch_backend(&mut self, new_type: VideoBackendType) -> Result<()> {
        // Shutdown current backend
        let mut backend = self.backend.lock().unwrap();
        backend.shutdown()?;
        drop(backend);

        // Create new backend
        let new_backend = VideoBackend::from_type(new_type)?;
        let mut backend = self.backend.lock().unwrap();
        *backend = new_backend;
        
        // Initialize new backend
        backend.initialize()?;
        
        // Update config
        self.config.backend_type = new_type;
        
        info!("Switched to {:?} backend", new_type);
        Ok(())
    }

    /// Get configuration
    pub fn config(&self) -> &VideoConfig {
        &self.config
    }

    /// Update configuration
    pub fn update_config(&mut self, config: VideoConfig) -> Result<()> {
        // Recreate backend if type changed
        if self.config.backend_type != config.backend_type {
            self.switch_backend(config.backend_type)?;
        }
        
        self.config = config;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_video_backend_factory() {
        // Test PipeWire backend creation
        let pipewire_backend = VideoBackend::new_pipewire();
        assert!(pipewire_backend.is_ok());

        // Test V4L2 backend creation
        let v4l2_backend = VideoBackend::new_v4l2();
        assert!(v4l2_backend.is_ok());
    }

    #[test]
    fn test_video_frame_creation() {
        let frame_data = vec![0u8; 1024];
        let frame = VideoFrame::new(frame_data.clone(), 32, 32, VideoFormat::RGB24);

        assert_eq!(frame.data, frame_data);
        assert_eq!(frame.width, 32);
        assert_eq!(frame.height, 32);
        assert_eq!(frame.format, VideoFormat::RGB24);
        assert!(frame.is_valid());
    }

    #[test]
    fn test_video_format_conversions() {
        assert_eq!(VideoFormat::MJPEG.as_str(), "MJPEG");
        assert_eq!(VideoFormat::YUV420.as_str(), "YUV420");
        assert_eq!(VideoFormat::RGB24.as_str(), "RGB24");

        assert_eq!(VideoFormat::MJPEG.bytes_per_pixel(), 0);
        assert_eq!(VideoFormat::YUV420.bytes_per_pixel(), 1);
        assert_eq!(VideoFormat::RGB24.bytes_per_pixel(), 3);
    }
}