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
//! Video input/output operations for streaming
//!
//! This module provides functionality for reading video streams from various sources
//! including image sequences, video files, and camera devices, along with performance
//! monitoring capabilities.
use super::core::{Frame, FrameMetadata};
use crate::error::Result;
use scirs2_core::ndarray::Array2;
use std::time::{Duration, Instant};
/// Video source type
pub enum VideoSource {
/// Image sequence (directory of images)
ImageSequence(std::path::PathBuf),
/// Video file (requires external decoder)
VideoFile(std::path::PathBuf),
/// Camera device
Camera(u32),
/// Dummy source for testing
Dummy {
/// Frame width in pixels
width: u32,
/// Frame height in pixels
height: u32,
/// Frames per second
fps: f32,
},
}
/// Video reader for streaming
pub struct VideoStreamReader {
source: VideoSource,
frame_count: usize,
fps: f32,
width: u32,
height: u32,
image_files: Option<Vec<std::path::PathBuf>>,
}
impl VideoStreamReader {
/// Create a video reader from a source
pub fn from_source(source: VideoSource) -> Result<Self> {
match source {
VideoSource::ImageSequence(ref path) => {
// Read directory and get sorted list of image files
let mut files = Vec::new();
if path.is_dir() {
for entry in std::fs::read_dir(path).map_err(|e| {
crate::error::VisionError::Other(format!("Failed to read directory: {e}"))
})? {
let entry = entry.map_err(|e| {
crate::error::VisionError::Other(format!("Failed to read entry: {e}"))
})?;
let path = entry.path();
if path.is_file() {
if let Some(ext) = path.extension() {
let ext_str = ext.to_string_lossy().to_lowercase();
if ["jpg", "jpeg", "png", "bmp", "tiff"].contains(&ext_str.as_str())
{
files.push(path);
}
}
}
}
files.sort();
}
if files.is_empty() {
return Err(crate::error::VisionError::Other(
"No image files found in directory".to_string(),
));
}
// Determine dimensions from first image (in real impl, would load and check)
Ok(Self {
source,
frame_count: 0,
fps: 30.0, // Default FPS for image sequences
width: 640, // Default, would read from actual image
height: 480,
image_files: Some(files),
})
}
VideoSource::VideoFile(ref _path) => {
// Would require video decoder integration (ffmpeg, gstreamer, etc.)
Err(crate::error::VisionError::Other(
"Video file reading not yet implemented. Use image sequences instead."
.to_string(),
))
}
VideoSource::Camera(_device_id) => {
// Would require camera API integration
Err(crate::error::VisionError::Other(
"Camera reading not yet implemented. Use image sequences instead.".to_string(),
))
}
VideoSource::Dummy { width, height, fps } => Ok(Self {
source,
frame_count: 0,
fps,
width,
height,
image_files: None,
}),
}
}
/// Create a dummy video reader for testing
pub fn dummy(width: u32, height: u32, fps: f32) -> Self {
Self {
source: VideoSource::Dummy { width, height, fps },
frame_count: 0,
fps,
width,
height,
image_files: None,
}
}
/// Read frames as a stream
pub fn frames(mut self) -> impl Iterator<Item = Frame> {
std::iter::from_fn(move || {
match &self.source {
VideoSource::ImageSequence(_) => {
if let Some(ref files) = self.image_files {
if self.frame_count < files.len() {
// In a real implementation, we would load the image here
// For now, generate a frame with noise to simulate image data
let frame_data = Array2::from_shape_fn(
(self.height as usize, self.width as usize),
|_| scirs2_core::random::random::<f32>(),
);
let frame = Frame {
data: frame_data,
timestamp: Instant::now(),
index: self.frame_count,
metadata: Some(FrameMetadata {
width: self.width,
height: self.height,
fps: self.fps,
channels: 1,
}),
};
self.frame_count += 1;
Some(frame)
} else {
None
}
} else {
None
}
}
VideoSource::Dummy { .. } => {
// Generate synthetic frame
if self.frame_count < 1000 {
// Limit to 1000 frames for testing
let frame_data = Array2::from_shape_fn(
(self.height as usize, self.width as usize),
|(y, x)| {
// Generate a simple pattern that changes over time
let t = self.frame_count as f32 * 0.1;
((x as f32 + y as f32 + t).sin() * 0.5 + 0.5).clamp(0.0, 1.0)
},
);
let frame = Frame {
data: frame_data,
timestamp: Instant::now(),
index: self.frame_count,
metadata: Some(FrameMetadata {
width: self.width,
height: self.height,
fps: self.fps,
channels: 1,
}),
};
self.frame_count += 1;
// Simulate frame rate by adding delay
std::thread::sleep(Duration::from_secs_f32(1.0 / self.fps));
Some(frame)
} else {
None
}
}
VideoSource::VideoFile(_) | VideoSource::Camera(_) => {
// Not implemented yet
None
}
}
})
}
}
/// Simple performance monitor for real-time metrics
pub struct SimplePerformanceMonitor {
frame_times: std::collections::VecDeque<Duration>,
max_samples: usize,
last_frame_time: Option<Instant>,
}
impl SimplePerformanceMonitor {
/// Create a new performance monitor
///
/// # Arguments
///
/// * `max_samples` - Maximum number of frame times to keep for averaging
///
/// # Returns
///
/// * New performance monitor instance
pub fn new(max_samples: usize) -> Self {
Self {
frame_times: std::collections::VecDeque::with_capacity(max_samples),
max_samples,
last_frame_time: None,
}
}
/// Record a new frame processing time
///
/// # Arguments
///
/// * `frame_time` - Processing time for the frame
pub fn record_frame(&mut self, frame_time: Duration) {
self.frame_times.push_back(frame_time);
if self.frame_times.len() > self.max_samples {
self.frame_times.pop_front();
}
self.last_frame_time = Some(Instant::now());
}
/// Get current FPS
pub fn fps(&self) -> f32 {
if self.frame_times.is_empty() {
return 0.0;
}
let avg_duration: Duration =
self.frame_times.iter().sum::<Duration>() / self.frame_times.len() as u32;
1.0 / avg_duration.as_secs_f32()
}
/// Get average latency
pub fn avg_latency(&self) -> Duration {
if self.frame_times.is_empty() {
return Duration::ZERO;
}
self.frame_times.iter().sum::<Duration>() / self.frame_times.len() as u32
}
}