capture, encode, export wiring
This commit is contained in:
+131
-1
@@ -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
@@ -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
@@ -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")
|
||||
|
||||
+340
-60
@@ -1,56 +1,221 @@
|
||||
<script lang="ts">
|
||||
import { api, type Config } from "./api"
|
||||
import { onMount } from "svelte"
|
||||
import {
|
||||
api,
|
||||
formatBytes,
|
||||
type Config,
|
||||
type Format,
|
||||
type RecordedClip,
|
||||
type ExportResult,
|
||||
} from "./api"
|
||||
|
||||
let recording: boolean = $state(false)
|
||||
type Phase = "idle" | "recording" | "editing" | "exporting" | "done"
|
||||
|
||||
let phase: Phase = $state("idle")
|
||||
let config: Config | null = $state(null)
|
||||
let clip: RecordedClip | null = $state(null)
|
||||
let elapsed: number = $state(0)
|
||||
let elapsedTimer: number | null = null
|
||||
|
||||
let format: Format = $state("gif")
|
||||
let keepAudio: boolean = $state(false)
|
||||
let fps: number = $state(30)
|
||||
let targetMB: number = $state(8)
|
||||
let exportResult: ExportResult | null = $state(null)
|
||||
let errMsg: string | null = $state(null)
|
||||
|
||||
onMount(async () => {
|
||||
config = await api.getConfig()
|
||||
format = config.export.default_format
|
||||
fps = config.capture.default_fps
|
||||
keepAudio = config.capture.capture_audio
|
||||
})
|
||||
|
||||
function toggle() {
|
||||
recording = !recording
|
||||
function tick() {
|
||||
elapsedTimer = window.setInterval(() => {
|
||||
elapsed += 0.1
|
||||
}, 100)
|
||||
}
|
||||
|
||||
function clearTick() {
|
||||
if (elapsedTimer !== null) {
|
||||
clearInterval(elapsedTimer)
|
||||
elapsedTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
async function startRec() {
|
||||
errMsg = null
|
||||
elapsed = 0
|
||||
try {
|
||||
await api.startCapture()
|
||||
phase = "recording"
|
||||
tick()
|
||||
} catch (e) {
|
||||
errMsg = String(e)
|
||||
}
|
||||
}
|
||||
|
||||
async function stopRec() {
|
||||
clearTick()
|
||||
try {
|
||||
const c = await api.stopCapture()
|
||||
clip = c
|
||||
phase = "editing"
|
||||
const sensible = Math.max(1, Math.round(c.duration_secs * 0.5))
|
||||
targetMB = Math.min(50, Math.max(minMB(c.duration_secs), sensible))
|
||||
} catch (e) {
|
||||
errMsg = String(e)
|
||||
phase = "idle"
|
||||
}
|
||||
}
|
||||
|
||||
function minMB(durationSecs: number): number {
|
||||
const minBytes = Math.max(50_000, durationSecs * 50_000)
|
||||
return Math.max(0.1, minBytes / 1_048_576)
|
||||
}
|
||||
|
||||
function maxMB(durationSecs: number): number {
|
||||
return Math.min(200, Math.max(10, durationSecs * 5))
|
||||
}
|
||||
|
||||
async function doExport() {
|
||||
if (!clip) return
|
||||
errMsg = null
|
||||
phase = "exporting"
|
||||
try {
|
||||
const result = await api.export({
|
||||
format,
|
||||
target_bytes: Math.round(targetMB * 1_048_576),
|
||||
fps,
|
||||
keep_audio: keepAudio && format !== "gif",
|
||||
})
|
||||
exportResult = result
|
||||
phase = "done"
|
||||
} catch (e) {
|
||||
errMsg = String(e)
|
||||
phase = "editing"
|
||||
}
|
||||
}
|
||||
|
||||
function startOver() {
|
||||
clip = null
|
||||
exportResult = null
|
||||
errMsg = null
|
||||
elapsed = 0
|
||||
phase = "idle"
|
||||
}
|
||||
</script>
|
||||
|
||||
<main>
|
||||
<header>
|
||||
<h1>ByteSize</h1>
|
||||
<p class="sub">ready</p>
|
||||
<p class="sub">
|
||||
{#if phase === "recording"}recording...
|
||||
{:else if phase === "editing"}clip ready
|
||||
{:else if phase === "exporting"}encoding...
|
||||
{:else if phase === "done"}exported
|
||||
{:else}ready{/if}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{#if phase === "idle"}
|
||||
<section class="controls">
|
||||
<button onclick={toggle} class:active={recording}>
|
||||
{recording ? "stop" : "start"}
|
||||
</button>
|
||||
<button class="primary big" onclick={startRec}>start recording</button>
|
||||
</section>
|
||||
<p class="hint">
|
||||
Captures your primary monitor. Region capture and the draggable overlay
|
||||
come next.
|
||||
</p>
|
||||
{:else if phase === "recording"}
|
||||
<section class="recording">
|
||||
<div class="elapsed">{elapsed.toFixed(1)}s</div>
|
||||
<button class="stop big" onclick={stopRec}>stop</button>
|
||||
</section>
|
||||
{:else if phase === "editing" && clip}
|
||||
<section class="clip">
|
||||
<h2>clip</h2>
|
||||
<dl>
|
||||
<dt>duration</dt><dd>{clip.duration_secs.toFixed(2)}s</dd>
|
||||
<dt>dimensions</dt><dd>{clip.width} x {clip.height}</dd>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
{#if config}
|
||||
<section class="cfg">
|
||||
<h2>current settings</h2>
|
||||
<dl>
|
||||
<dt>format</dt>
|
||||
<dd>{config.export.default_format}</dd>
|
||||
<dt>fps</dt>
|
||||
<dd>{config.capture.default_fps}</dd>
|
||||
<dt>cursor</dt>
|
||||
<dd>{config.capture.capture_cursor ? "on" : "off"}</dd>
|
||||
<dt>audio</dt>
|
||||
<dd>{config.capture.capture_audio ? "on" : "off"}</dd>
|
||||
<dt>hotkeys</dt>
|
||||
<dd>
|
||||
start: {config.hotkeys.start ?? "-"} |
|
||||
stop: {config.hotkeys.stop ?? "-"} |
|
||||
pause: {config.hotkeys.pause ?? "-"}
|
||||
</dd>
|
||||
</dl>
|
||||
<section class="export">
|
||||
<h2>export</h2>
|
||||
|
||||
<div class="row">
|
||||
<label class:active={format === "gif"}>
|
||||
<input type="radio" bind:group={format} value="gif" />
|
||||
<span>GIF</span>
|
||||
</label>
|
||||
<label class:active={format === "webm"}>
|
||||
<input type="radio" bind:group={format} value="webm" />
|
||||
<span>WebM</span>
|
||||
</label>
|
||||
<label class:active={format === "mp4"}>
|
||||
<input type="radio" bind:group={format} value="mp4" />
|
||||
<span>MP4</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="slider-row">
|
||||
<label>
|
||||
target size
|
||||
<input
|
||||
type="range"
|
||||
min={minMB(clip.duration_secs)}
|
||||
max={maxMB(clip.duration_secs)}
|
||||
step="0.1"
|
||||
bind:value={targetMB}
|
||||
/>
|
||||
</label>
|
||||
<div class="readout">{targetMB.toFixed(1)} MB</div>
|
||||
</div>
|
||||
|
||||
<div class="grid-row">
|
||||
<label>
|
||||
fps
|
||||
<select bind:value={fps}>
|
||||
<option value={15}>15</option>
|
||||
<option value={24}>24</option>
|
||||
<option value={30}>30</option>
|
||||
<option value={60}>60</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
{#if format !== "gif"}
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" bind:checked={keepAudio} />
|
||||
<span>keep audio</span>
|
||||
</label>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<button class="primary" onclick={doExport}>export</button>
|
||||
<button onclick={startOver}>discard and start over</button>
|
||||
</div>
|
||||
</section>
|
||||
{:else if phase === "exporting"}
|
||||
<section class="exporting">
|
||||
<p>ffmpeg is working...</p>
|
||||
<p class="hint">two-pass encode for target size. usually a few seconds.</p>
|
||||
</section>
|
||||
{:else if phase === "done" && exportResult}
|
||||
<section class="done">
|
||||
<h2>exported</h2>
|
||||
<p class="path">{exportResult.output_path}</p>
|
||||
<p>final size: {formatBytes(exportResult.size_bytes)}</p>
|
||||
<div class="row">
|
||||
<button class="primary" onclick={startOver}>record another</button>
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<p class="hint">
|
||||
capture and encode aren't wired up yet. that's next.
|
||||
</p>
|
||||
{#if errMsg}
|
||||
<p class="err">{errMsg}</p>
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
<style>
|
||||
@@ -69,34 +234,10 @@
|
||||
font-size: 0.875rem;
|
||||
margin: 0 0 1.5rem;
|
||||
}
|
||||
.controls {
|
||||
margin: 1rem 0 2rem;
|
||||
section {
|
||||
margin: 1.25rem 0;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
padding: 0.6rem 1.2rem;
|
||||
border: 1px solid #444;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
font-size: 1rem;
|
||||
}
|
||||
button:hover {
|
||||
border-color: #888;
|
||||
}
|
||||
button.active {
|
||||
background: #c33;
|
||||
border-color: #c33;
|
||||
color: #fff;
|
||||
}
|
||||
.cfg {
|
||||
border: 1px solid #2a2a2a;
|
||||
border-radius: 6px;
|
||||
padding: 1rem 1.25rem;
|
||||
background: #1e1e1e;
|
||||
}
|
||||
.cfg h2 {
|
||||
h2 {
|
||||
margin: 0 0 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
color: #888;
|
||||
@@ -106,8 +247,8 @@
|
||||
}
|
||||
dl {
|
||||
display: grid;
|
||||
grid-template-columns: 100px 1fr;
|
||||
gap: 0.5rem 1rem;
|
||||
grid-template-columns: 110px 1fr;
|
||||
gap: 0.4rem 1rem;
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
@@ -117,9 +258,148 @@
|
||||
dd {
|
||||
margin: 0;
|
||||
}
|
||||
.controls {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-top: 2rem;
|
||||
}
|
||||
.recording {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
.elapsed {
|
||||
font-size: 2.5rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: #4a8;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
padding: 0.5rem 1rem;
|
||||
border: 1px solid #444;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
}
|
||||
button:hover {
|
||||
border-color: #888;
|
||||
}
|
||||
button.primary {
|
||||
background: #4a8;
|
||||
border-color: #4a8;
|
||||
color: #111;
|
||||
}
|
||||
button.primary:hover {
|
||||
background: #5b9;
|
||||
border-color: #5b9;
|
||||
}
|
||||
button.big {
|
||||
padding: 0.75rem 1.75rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
button.stop {
|
||||
background: #c33;
|
||||
border-color: #c33;
|
||||
color: #fff;
|
||||
padding: 0.75rem 2rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
.clip {
|
||||
border: 1px solid #2a2a2a;
|
||||
border-radius: 6px;
|
||||
padding: 1rem 1.25rem;
|
||||
background: #1e1e1e;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
.row label {
|
||||
flex: 1;
|
||||
border: 1px solid #2a2a2a;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
background: #1e1e1e;
|
||||
}
|
||||
.row label.active {
|
||||
border-color: #4a8;
|
||||
background: #1a2a24;
|
||||
}
|
||||
.row label input[type="radio"] {
|
||||
display: none;
|
||||
}
|
||||
.slider-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: 1rem;
|
||||
align-items: center;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
.slider-row label {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
color: #aaa;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.readout {
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 1rem;
|
||||
color: #e8e8e8;
|
||||
min-width: 80px;
|
||||
text-align: right;
|
||||
}
|
||||
input[type="range"] {
|
||||
width: 100%;
|
||||
}
|
||||
.grid-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1rem;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
.grid-row label {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
color: #aaa;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.checkbox {
|
||||
flex-direction: row !important;
|
||||
align-items: center !important;
|
||||
gap: 0.5rem !important;
|
||||
}
|
||||
select {
|
||||
font: inherit;
|
||||
padding: 0.4rem 0.5rem;
|
||||
border: 1px solid #444;
|
||||
background: #222;
|
||||
color: inherit;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.path {
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.85rem;
|
||||
color: #ccc;
|
||||
word-break: break-all;
|
||||
background: #1e1e1e;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.err {
|
||||
color: #ec9a9a;
|
||||
background: #2a1818;
|
||||
padding: 0.6rem 0.75rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.hint {
|
||||
color: #888;
|
||||
font-size: 0.85rem;
|
||||
margin-top: 2rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -49,6 +49,25 @@ export type DownloadProgress = {
|
||||
total: number | null
|
||||
}
|
||||
|
||||
export type RecordedClip = {
|
||||
temp_path: string
|
||||
duration_secs: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export type ExportRequest = {
|
||||
format: Format
|
||||
target_bytes: number
|
||||
fps: number
|
||||
keep_audio: boolean
|
||||
}
|
||||
|
||||
export type ExportResult = {
|
||||
output_path: string
|
||||
size_bytes: number
|
||||
}
|
||||
|
||||
export const api = {
|
||||
getStatus: () => invoke<AppStatus>("get_status"),
|
||||
getConfig: () => invoke<Config>("get_config"),
|
||||
@@ -56,6 +75,9 @@ export const api = {
|
||||
downloadFfmpeg: () => invoke<void>("download_ffmpeg"),
|
||||
onFfmpegProgress: (handler: (p: DownloadProgress) => void): Promise<UnlistenFn> =>
|
||||
listen<DownloadProgress>("ffmpeg-progress", (e) => handler(e.payload)),
|
||||
startCapture: () => invoke<void>("start_capture"),
|
||||
stopCapture: () => invoke<RecordedClip>("stop_capture"),
|
||||
export: (request: ExportRequest) => invoke<ExportResult>("export", { request }),
|
||||
}
|
||||
|
||||
export function formatBytes(n: number): string {
|
||||
|
||||
Reference in New Issue
Block a user