use std::{
io::{self, Write},
time::Instant,
};
use windows_capture::{
capture::{Context, GraphicsCaptureApiHandler},
encoder::{AudioSettingsBuilder, ContainerSettingsBuilder, VideoEncoder, VideoSettingsBuilder},
frame::Frame,
graphics_capture_api::InternalCaptureControl,
monitor::Monitor,
settings::{ColorFormat, CursorCaptureSettings, DrawBorderSettings, Settings},
};
struct Capture {
encoder: Option<VideoEncoder>,
start: Instant,
}
impl GraphicsCaptureApiHandler for Capture {
type Flags = String;
type Error = Box<dyn std::error::Error + Send + Sync>;
fn new(ctx: Context<Self::Flags>) -> Result<Self, Self::Error> {
println!("Created with Flags: {}", ctx.flags);
let encoder = VideoEncoder::new(
VideoSettingsBuilder::new(1920, 1080),
AudioSettingsBuilder::default().disabled(true),
ContainerSettingsBuilder::default(),
"video.mp4",
)?;
Ok(Self {
encoder: Some(encoder),
start: Instant::now(),
})
}
fn on_frame_arrived(
&mut self,
frame: &mut Frame,
capture_control: InternalCaptureControl,
) -> Result<(), Self::Error> {
print!(
"\rRecording for: {} seconds",
self.start.elapsed().as_secs()
);
io::stdout().flush()?;
self.encoder.as_mut().unwrap().send_frame(frame)?;
if self.start.elapsed().as_secs() >= 6 {
self.encoder.take().unwrap().finish()?;
capture_control.stop();
println!();
}
Ok(())
}
fn on_closed(&mut self) -> Result<(), Self::Error> {
println!("Capture session ended");
Ok(())
}
}
fn main() {
let primary_monitor = Monitor::primary().expect("There is no primary monitor");
let settings = Settings::new(
primary_monitor,
CursorCaptureSettings::Default,
DrawBorderSettings::Default,
ColorFormat::Rgba8,
"Yea this works".to_string(),
);
Capture::start(settings).expect("Screen capture failed");
}