capture_grab/
capture_grab.rs

1use ccap::{LogLevel, PropertyName, Provider, Result, Utils};
2use std::fs;
3
4fn 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!(
11            "Camera Error - Code: {}, Description: {}",
12            error_code, description
13        );
14    });
15
16    // Create a camera provider
17    let mut provider = Provider::new()?;
18
19    // Open default device
20    provider.open()?;
21    provider.start_capture()?;
22
23    if !provider.is_started() {
24        eprintln!("Failed to start camera!");
25        return Ok(());
26    }
27
28    // Print the real resolution and fps after camera started
29    let real_width = provider.get_property(PropertyName::Width)? as u32;
30    let real_height = provider.get_property(PropertyName::Height)? as u32;
31    let real_fps = provider.get_property(PropertyName::FrameRate)?;
32
33    println!(
34        "Camera started successfully, real resolution: {}x{}, real fps: {}",
35        real_width, real_height, real_fps
36    );
37
38    // Create capture directory
39    let capture_dir = "./image_capture";
40    if !std::path::Path::new(capture_dir).exists() {
41        fs::create_dir_all(capture_dir).map_err(|e| {
42            ccap::CcapError::InvalidParameter(format!("Failed to create directory: {}", e))
43        })?;
44    }
45
46    // Capture frames (3000 ms timeout when grabbing frames)
47    let mut frame_count = 0;
48    while let Some(frame) = provider.grab_frame(3000)? {
49        let frame_info = frame.info()?;
50        println!(
51            "VideoFrame {} grabbed: width = {}, height = {}, bytes: {}",
52            frame_info.frame_index, frame_info.width, frame_info.height, frame_info.size_in_bytes
53        );
54
55        // Save frame to directory
56        match Utils::dump_frame_to_directory(&frame, capture_dir) {
57            Ok(dump_file) => {
58                println!("VideoFrame saved to: {}", dump_file);
59            }
60            Err(e) => {
61                eprintln!("Failed to save frame: {}", e);
62            }
63        }
64
65        frame_count += 1;
66        if frame_count >= 10 {
67            println!("Captured 10 frames, stopping...");
68            break;
69        }
70    }
71
72    Ok(())
73}