Utils

Struct Utils 

Source
pub struct Utils;
Expand description

Utility functions

Implementations§

Source§

impl Utils

Source

pub fn pixel_format_to_string(format: PixelFormat) -> Result<String>

Convert pixel format enum to string

Source

pub fn string_to_pixel_format(format_str: &str) -> Result<PixelFormat>

Convert string to pixel format enum

Source

pub fn save_frame_as_bmp<P: AsRef<Path>>( frame: &VideoFrame, file_path: P, ) -> Result<()>

Save frame as BMP file

Source

pub fn dump_frame_to_file<P: AsRef<Path>>( frame: &VideoFrame, filename_no_suffix: P, ) -> Result<String>

Save a video frame to a file with automatic format detection

Source

pub fn dump_frame_to_directory<P: AsRef<Path>>( frame: &VideoFrame, directory: P, ) -> Result<String>

Save a video frame to directory with auto-generated filename

Examples found in repository?
examples/capture_grab.rs (line 56)
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}
More examples
Hide additional examples
examples/capture_callback.rs (line 87)
6fn main() -> Result<()> {
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!(
13            "Camera Error - Code: {}, Description: {}",
14            error_code, description
15        );
16    });
17
18    let temp_provider = Provider::new()?;
19    let devices = temp_provider.list_devices()?;
20    if devices.is_empty() {
21        eprintln!("No camera devices found!");
22        return Ok(());
23    }
24
25    for (i, device) in devices.iter().enumerate() {
26        println!("## Found video capture device: {}: {}", i, device);
27    }
28
29    // Select camera device (automatically use first device for testing)
30    let device_index = 0;
31
32    // Create provider with selected device
33    let mut provider = Provider::with_device(device_index)?;
34
35    // Set camera properties
36    let requested_width = 1920;
37    let requested_height = 1080;
38    let requested_fps = 60.0;
39
40    provider.set_property(PropertyName::Width, requested_width as f64)?;
41    provider.set_property(PropertyName::Height, requested_height as f64)?;
42    provider.set_property(
43        PropertyName::PixelFormatOutput,
44        PixelFormat::Bgra32 as u32 as f64,
45    )?;
46    provider.set_property(PropertyName::FrameRate, requested_fps)?;
47
48    // Open and start camera
49    provider.open()?;
50    provider.start()?;
51
52    if !provider.is_started() {
53        eprintln!("Failed to start camera!");
54        return Ok(());
55    }
56
57    // Get real camera properties
58    let real_width = provider.get_property(PropertyName::Width)? as i32;
59    let real_height = provider.get_property(PropertyName::Height)? as i32;
60    let real_fps = provider.get_property(PropertyName::FrameRate)?;
61
62    println!("Camera started successfully, requested resolution: {}x{}, real resolution: {}x{}, requested fps {}, real fps: {}",
63             requested_width, requested_height, real_width, real_height, requested_fps, real_fps);
64
65    // Create directory for captures (using std::fs)
66    std::fs::create_dir_all("./image_capture")
67        .map_err(|e| ccap::CcapError::FileOperationFailed(e.to_string()))?;
68
69    // Statistics tracking
70    let frame_count = Arc::new(Mutex::new(0u32));
71    let frame_count_clone = frame_count.clone();
72
73    // Set frame callback
74    provider.set_new_frame_callback(move |frame| {
75        let mut count = frame_count_clone.lock().unwrap();
76        *count += 1;
77
78        println!(
79            "VideoFrame {} grabbed: width = {}, height = {}, bytes: {}",
80            frame.index(),
81            frame.width(),
82            frame.height(),
83            frame.data_size()
84        );
85
86        // Try to save frame to directory
87        if let Ok(filename) = Utils::dump_frame_to_directory(frame, "./image_capture") {
88            println!("VideoFrame saved to: {}", filename);
89        } else {
90            eprintln!("Failed to save frame!");
91        }
92
93        true // no need to retain the frame
94    })?;
95
96    // Wait for 5 seconds to capture frames
97    println!("Capturing frames for 5 seconds...");
98    thread::sleep(Duration::from_secs(5));
99
100    // Get final count
101    let final_count = *frame_count.lock().unwrap();
102    println!("Captured {} frames, stopping...", final_count);
103
104    // Remove callback before dropping
105    let _ = provider.remove_new_frame_callback();
106
107    Ok(())
108}
Source

pub fn save_rgb_data_as_bmp<P: AsRef<Path>>( filename: P, data: &[u8], width: u32, stride: u32, height: u32, is_bgr: bool, has_alpha: bool, is_top_to_bottom: bool, ) -> Result<()>

Save RGB data as BMP file (generic version)

Source

pub fn select_camera(devices: &[String]) -> Result<usize>

Interactive camera selection helper

Examples found in repository?
examples/minimal_example.rs (line 14)
3fn main() -> Result<()> {
4    // Set error callback to receive error notifications
5    Provider::set_error_callback(|error_code, description| {
6        eprintln!(
7            "Error occurred - Code: {}, Description: {}",
8            error_code, description
9        );
10    });
11
12    let temp_provider = Provider::new()?;
13    let devices = temp_provider.list_devices()?;
14    let camera_index = Utils::select_camera(&devices)?;
15
16    // Use device index instead of name to avoid issues
17    let camera_index_i32 = i32::try_from(camera_index).map_err(|_| {
18        CcapError::InvalidParameter(format!(
19            "camera index {} does not fit into i32",
20            camera_index
21        ))
22    })?;
23    let mut provider = Provider::with_device(camera_index_i32)?;
24    provider.open()?;
25    provider.start()?;
26
27    if !provider.is_started() {
28        eprintln!("Failed to start camera!");
29        return Ok(());
30    }
31
32    println!("Camera started successfully.");
33
34    // Capture frames
35    for i in 0..10 {
36        match provider.grab_frame(3000) {
37            Ok(Some(frame)) => {
38                println!(
39                    "VideoFrame {} grabbed: width = {}, height = {}, bytes: {}, format: {:?}",
40                    frame.index(),
41                    frame.width(),
42                    frame.height(),
43                    frame.data_size(),
44                    frame.pixel_format()
45                );
46            }
47            Ok(None) => {
48                eprintln!("Failed to grab frame {}!", i);
49                return Ok(());
50            }
51            Err(e) => {
52                eprintln!("Error grabbing frame {}: {}", i, e);
53                return Ok(());
54            }
55        }
56    }
57
58    println!("Captured 10 frames, stopping...");
59    let _ = provider.stop();
60    Ok(())
61}
Source

pub fn set_log_level(level: LogLevel)

Set log level

Examples found in repository?
examples/print_camera.rs (line 21)
20fn print_camera_info(device_name: &str) -> Result<()> {
21    Utils::set_log_level(LogLevel::Verbose);
22
23    // Create provider with specific device name
24    let provider = match Provider::with_device_name(device_name) {
25        Ok(p) => p,
26        Err(e) => {
27            eprintln!(
28                "### Failed to create provider for device: {}, error: {}",
29                device_name, e
30            );
31            return Ok(());
32        }
33    };
34
35    match provider.device_info() {
36        Ok(device_info) => {
37            println!("===== Info for device: {} =======", device_name);
38
39            println!("  Supported resolutions:");
40            for resolution in &device_info.supported_resolutions {
41                println!("    {}x{}", resolution.width, resolution.height);
42            }
43
44            println!("  Supported pixel formats:");
45            for format in &device_info.supported_pixel_formats {
46                println!("    {}", format.as_str());
47            }
48
49            println!("===== Info end =======\n");
50        }
51        Err(e) => {
52            eprintln!(
53                "Failed to get device info for: {}, error: {}",
54                device_name, e
55            );
56        }
57    }
58
59    Ok(())
60}
More examples
Hide additional examples
examples/capture_grab.rs (line 6)
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}
examples/capture_callback.rs (line 8)
6fn main() -> Result<()> {
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!(
13            "Camera Error - Code: {}, Description: {}",
14            error_code, description
15        );
16    });
17
18    let temp_provider = Provider::new()?;
19    let devices = temp_provider.list_devices()?;
20    if devices.is_empty() {
21        eprintln!("No camera devices found!");
22        return Ok(());
23    }
24
25    for (i, device) in devices.iter().enumerate() {
26        println!("## Found video capture device: {}: {}", i, device);
27    }
28
29    // Select camera device (automatically use first device for testing)
30    let device_index = 0;
31
32    // Create provider with selected device
33    let mut provider = Provider::with_device(device_index)?;
34
35    // Set camera properties
36    let requested_width = 1920;
37    let requested_height = 1080;
38    let requested_fps = 60.0;
39
40    provider.set_property(PropertyName::Width, requested_width as f64)?;
41    provider.set_property(PropertyName::Height, requested_height as f64)?;
42    provider.set_property(
43        PropertyName::PixelFormatOutput,
44        PixelFormat::Bgra32 as u32 as f64,
45    )?;
46    provider.set_property(PropertyName::FrameRate, requested_fps)?;
47
48    // Open and start camera
49    provider.open()?;
50    provider.start()?;
51
52    if !provider.is_started() {
53        eprintln!("Failed to start camera!");
54        return Ok(());
55    }
56
57    // Get real camera properties
58    let real_width = provider.get_property(PropertyName::Width)? as i32;
59    let real_height = provider.get_property(PropertyName::Height)? as i32;
60    let real_fps = provider.get_property(PropertyName::FrameRate)?;
61
62    println!("Camera started successfully, requested resolution: {}x{}, real resolution: {}x{}, requested fps {}, real fps: {}",
63             requested_width, requested_height, real_width, real_height, requested_fps, real_fps);
64
65    // Create directory for captures (using std::fs)
66    std::fs::create_dir_all("./image_capture")
67        .map_err(|e| ccap::CcapError::FileOperationFailed(e.to_string()))?;
68
69    // Statistics tracking
70    let frame_count = Arc::new(Mutex::new(0u32));
71    let frame_count_clone = frame_count.clone();
72
73    // Set frame callback
74    provider.set_new_frame_callback(move |frame| {
75        let mut count = frame_count_clone.lock().unwrap();
76        *count += 1;
77
78        println!(
79            "VideoFrame {} grabbed: width = {}, height = {}, bytes: {}",
80            frame.index(),
81            frame.width(),
82            frame.height(),
83            frame.data_size()
84        );
85
86        // Try to save frame to directory
87        if let Ok(filename) = Utils::dump_frame_to_directory(frame, "./image_capture") {
88            println!("VideoFrame saved to: {}", filename);
89        } else {
90            eprintln!("Failed to save frame!");
91        }
92
93        true // no need to retain the frame
94    })?;
95
96    // Wait for 5 seconds to capture frames
97    println!("Capturing frames for 5 seconds...");
98    thread::sleep(Duration::from_secs(5));
99
100    // Get final count
101    let final_count = *frame_count.lock().unwrap();
102    println!("Captured {} frames, stopping...", final_count);
103
104    // Remove callback before dropping
105    let _ = provider.remove_new_frame_callback();
106
107    Ok(())
108}

Auto Trait Implementations§

§

impl Freeze for Utils

§

impl RefUnwindSafe for Utils

§

impl Send for Utils

§

impl Sync for Utils

§

impl Unpin for Utils

§

impl UnwindSafe for Utils

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.