global hotkeys wired up
This commit is contained in:
+123
-31
@@ -1,15 +1,12 @@
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use windows_capture::capture::{
|
||||
CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler,
|
||||
};
|
||||
|
||||
use crate::CaptureRect;
|
||||
use windows_capture::encoder::{
|
||||
AudioSettingsBuilder, ContainerSettingsBuilder, VideoEncoder, VideoSettingsBuilder,
|
||||
};
|
||||
use windows_capture::frame::Frame;
|
||||
use windows_capture::graphics_capture_api::InternalCaptureControl;
|
||||
use windows_capture::monitor::Monitor;
|
||||
@@ -18,16 +15,27 @@ use windows_capture::settings::{
|
||||
MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
|
||||
};
|
||||
|
||||
use crate::CaptureRect;
|
||||
|
||||
const TARGET_FPS: u32 = 30;
|
||||
const MAX_ENCODE_WIDTH: u32 = 1920;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CaptureSetup {
|
||||
pub output_path: PathBuf,
|
||||
pub ffmpeg_path: PathBuf,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub audio: bool,
|
||||
pub fps: u32,
|
||||
pub crop: Option<CaptureRect>,
|
||||
}
|
||||
|
||||
pub struct CaptureHandler {
|
||||
encoder: Option<VideoEncoder>,
|
||||
stdin: Option<ChildStdin>,
|
||||
child: Option<Child>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
scratch: Vec<u8>,
|
||||
}
|
||||
|
||||
impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
@@ -36,15 +44,60 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
|
||||
fn new(ctx: CaptureContext<Self::Flags>) -> Result<Self, Self::Error> {
|
||||
let setup = ctx.flags;
|
||||
let audio = AudioSettingsBuilder::new().disabled(!setup.audio);
|
||||
let encoder = VideoEncoder::new(
|
||||
VideoSettingsBuilder::new(setup.width, setup.height),
|
||||
audio,
|
||||
ContainerSettingsBuilder::new(),
|
||||
&setup.output_path,
|
||||
)
|
||||
.map_err(|e| anyhow!("video encoder init: {e}"))?;
|
||||
Ok(Self { encoder: Some(encoder) })
|
||||
|
||||
let mut filter_parts: Vec<String> = Vec::new();
|
||||
let working_width = if let Some(c) = setup.crop {
|
||||
let x = c.x.max(0);
|
||||
let y = c.y.max(0);
|
||||
let w = c.width.min(setup.width.saturating_sub(x as u32));
|
||||
let h = c.height.min(setup.height.saturating_sub(y as u32));
|
||||
filter_parts.push(format!("crop={}:{}:{}:{}", w, h, x, y));
|
||||
w
|
||||
} else {
|
||||
setup.width
|
||||
};
|
||||
|
||||
if working_width > MAX_ENCODE_WIDTH {
|
||||
filter_parts.push(format!("scale={}:-2", MAX_ENCODE_WIDTH));
|
||||
} else {
|
||||
filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string());
|
||||
}
|
||||
let filter = filter_parts.join(",");
|
||||
|
||||
let mut cmd = Command::new(&setup.ffmpeg_path);
|
||||
cmd.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.args(["-loglevel", "error"])
|
||||
.args(["-f", "rawvideo"])
|
||||
.args(["-pixel_format", "bgra"])
|
||||
.args(["-video_size", &format!("{}x{}", setup.width, setup.height)])
|
||||
.args(["-framerate", &setup.fps.to_string()])
|
||||
.args(["-i", "-"])
|
||||
.args(["-vf", &filter])
|
||||
.args(["-c:v", "libx264"])
|
||||
.args(["-preset", "ultrafast"])
|
||||
.args(["-tune", "zerolatency"])
|
||||
.args(["-pix_fmt", "yuv420p"])
|
||||
.args(["-movflags", "+faststart"])
|
||||
.arg(&setup.output_path)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
|
||||
let mut child = cmd.spawn().map_err(|e| anyhow!("spawning ffmpeg: {e}"))?;
|
||||
let stdin = child
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("ffmpeg stdin not captured"))?;
|
||||
|
||||
let frame_size = (setup.width as usize) * (setup.height as usize) * 4;
|
||||
Ok(Self {
|
||||
stdin: Some(stdin),
|
||||
child: Some(child),
|
||||
width: setup.width,
|
||||
height: setup.height,
|
||||
scratch: Vec::with_capacity(frame_size),
|
||||
})
|
||||
}
|
||||
|
||||
fn on_frame_arrived(
|
||||
@@ -52,20 +105,31 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
frame: &mut Frame<'_>,
|
||||
_capture_control: InternalCaptureControl,
|
||||
) -> Result<(), Self::Error> {
|
||||
if let Some(enc) = self.encoder.as_mut() {
|
||||
enc.send_frame(frame)
|
||||
.map_err(|e| anyhow!("send frame: {e}"))?;
|
||||
}
|
||||
let Some(stdin) = self.stdin.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let buf = frame
|
||||
.buffer()
|
||||
.map_err(|e| anyhow!("frame buffer: {e:?}"))?;
|
||||
self.scratch.clear();
|
||||
let bytes = buf.as_nopadding_buffer(&mut self.scratch);
|
||||
let expected = (self.width as usize) * (self.height as usize) * 4;
|
||||
let slice = if bytes.len() >= expected {
|
||||
&bytes[..expected]
|
||||
} else {
|
||||
bytes
|
||||
};
|
||||
let _ = stdin.write_all(slice);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CaptureHandler {
|
||||
fn drop(&mut self) {
|
||||
if let Some(enc) = self.encoder.take() {
|
||||
if let Err(e) = enc.finish() {
|
||||
tracing::error!("encoder finish failed: {e}");
|
||||
}
|
||||
drop(self.stdin.take());
|
||||
if let Some(mut child) = self.child.take() {
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,23 +145,30 @@ pub struct CaptureSession {
|
||||
|
||||
pub fn start(
|
||||
output_path: PathBuf,
|
||||
ffmpeg_path: PathBuf,
|
||||
capture_cursor: bool,
|
||||
audio: bool,
|
||||
_audio: bool,
|
||||
crop: Option<CaptureRect>,
|
||||
) -> Result<CaptureSession> {
|
||||
let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?;
|
||||
let width = monitor
|
||||
let raw_width = monitor
|
||||
.width()
|
||||
.map_err(|e| anyhow!("monitor width: {e:?}"))?;
|
||||
let height = monitor
|
||||
let raw_height = monitor
|
||||
.height()
|
||||
.map_err(|e| anyhow!("monitor height: {e:?}"))?;
|
||||
let width = raw_width & !1;
|
||||
let height = raw_height & !1;
|
||||
|
||||
let (out_w, out_h) = compute_output_dims(width, height, crop);
|
||||
|
||||
let setup = CaptureSetup {
|
||||
output_path: output_path.clone(),
|
||||
ffmpeg_path,
|
||||
width,
|
||||
height,
|
||||
audio,
|
||||
fps: TARGET_FPS,
|
||||
crop,
|
||||
};
|
||||
|
||||
let cursor_setting = if capture_cursor {
|
||||
@@ -113,7 +184,7 @@ pub fn start(
|
||||
SecondaryWindowSettings::Default,
|
||||
MinimumUpdateIntervalSettings::Default,
|
||||
DirtyRegionSettings::Default,
|
||||
ColorFormat::Rgba8,
|
||||
ColorFormat::Bgra8,
|
||||
setup,
|
||||
);
|
||||
|
||||
@@ -123,13 +194,34 @@ pub fn start(
|
||||
Ok(CaptureSession {
|
||||
output_path,
|
||||
started_at: Instant::now(),
|
||||
width,
|
||||
height,
|
||||
width: out_w,
|
||||
height: out_h,
|
||||
crop,
|
||||
control,
|
||||
})
|
||||
}
|
||||
|
||||
fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>) -> (u32, u32) {
|
||||
let (raw_w, raw_h) = match crop {
|
||||
Some(c) => {
|
||||
let x = c.x.max(0) as u32;
|
||||
let y = c.y.max(0) as u32;
|
||||
(
|
||||
c.width.min(monitor_w.saturating_sub(x)),
|
||||
c.height.min(monitor_h.saturating_sub(y)),
|
||||
)
|
||||
}
|
||||
None => (monitor_w, monitor_h),
|
||||
};
|
||||
if raw_w > MAX_ENCODE_WIDTH {
|
||||
let scale = MAX_ENCODE_WIDTH as f64 / raw_w as f64;
|
||||
let nh = (raw_h as f64 * scale).round() as u32;
|
||||
(MAX_ENCODE_WIDTH, (nh / 2) * 2)
|
||||
} else {
|
||||
((raw_w / 2) * 2, (raw_h / 2) * 2)
|
||||
}
|
||||
}
|
||||
|
||||
impl CaptureSession {
|
||||
pub fn stop(self) -> Result<PathBuf> {
|
||||
self.control
|
||||
|
||||
Reference in New Issue
Block a user