capture, encode, export wiring

This commit is contained in:
2026-05-11 23:54:21 +03:00
parent c64ec2045e
commit 2c041be5a9
5 changed files with 938 additions and 68 deletions
+131 -1
View File
@@ -1 +1,131 @@
// screen capture via windows-capture (Windows Graphics Capture API)
use std::path::PathBuf;
use std::time::Instant;
use anyhow::{anyhow, Result};
use windows_capture::capture::{
CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler,
};
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;
use windows_capture::settings::{
ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings,
MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
};
#[derive(Debug, Clone)]
pub struct CaptureSetup {
pub output_path: PathBuf,
pub width: u32,
pub height: u32,
pub audio: bool,
}
pub struct CaptureHandler {
encoder: Option<VideoEncoder>,
}
impl GraphicsCaptureApiHandler for CaptureHandler {
type Flags = CaptureSetup;
type Error = anyhow::Error;
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) })
}
fn on_frame_arrived(
&mut self,
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}"))?;
}
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}");
}
}
}
}
pub struct CaptureSession {
pub output_path: PathBuf,
pub started_at: Instant,
pub width: u32,
pub height: u32,
control: CaptureControl<CaptureHandler, anyhow::Error>,
}
pub fn start(output_path: PathBuf, capture_cursor: bool, audio: bool) -> Result<CaptureSession> {
let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?;
let width = monitor
.width()
.map_err(|e| anyhow!("monitor width: {e:?}"))?;
let height = monitor
.height()
.map_err(|e| anyhow!("monitor height: {e:?}"))?;
let setup = CaptureSetup {
output_path: output_path.clone(),
width,
height,
audio,
};
let cursor_setting = if capture_cursor {
CursorCaptureSettings::WithCursor
} else {
CursorCaptureSettings::WithoutCursor
};
let settings = Settings::new(
monitor,
cursor_setting,
DrawBorderSettings::Default,
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Default,
DirtyRegionSettings::Default,
ColorFormat::Rgba8,
setup,
);
let control = CaptureHandler::start_free_threaded(settings)
.map_err(|e| anyhow!("capture start: {e}"))?;
Ok(CaptureSession {
output_path,
started_at: Instant::now(),
width,
height,
control,
})
}
impl CaptureSession {
pub fn stop(self) -> Result<PathBuf> {
self.control
.stop()
.map_err(|e| anyhow!("capture stop: {e}"))?;
Ok(self.output_path)
}
}
+225 -1
View File
@@ -1 +1,225 @@
// ffmpeg invocation, target-size encoding logic, codec selection
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{anyhow, bail, Context, Result};
use crate::config::{Format, GifDither, Mp4Codec, WebmCodec};
const AUDIO_BITRATE_KBPS: u64 = 128;
#[derive(Debug, Clone)]
pub struct TranscodeRequest {
pub input: PathBuf,
pub output: PathBuf,
pub format: Format,
pub target_bytes: u64,
pub duration_secs: f64,
pub fps: u32,
pub keep_audio: bool,
pub gif_dither: GifDither,
pub webm_codec: WebmCodec,
pub mp4_codec: Mp4Codec,
pub scratch_dir: PathBuf,
}
pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
if req.duration_secs <= 0.01 {
bail!("clip duration is essentially zero - nothing to encode");
}
std::fs::create_dir_all(&req.scratch_dir).context("creating scratch dir")?;
if let Some(parent) = req.output.parent() {
std::fs::create_dir_all(parent).context("creating output dir")?;
}
match req.format {
Format::Mp4 => two_pass_video(ffmpeg, req, mp4_video_codec(req.mp4_codec), "aac", "mp4"),
Format::Webm => two_pass_video(
ffmpeg,
req,
webm_video_codec(req.webm_codec),
"libopus",
"webm",
),
Format::Gif => encode_gif(ffmpeg, req),
}
}
fn mp4_video_codec(c: Mp4Codec) -> &'static str {
match c {
Mp4Codec::H264 => "libx264",
Mp4Codec::H265 => "libx265",
}
}
fn webm_video_codec(c: WebmCodec) -> &'static str {
match c {
WebmCodec::Vp9 => "libvpx-vp9",
WebmCodec::Av1 => "libsvtav1",
}
}
fn video_bitrate_kbps(req: &TranscodeRequest) -> Result<u64> {
let target_bits = req.target_bytes.saturating_mul(8) as f64;
let audio_bits = if req.keep_audio {
AUDIO_BITRATE_KBPS as f64 * 1000.0 * req.duration_secs
} else {
0.0
};
let video_bits = target_bits - audio_bits;
if video_bits <= 0.0 {
bail!("target size too small to fit audio at {AUDIO_BITRATE_KBPS}k - increase target or strip audio");
}
let kbps = (video_bits / 1000.0 / req.duration_secs).round() as u64;
Ok(kbps.max(16))
}
fn two_pass_video(
ffmpeg: &Path,
req: &TranscodeRequest,
video_codec: &str,
audio_codec: &str,
container: &str,
) -> Result<()> {
let bitrate_kbps = video_bitrate_kbps(req)?;
let bitrate = format!("{bitrate_kbps}k");
let log_stem = req.scratch_dir.join(format!("ffmpeg2pass-{container}"));
let log_stem_str = log_stem
.to_str()
.ok_or_else(|| anyhow!("scratch dir contains non-UTF8"))?;
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
let mut pass1 = Command::new(ffmpeg);
pass1
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input)
.args(["-c:v", video_codec])
.args(["-b:v", &bitrate])
.args(["-pass", "1"])
.args(["-passlogfile", log_stem_str])
.arg("-an")
.args(["-f", container])
.arg(null_target);
run(&mut pass1, "pass 1")?;
let mut pass2 = Command::new(ffmpeg);
pass2
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input)
.args(["-c:v", video_codec])
.args(["-b:v", &bitrate])
.args(["-pass", "2"])
.args(["-passlogfile", log_stem_str]);
if req.keep_audio {
pass2
.args(["-c:a", audio_codec])
.args(["-b:a", &format!("{AUDIO_BITRATE_KBPS}k")]);
} else {
pass2.arg("-an");
}
pass2.arg(&req.output);
run(&mut pass2, "pass 2")?;
cleanup_pass_logs(&log_stem);
Ok(())
}
fn cleanup_pass_logs(stem: &Path) {
let parent = match stem.parent() {
Some(p) => p,
None => return,
};
let prefix = stem.file_name().and_then(OsStr::to_str).unwrap_or("");
if prefix.is_empty() {
return;
}
if let Ok(entries) = std::fs::read_dir(parent) {
for entry in entries.flatten() {
let name = entry.file_name();
if let Some(name_str) = name.to_str() {
if name_str.starts_with(prefix) {
let _ = std::fs::remove_file(entry.path());
}
}
}
}
}
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let palette_path = req.scratch_dir.join("palette.png");
let scale_width = estimate_gif_scale_width(req);
let palettegen_filter = format!(
"fps={fps},scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff",
fps = req.fps,
w = scale_width,
);
let mut gen = Command::new(ffmpeg);
gen.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input)
.args(["-vf", &palettegen_filter])
.arg(&palette_path);
run(&mut gen, "gif palette generation")?;
let dither = match req.gif_dither {
GifDither::FloydSteinberg => "floyd_steinberg",
GifDither::Bayer => "bayer:bayer_scale=3",
GifDither::None => "none",
};
let use_filter = format!(
"fps={fps},scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}",
fps = req.fps,
w = scale_width,
d = dither,
);
let mut encode = Command::new(ffmpeg);
encode
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input)
.arg("-i")
.arg(&palette_path)
.args(["-lavfi", &use_filter])
.args(["-loop", "0"])
.arg(&req.output);
run(&mut encode, "gif encode")?;
let _ = std::fs::remove_file(&palette_path);
Ok(())
}
fn estimate_gif_scale_width(req: &TranscodeRequest) -> u32 {
let bytes_per_pixel_per_frame = 0.5_f64;
let frames = (req.fps as f64 * req.duration_secs).max(1.0);
let budget = req.target_bytes as f64 / (frames * bytes_per_pixel_per_frame);
let aspect = 16.0_f64 / 9.0;
let w = (budget * aspect).sqrt();
let w = w.clamp(120.0, 1280.0).round() as u32;
(w / 2) * 2
}
fn run(cmd: &mut Command, label: &str) -> Result<()> {
let mut printable = OsString::from(label);
printable.push(": ");
printable.push(cmd.get_program());
for arg in cmd.get_args() {
printable.push(" ");
printable.push(arg);
}
tracing::debug!("{}", printable.to_string_lossy());
let status = cmd.status().with_context(|| format!("spawning ffmpeg for {label}"))?;
if !status.success() {
bail!("ffmpeg {label} exited with {status}");
}
Ok(())
}
+219 -5
View File
@@ -3,29 +3,129 @@ mod capture;
mod config;
mod encode;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::Result;
use serde::Serialize;
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, State};
use crate::bootstrap::FfmpegStatus;
use crate::config::Config;
use crate::config::{Config, Format, GifDither, Mp4Codec, WebmCodec};
pub struct AppState {
pub app_dir: PathBuf,
pub config: Mutex<Config>,
pub capture: Mutex<Option<capture::CaptureSession>>,
pub last_clip: Mutex<Option<RecordedClip>>,
}
#[derive(Debug, Clone, Serialize)]
pub struct RecordedClip {
pub temp_path: PathBuf,
pub duration_secs: f64,
pub width: u32,
pub height: u32,
}
fn exe_dir() -> Result<PathBuf> {
let exe = std::env::current_exe()?;
Ok(exe
.parent()
.ok_or_else(|| anyhow::anyhow!("exe has no parent directory"))?
.ok_or_else(|| anyhow!("exe has no parent directory"))?
.to_path_buf())
}
fn temp_dir(app_dir: &Path) -> PathBuf {
app_dir.join("temp")
}
fn output_dir(app_dir: &Path, cfg: &Config) -> PathBuf {
cfg.output_dir
.clone()
.unwrap_or_else(|| app_dir.join("output"))
}
fn timestamp_slug() -> String {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let local = chrono_like(now);
format!(
"{:04}{:02}{:02}-{:02}{:02}{:02}",
local.year, local.month, local.day, local.hour, local.minute, local.second
)
}
struct LocalTime {
year: u32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
}
fn chrono_like(epoch_secs: u64) -> LocalTime {
let seconds_per_day = 86400u64;
let days = epoch_secs / seconds_per_day;
let secs_in_day = epoch_secs % seconds_per_day;
let hour = (secs_in_day / 3600) as u32;
let minute = ((secs_in_day % 3600) / 60) as u32;
let second = (secs_in_day % 60) as u32;
let mut year = 1970u32;
let mut remaining = days as i64;
loop {
let leap = is_leap(year);
let days_in_year = if leap { 366 } else { 365 };
if remaining < days_in_year {
break;
}
remaining -= days_in_year;
year += 1;
}
let leap = is_leap(year);
let month_days: [i64; 12] = [
31,
if leap { 29 } else { 28 },
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
];
let mut month = 1u32;
for d in month_days {
if remaining < d {
break;
}
remaining -= d;
month += 1;
}
let day = remaining as u32 + 1;
LocalTime { year, month, day, hour, minute, second }
}
fn is_leap(year: u32) -> bool {
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
fn ext_for(format: Format) -> &'static str {
match format {
Format::Gif => "gif",
Format::Webm => "webm",
Format::Mp4 => "mp4",
}
}
#[derive(Serialize)]
struct AppStatus {
ffmpeg: FfmpegStatus,
@@ -74,6 +174,115 @@ async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(
.map_err(|e| format!("{e:#}"))
}
#[tauri::command]
fn start_capture(state: State<'_, AppState>) -> Result<(), String> {
let mut slot = state.capture.lock().expect("capture mutex");
if slot.is_some() {
return Err("a capture is already running".to_string());
}
let cfg = state.config.lock().expect("config mutex").clone();
let temp = temp_dir(&state.app_dir);
std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e}"))?;
let output = temp.join("recording.mp4");
let _ = std::fs::remove_file(&output);
let session = capture::start(output, cfg.capture.capture_cursor, cfg.capture.capture_audio)
.map_err(|e| format!("{e:#}"))?;
*slot = Some(session);
Ok(())
}
#[tauri::command]
fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
let session = state
.capture
.lock()
.expect("capture mutex")
.take()
.ok_or_else(|| "no capture in progress".to_string())?;
let duration_secs = session.started_at.elapsed().as_secs_f64();
let width = session.width;
let height = session.height;
let temp_path = session.stop().map_err(|e| format!("{e:#}"))?;
let clip = RecordedClip {
temp_path,
duration_secs,
width,
height,
};
*state.last_clip.lock().expect("clip mutex") = Some(clip.clone());
Ok(clip)
}
#[derive(Debug, Deserialize)]
pub struct ExportRequest {
pub format: Format,
pub target_bytes: u64,
pub fps: u32,
pub keep_audio: bool,
}
#[derive(Debug, Serialize)]
pub struct ExportResult {
pub output_path: PathBuf,
pub size_bytes: u64,
}
#[tauri::command]
fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
let cfg = state.config.lock().expect("config mutex").clone();
let clip = state
.last_clip
.lock()
.expect("clip mutex")
.clone()
.ok_or_else(|| "no recorded clip available".to_string())?;
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
if !ffmpeg.is_file() {
return Err("ffmpeg.exe not found - run the encoder setup first".to_string());
}
let out_dir = output_dir(&state.app_dir, &cfg);
std::fs::create_dir_all(&out_dir).map_err(|e| format!("creating output dir: {e}"))?;
let out_path = out_dir.join(format!(
"bytesize-{}.{}",
timestamp_slug(),
ext_for(request.format)
));
let req = encode::TranscodeRequest {
input: clip.temp_path.clone(),
output: out_path.clone(),
format: request.format,
target_bytes: request.target_bytes,
duration_secs: clip.duration_secs,
fps: request.fps,
keep_audio: request.keep_audio,
gif_dither: cfg.export.gif_dither,
webm_codec: cfg.export.webm_codec,
mp4_codec: cfg.export.mp4_codec,
scratch_dir: temp_dir(&state.app_dir),
};
encode::transcode(&ffmpeg, &req).map_err(|e| format!("{e:#}"))?;
let size_bytes = std::fs::metadata(&out_path)
.map(|m| m.len())
.unwrap_or(0);
Ok(ExportResult {
output_path: out_path,
size_bytes,
})
}
// Suppress dead-code warnings for codec helper functions used only via config.
#[allow(dead_code)]
fn _codec_keepalive() -> (GifDither, WebmCodec, Mp4Codec) {
(GifDither::None, WebmCodec::Vp9, Mp4Codec::H264)
}
pub fn run() {
tracing_subscriber::fmt::init();
@@ -86,6 +295,8 @@ pub fn run() {
let state = AppState {
app_dir,
config: Mutex::new(cfg),
capture: Mutex::new(None),
last_clip: Mutex::new(None),
};
tauri::Builder::default()
@@ -96,6 +307,9 @@ pub fn run() {
get_config,
save_config,
download_ffmpeg,
start_capture,
stop_capture,
export,
])
.run(tauri::generate_context!())
.expect("error while running ByteSize")