Skip to content

Commit 30b5e70

Browse files
committed
Fix demo error
1 parent ad55ca4 commit 30b5e70

File tree

10 files changed

+580
-363
lines changed

10 files changed

+580
-363
lines changed
Lines changed: 86 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,96 +1,100 @@
1-
use ccap::{Provider, Result};
2-
use std::sync::{Arc, Mutex, mpsc};
1+
use ccap::{Provider, Result, Utils, PropertyName, PixelFormat, LogLevel};
2+
use std::sync::{Arc, Mutex};
33
use std::thread;
4-
use std::time::{Duration, Instant};
4+
use std::time::Duration;
55

66
fn main() -> Result<()> {
7-
// Create a camera provider
8-
let mut provider = Provider::new()?;
7+
// Enable verbose log to see debug information
8+
Utils::set_log_level(LogLevel::Verbose);
9+
10+
// Set error callback to receive error notifications
11+
Provider::set_error_callback(|error_code, description| {
12+
eprintln!("Camera Error - Code: {}, Description: {}", error_code, description);
13+
});
14+
15+
let temp_provider = Provider::new()?;
16+
let devices = temp_provider.list_devices()?;
17+
if devices.is_empty() {
18+
eprintln!("No camera devices found!");
19+
return Ok(());
20+
}
21+
22+
for (i, device) in devices.iter().enumerate() {
23+
println!("## Found video capture device: {}: {}", i, device);
24+
}
25+
26+
// Select camera device (automatically use first device for testing)
27+
let device_index = if devices.len() == 1 {
28+
0
29+
} else {
30+
0 // Just use first device for now
31+
};
932

10-
// Open the first available device
33+
// Create provider with selected device
34+
let mut provider = Provider::with_device(device_index as i32)?;
35+
36+
// Set camera properties
37+
let requested_width = 1920;
38+
let requested_height = 1080;
39+
let requested_fps = 60.0;
40+
41+
provider.set_property(PropertyName::Width, requested_width as f64)?;
42+
provider.set_property(PropertyName::Height, requested_height as f64)?;
43+
provider.set_property(PropertyName::PixelFormatOutput, PixelFormat::Bgra32 as u32 as f64)?;
44+
provider.set_property(PropertyName::FrameRate, requested_fps)?;
45+
46+
// Open and start camera
1147
provider.open()?;
12-
println!("Camera opened successfully.");
13-
14-
// Start capture
1548
provider.start()?;
16-
println!("Camera capture started.");
17-
49+
50+
if !provider.is_started() {
51+
eprintln!("Failed to start camera!");
52+
return Ok(());
53+
}
54+
55+
// Get real camera properties
56+
let real_width = provider.get_property(PropertyName::Width)? as i32;
57+
let real_height = provider.get_property(PropertyName::Height)? as i32;
58+
let real_fps = provider.get_property(PropertyName::FrameRate)?;
59+
60+
println!("Camera started successfully, requested resolution: {}x{}, real resolution: {}x{}, requested fps {}, real fps: {}",
61+
requested_width, requested_height, real_width, real_height, requested_fps, real_fps);
62+
63+
// Create directory for captures (using std::fs)
64+
std::fs::create_dir_all("./image_capture").map_err(|e| ccap::CcapError::FileOperationFailed(e.to_string()))?;
65+
1866
// Statistics tracking
1967
let frame_count = Arc::new(Mutex::new(0u32));
20-
let start_time = Arc::new(Mutex::new(Instant::now()));
21-
22-
// Create a channel for communication
23-
let (tx, rx) = mpsc::channel();
24-
25-
// Spawn a thread to continuously grab frames
2668
let frame_count_clone = frame_count.clone();
27-
let start_time_clone = start_time.clone();
28-
29-
thread::spawn(move || {
30-
loop {
31-
// Check for stop signal
32-
match rx.try_recv() {
33-
Ok(_) => break,
34-
Err(mpsc::TryRecvError::Disconnected) => break,
35-
Err(mpsc::TryRecvError::Empty) => {}
36-
}
37-
38-
// Grab frame with timeout
39-
match provider.grab_frame(100) {
40-
Ok(Some(frame)) => {
41-
let mut count = frame_count_clone.lock().unwrap();
42-
*count += 1;
43-
44-
// Print stats every 30 frames
45-
if *count % 30 == 0 {
46-
let elapsed = start_time_clone.lock().unwrap().elapsed();
47-
let fps = *count as f64 / elapsed.as_secs_f64();
48-
49-
println!("Frame {}: {}x{}, format: {:?}, FPS: {:.1}",
50-
*count,
51-
frame.width(),
52-
frame.height(),
53-
frame.pixel_format(),
54-
fps
55-
);
56-
57-
// TODO: Save every 30th frame (saving not yet implemented)
58-
println!("Frame {} captured: {}x{}, format: {:?} (saving not implemented)",
59-
*count, frame.width(), frame.height(), frame.pixel_format());
60-
}
61-
}
62-
Ok(None) => {
63-
// No frame available, continue
64-
}
65-
Err(e) => {
66-
eprintln!("Error grabbing frame: {}", e);
67-
thread::sleep(Duration::from_millis(10));
68-
}
69-
}
69+
70+
// Set frame callback
71+
provider.set_new_frame_callback(move |frame| {
72+
let mut count = frame_count_clone.lock().unwrap();
73+
*count += 1;
74+
75+
println!("VideoFrame {} grabbed: width = {}, height = {}, bytes: {}",
76+
frame.index(), frame.width(), frame.height(), frame.data_size());
77+
78+
// Try to save frame to directory
79+
if let Ok(filename) = Utils::dump_frame_to_directory(frame, "./image_capture") {
80+
println!("VideoFrame saved to: {}", filename);
81+
} else {
82+
eprintln!("Failed to save frame!");
7083
}
71-
72-
println!("Frame grabbing thread stopped.");
73-
});
74-
75-
// Run for 10 seconds
76-
println!("Capturing frames for 10 seconds...");
77-
thread::sleep(Duration::from_secs(10));
78-
79-
// Signal stop
80-
let _ = tx.send(());
81-
82-
// Wait a bit for thread to finish
83-
thread::sleep(Duration::from_millis(100));
84-
85-
// Print final statistics
84+
85+
true // no need to retain the frame
86+
})?;
87+
88+
// Wait for 5 seconds to capture frames
89+
println!("Capturing frames for 5 seconds...");
90+
thread::sleep(Duration::from_secs(5));
91+
92+
// Get final count
8693
let final_count = *frame_count.lock().unwrap();
87-
let total_time = start_time.lock().unwrap().elapsed();
88-
let avg_fps = final_count as f64 / total_time.as_secs_f64();
89-
90-
println!("Capture completed:");
91-
println!(" Total frames: {}", final_count);
92-
println!(" Total time: {:.2}s", total_time.as_secs_f64());
93-
println!(" Average FPS: {:.1}", avg_fps);
94+
println!("Captured {} frames, stopping...", final_count);
9495

96+
// Remove callback before dropping
97+
let _ = provider.remove_new_frame_callback();
98+
9599
Ok(())
96100
}
Lines changed: 52 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,75 +1,65 @@
1-
use ccap::{Provider, Result, PixelFormat};
1+
use ccap::{Provider, Result, PixelFormat, Utils, PropertyName, LogLevel};
2+
use std::fs;
23

34
fn main() -> Result<()> {
5+
// Enable verbose log to see debug information
6+
Utils::set_log_level(LogLevel::Verbose);
7+
8+
// Set error callback to receive error notifications
9+
Provider::set_error_callback(|error_code, description| {
10+
eprintln!("Camera Error - Code: {}, Description: {}", error_code, description);
11+
});
12+
413
// Create a camera provider
514
let mut provider = Provider::new()?;
6-
7-
// List devices
8-
let devices = provider.list_devices()?;
9-
if devices.is_empty() {
10-
eprintln!("No camera devices found.");
15+
16+
// Open default device
17+
provider.open()?;
18+
provider.start_capture()?;
19+
20+
if !provider.is_started() {
21+
eprintln!("Failed to start camera!");
1122
return Ok(());
1223
}
13-
14-
println!("Found {} camera device(s):", devices.len());
15-
for (i, device) in devices.iter().enumerate() {
16-
println!(" {}: {}", i, device);
17-
}
18-
19-
// Open the first device
20-
provider.open_device(Some(&devices[0]), true)?;
21-
println!("Opened device: {}", devices[0]);
22-
23-
// Get device info
24-
let device_info = provider.device_info()?;
25-
println!("Device info:");
26-
println!(" Supported pixel formats: {:?}", device_info.supported_pixel_formats);
27-
println!(" Supported resolutions: {:?}", device_info.supported_resolutions);
28-
29-
// Try to set a common resolution
30-
if let Some(res) = device_info.supported_resolutions.first() {
31-
provider.set_resolution(res.width, res.height)?;
32-
println!("Set resolution to {}x{}", res.width, res.height);
33-
}
34-
35-
// Try to set RGB24 format if supported
36-
if device_info.supported_pixel_formats.contains(&PixelFormat::Rgb24) {
37-
provider.set_pixel_format(PixelFormat::Rgb24)?;
38-
println!("Set pixel format to RGB24");
24+
25+
// Print the real resolution and fps after camera started
26+
let real_width = provider.get_property(PropertyName::Width)? as u32;
27+
let real_height = provider.get_property(PropertyName::Height)? as u32;
28+
let real_fps = provider.get_property(PropertyName::FrameRate)?;
29+
30+
println!("Camera started successfully, real resolution: {}x{}, real fps: {}",
31+
real_width, real_height, real_fps);
32+
33+
// Create capture directory
34+
let capture_dir = "./image_capture";
35+
if !std::path::Path::new(capture_dir).exists() {
36+
fs::create_dir_all(capture_dir)
37+
.map_err(|e| ccap::CcapError::InvalidParameter(format!("Failed to create directory: {}", e)))?;
3938
}
40-
41-
// Print current settings
42-
let resolution = provider.resolution()?;
43-
let pixel_format = provider.pixel_format()?;
44-
let frame_rate = provider.frame_rate()?;
45-
46-
println!("Current settings:");
47-
println!(" Resolution: {}x{}", resolution.0, resolution.1);
48-
println!(" Pixel format: {:?}", pixel_format);
49-
println!(" Frame rate: {:.2} fps", frame_rate);
50-
51-
// Capture and save a frame
52-
println!("Grabbing a frame...");
53-
match provider.grab_frame(2000) {
54-
Ok(Some(frame)) => {
55-
println!("Captured frame: {}x{}, format: {:?}, size: {} bytes",
56-
frame.width(), frame.height(), frame.pixel_format(), frame.data_size());
57-
58-
// TODO: Add frame saving functionality
59-
println!("Frame captured successfully (saving not yet implemented)");
60-
61-
// TODO: Add frame conversion functionality
62-
if frame.pixel_format() != PixelFormat::Rgb24 {
63-
println!("Frame format conversion not yet implemented");
39+
40+
// Capture frames (3000 ms timeout when grabbing frames)
41+
let mut frame_count = 0;
42+
while let Some(frame) = provider.grab_frame(3000)? {
43+
let frame_info = frame.info()?;
44+
println!("VideoFrame {} grabbed: width = {}, height = {}, bytes: {}",
45+
frame_info.frame_index, frame_info.width, frame_info.height, frame_info.size_in_bytes);
46+
47+
// Save frame to directory
48+
match Utils::dump_frame_to_directory(&frame, capture_dir) {
49+
Ok(dump_file) => {
50+
println!("VideoFrame saved to: {}", dump_file);
51+
}
52+
Err(e) => {
53+
eprintln!("Failed to save frame: {}", e);
6454
}
6555
}
66-
Ok(None) => {
67-
println!("No frame available (timeout)");
68-
}
69-
Err(e) => {
70-
eprintln!("Error grabbing frame: {}", e);
56+
57+
frame_count += 1;
58+
if frame_count >= 10 {
59+
println!("Captured 10 frames, stopping...");
60+
break;
7161
}
7262
}
73-
63+
7464
Ok(())
7565
}
Lines changed: 30 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,46 @@
1-
use ccap::{Provider, Result};
2-
use std::thread;
3-
use std::time::Duration;
1+
use ccap::{Provider, Result, Utils};
42

53
fn main() -> Result<()> {
6-
// Create a camera provider and open the first device
7-
let mut provider = Provider::new()?;
4+
// Set error callback to receive error notifications
5+
Provider::set_error_callback(|error_code, description| {
6+
eprintln!("Error occurred - Code: {}, Description: {}", error_code, description);
7+
});
8+
9+
let temp_provider = Provider::new()?;
10+
let devices = temp_provider.list_devices()?;
11+
let camera_index = Utils::select_camera(&devices)?;
812

9-
// Open device with auto-start
13+
// Use device index instead of name to avoid issues
14+
let mut provider = Provider::with_device(camera_index as i32)?;
1015
provider.open()?;
11-
println!("Camera opened successfully.");
12-
13-
// Check if capture is started
14-
if provider.is_started() {
15-
println!("Camera capture started.");
16-
} else {
17-
println!("Starting camera capture...");
18-
provider.start()?;
16+
provider.start()?;
17+
18+
if !provider.is_started() {
19+
eprintln!("Failed to start camera!");
20+
return Ok(());
1921
}
20-
21-
// Capture a few frames
22-
println!("Capturing frames...");
23-
for i in 0..5 {
24-
match provider.grab_frame(1000) {
22+
23+
println!("Camera started successfully.");
24+
25+
// Capture frames
26+
for i in 0..10 {
27+
match provider.grab_frame(3000) {
2528
Ok(Some(frame)) => {
26-
let width = frame.width();
27-
let height = frame.height();
28-
let format = frame.pixel_format();
29-
let data_size = frame.data_size();
30-
31-
println!("Frame {}: {}x{}, format: {:?}, size: {} bytes",
32-
i + 1, width, height, format, data_size);
29+
println!("VideoFrame {} grabbed: width = {}, height = {}, bytes: {}, format: {:?}",
30+
frame.index(), frame.width(), frame.height(), frame.data_size(), frame.pixel_format());
3331
}
3432
Ok(None) => {
35-
println!("Frame {}: No frame available (timeout)", i + 1);
33+
eprintln!("Failed to grab frame {}!", i);
34+
return Ok(());
3635
}
3736
Err(e) => {
38-
eprintln!("Frame {}: Error grabbing frame: {}", i + 1, e);
37+
eprintln!("Error grabbing frame {}: {}", i, e);
38+
return Ok(());
3939
}
4040
}
41-
42-
// Small delay between captures
43-
thread::sleep(Duration::from_millis(100));
4441
}
45-
46-
// Stop capture
42+
43+
println!("Captured 10 frames, stopping...");
4744
let _ = provider.stop();
48-
println!("Camera capture stopped.");
49-
5045
Ok(())
5146
}

0 commit comments

Comments
 (0)