Skip to content

Instantly share code, notes, and snippets.

@raymanfx
Created February 24, 2021 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raymanfx/70c1916d37d3e60af678de2d41176aad to your computer and use it in GitHub Desktop.
Save raymanfx/70c1916d37d3e60af678de2d41176aad to your computer and use it in GitHub Desktop.
use eye::prelude::*;
use minifb::{Window, WindowOptions};
use std::{io, time};
fn main() -> io::Result<()> {
// Query for available devices.
let devices = Context::enumerate_devices();
if devices.is_empty() {
return Err(io::Error::new(io::ErrorKind::Other, "No devices available"));
}
// First, we need a capture device to read images from. For this example, let's just choose
// whatever device is first in the list.
let dev = Device::with_uri(&devices[0])?;
// Explictly request RGB pixelformat, either native or emulated.
let desc = dev.preferred_stream(&|x, y| {
if x.pixfmt == PixelFormat::Rgb(24) && y.pixfmt == PixelFormat::Rgb(24) {
if x.interval > time::Duration::from_millis(33) {
return y;
}
if x.width > y.width {
x
} else {
y
}
} else if x.pixfmt == PixelFormat::Rgb(24) {
x
} else {
y
}
})?;
if desc.pixfmt != PixelFormat::Rgb(24) {
return Err(io::Error::new(
io::ErrorKind::Other,
"Failed to set RGB format",
));
}
println!("Stream: {:?}", desc);
// Since we want to capture images, we need to access the native image stream of the device.
// The backend will internally select a suitable implementation for the platform stream. On
// Linux for example, most devices support memory-mapped buffers.
let mut stream = dev.start_stream(&desc)?;
// Initialize the MiniFB window.
let mut window = Window::new(
&devices[0],
desc.width as usize,
desc.height as usize,
WindowOptions::default(),
)
.unwrap_or_else(|e| {
panic!("{}", e);
});
// Here we create a loop and just capture images as long as the device produces them. Normally,
// this loop will run forever unless we unplug the camera or exit the program.
loop {
let frame = stream.next().expect("Stream is dead")?;
// Convert the pixel data to the 0RGB format required by MiniFB.
let pixels: Vec<u32> = frame
.as_bytes()
.chunks(3)
.map(|rgb| {
let pixel = [0, rgb[0], rgb[1], rgb[2]];
u32::from_be_bytes(pixel)
})
.collect();
window
.update_with_buffer(&pixels, desc.width as usize, desc.height as usize)
.unwrap();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment