To achieve capturing a 480x270 area centered around the mouse pointer at 60fps and sending it to your device, you can use the Windows GDI API to capture the screen area efficiently. Below is the code that accomplishes this task.
First, add the necessary dependencies to your Cargo.toml:
[dependencies]
image = "0.24"
tokio = { version = "1", features = ["full"] }
windows = { version = "0.48", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_UI_WindowsAndMessaging"] }
Now, implement the required functions and the main streaming function:
use std::time::{Duration, Instant};
use tokio::task;
use windows::Win32::Foundation::{HWND, POINT};
use windows::Win32::Graphics::Gdi::{
BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject,
GetDIBits, SelectObject, BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CAPTUREBLT, DIB_RGB_COLORS,
HBITMAP, HDC, SRCCOPY,
};
use windows::Win32::UI::WindowsAndMessaging::{GetCursorPos, ReleaseDC};
use image::{DynamicImage, ImageBuffer, Rgba};
// Function to get the cursor position
fn get_cursor_pos() -> Result<(i32, i32), Box<dyn std::error::Error>> {
unsafe {
let mut point = POINT { x: 0, y: 0 };
if GetCursorPos(&mut point).as_bool() {
Ok((point.x, point.y))
} else {
Err(std::io::Error::last_os_error().into())
}
}
}
// Function to capture a screen area and return it as a DynamicImage
fn capture_screen_area(x: i32, y: i32, width: i32, height: i32) -> Result<DynamicImage, Box<dyn std::error::Error>> {
unsafe {
// Get the device context of the screen
let hdc_screen: HDC = windows::Win32::Graphics::Gdi::GetDC(HWND(0));
if hdc_screen.0 == 0 {
return Err("Failed to get screen DC".into());
}
// Create a compatible DC which is used in a BitBlt from the window DC
let hdc_mem_dc: HDC = CreateCompatibleDC(hdc_screen);
if hdc_mem_dc.0 == 0 {
ReleaseDC(HWND(0), hdc_screen);
return Err("Failed to create compatible DC".into());
}
// Create a compatible bitmap from the Window DC
let hbm_screen: HBITMAP = CreateCompatibleBitmap(hdc_screen, width, height);
if hbm_screen.0 == 0 {
DeleteDC(hdc_mem_dc);
ReleaseDC(HWND(0), hdc_screen);
return Err("Failed to create compatible bitmap".into());
}
// Select the compatible bitmap into the compatible memory DC
let old_bmp = SelectObject(hdc_mem_dc, hbm_screen);
if old_bmp.0 == 0 {
DeleteObject(hbm_screen);
DeleteDC(hdc_mem_dc);
ReleaseDC(HWND(0), hdc_screen);
return Err("Failed to select object into DC".into());
}
// Bit block transfer into our compatible memory DC
if !BitBlt(hdc_mem_dc, 0, 0, width, height, hdc_screen, x, y, SRCCOPY | CAPTUREBLT).as_bool() {
SelectObject(hdc_mem_dc, old_bmp);
DeleteObject(hbm_screen);
DeleteDC(hdc_mem_dc);
ReleaseDC(HWND(0), hdc_screen);
return Err("BitBlt failed".into());
}
// Prepare bitmap info header
let mut bmi = BITMAPINFO {
bmiHeader: BITMAPINFOHEADER {
biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
biWidth: width,
biHeight: -height, // Negative height to indicate a top-down DIB
biPlanes: 1,
biBitCount: 32, // 32 bits per pixel
biCompression: BI_RGB as u32,
..Default::default()
},
..Default::default()
};
// Calculate the image size and create a buffer
let image_size = (width * height * 4) as usize; // 4 bytes per pixel (RGBA)
let mut buffer = vec![0u8; image_size];
// Use GetDIBits to copy the image data into the buffer
if GetDIBits(
hdc_mem_dc,
hbm_screen,
0,
height as u32,
buffer.as_mut_ptr() as *mut _,
&mut bmi,
DIB_RGB_COLORS,
) == 0 {
SelectObject(hdc_mem_dc, old_bmp);
DeleteObject(hbm_screen);
DeleteDC(hdc_mem_dc);
ReleaseDC(HWND(0), hdc_screen);
return Err("GetDIBits failed".into());
}
// Convert the buffer into an ImageBuffer
// The image data is in BGRA format, so we need to convert it to RGBA
let mut image_buffer = ImageBuffer::<Rgba<u8>, _>::from_raw(width as u32, height as u32, buffer)
.ok_or("Failed to create ImageBuffer")?;
for pixel in image_buffer.pixels_mut() {
let Rgba([b, g, r, a]) = *pixel;
*pixel = Rgba([r, g, b, a]);
}
// Convert ImageBuffer to DynamicImage
let image = DynamicImage::ImageRgba8(image_buffer);
// Clean up
SelectObject(hdc_mem_dc, old_bmp);
DeleteObject(hbm_screen);
DeleteDC(hdc_mem_dc);
ReleaseDC(HWND(0), hdc_screen);
Ok(image)
}
}
// The main streaming function
async fn stream_screenshots(control_interface: ControlInterface) -> Result<(), Box<dyn std::error::Error>> {
let frame_duration = Duration::from_secs_f64(1.0 / 60.0);
loop {
let start_time = Instant::now();
// Spawn blocking task to capture and process the image
let result = task::spawn_blocking(|| {
// Get cursor position
let (mouse_x, mouse_y) = get_cursor_pos()?;
// Compute the rectangle to capture
let x = mouse_x - (480 / 2);
let y = mouse_y - (270 / 2);
// Adjust x and y to ensure they are within screen bounds
let x = x.max(0);
let y = y.max(0);
// Capture screen area
let image = capture_screen_area(x, y, 480, 270)?;
// Optionally resize or process the image here if needed
// Convert image to rgb565
let rgb565_data = image_to_rgb565(&image);
Ok::<_, Box<dyn std::error::Error>>(rgb565_data)
})
.await?;
match result {
Ok(rgb565_data) => {
// After getting the data, send it over the channel
let message = MessageType::DrawScreen(rgb565_data);
control_interface.tx_pending_send.send(message).await?;
}
Err(e) => {
eprintln!("Error capturing screen: {}", e);
}
}
// Sleep until the next frame
let elapsed = start_time.elapsed();
if elapsed < frame_duration {
tokio::time::sleep(frame_duration - elapsed).await;
} else {
// We're behind schedule, no delay
}
}
}
Explanation:
- get_cursor_pos: Uses the Windows API to get the current mouse cursor position.
- capture_screen_area: Captures the specified screen area using Windows GDI functions and converts the image data into an
image::DynamicImage.
- It handles the image format conversion from BGRA (Windows default) to RGBA.
- stream_screenshots: An asynchronous function that runs in a loop to capture the screen at 60fps.
- It uses
tokio::task::spawn_blocking to offload the blocking screen capture and processing to a separate thread.
- Captured image data is sent to the device via the
tokio::mpsc::Sender.
- Frame timing is managed to maintain approximately 60fps.
Note:
- Error Handling: Errors are propagated using the
Result type, and any errors during capture or processing are printed to stderr.
- Performance Considerations: Capturing the screen and processing image data can be intensive. Using
spawn_blocking ensures that the asynchronous runtime is not blocked.
- Image Conversion: The captured screen data is converted from BGRA to RGBA format to be compatible with the
image crate and your image_to_rgb565 function.
Usage:
To use the stream_screenshots function, call it from an asynchronous context, such as within #[tokio::main]:
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Setup your ControlInterface and other initialization here
// Start streaming screenshots
stream_screenshots(control_interface).await?;
Ok(())
}
This implementation should efficiently capture the screen area around the mouse pointer at the desired frame rate and send it to your device using the provided channel.