separate trim from review and save

This commit is contained in:
2026-10-22 20:33:00 +03:00
parent 271613f6f9
commit b4d1d6c734
13 changed files with 1476 additions and 1742 deletions
+215 -311
View File
@@ -102,7 +102,6 @@ pub(crate) struct TranscodeRequest {
pub crop: Option<CaptureRect>,
pub gif_budget_mode: GifBudgetMode,
pub gif_colors: u16,
pub deleted_frame_indices: Vec<u32>,
pub trim_start_secs: Option<f64>,
pub trim_end_secs: Option<f64>,
pub clicks: Vec<Click>,
@@ -139,15 +138,11 @@ fn click_box(clip_x: i32, clip_y: i32, clip_w: u32, clip_h: u32) -> Option<(i32,
Some((x, y))
}
/// The time `apply_trim` cuts off the head of the clip. A seek rebases the
/// filter graph's timestamps to zero, so anything recorded against clip time -
/// the click highlights - has to be shifted by the same amount or it lands late
/// by the length of the trim.
fn trim_offset(req: &TranscodeRequest) -> f64 {
req.trim_start_secs.filter(|s| *s > 0.001).unwrap_or(0.0)
}
fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32, time_offset: f64) -> Option<String> {
fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32) -> Option<String> {
if clicks.is_empty() {
return None;
}
@@ -169,10 +164,7 @@ fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32, time_offset: f64) -
let Some((x, y)) = click_box(click.x, click.y, clip_w, clip_h) else {
continue;
};
let t = click.time_secs - time_offset;
if t + 0.25 < 0.0 {
continue;
}
let t = click.time_secs;
let t1 = (t - 0.05).max(0.0);
let t2 = t + 0.25;
let color = match click.button {
@@ -202,19 +194,26 @@ fn apply_trim(cmd: &mut Command, req: &TranscodeRequest) {
}
}
fn select_filter_for_deleted(deleted: &[u32]) -> Option<String> {
if deleted.is_empty() {
return None;
fn gif_timeline_filter(req: &TranscodeRequest, effective_fps: u32) -> String {
let mut trim = Vec::new();
if let Some(start) = req.trim_start_secs {
trim.push(format!("start={start}"));
}
if let Some(end) = req.trim_end_secs {
trim.push(format!("end={end}"));
}
let fps = format!("fps={effective_fps}");
if trim.is_empty() {
fps
} else {
format!("trim={},setpts=PTS-STARTPTS,{fps}", trim.join(":"))
}
let parts: Vec<String> = deleted.iter().map(|n| format!("eq(n\\,{n})")).collect();
let expr = parts.join("+");
Some(format!("select='not({expr})',setpts=N/FRAME_RATE/TB"))
}
fn crop_filter(crop: Option<CaptureRect>) -> Option<String> {
crop.map(|c| {
format!(
"crop={w}:{h}:{x}:{y}",
"crop={w}:{h}:{x}:{y}:exact=1",
w = c.width,
h = c.height,
x = c.x.max(0),
@@ -227,6 +226,9 @@ pub(crate) fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
if req.duration_secs <= 0.01 {
bail!("clip duration is essentially zero - nothing to encode");
}
if req.fps == 0 {
bail!("export frame rate must be greater than zero");
}
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")?;
@@ -407,15 +409,14 @@ fn video_bitrate_kbps(req: &TranscodeRequest) -> Result<u64> {
Ok(kbps.max(16))
}
/// Chain the crop and the click highlights into the single `-vf` argument the
/// two video passes share.
fn combined_video_filter(crop: Option<&String>, clicks: Option<&String>) -> Option<String> {
match (crop, clicks) {
(Some(c), Some(k)) => Some(format!("{c},{k}")),
(Some(c), None) => Some(c.clone()),
(None, Some(k)) => Some(k.clone()),
(None, None) => None,
}
fn video_filters(req: &TranscodeRequest) -> String {
let crop = crop_filter(req.crop);
let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height);
[clicks, crop, Some(format!("fps={}", req.fps))]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join(",")
}
fn two_pass_video(
@@ -423,7 +424,7 @@ fn two_pass_video(
req: &TranscodeRequest,
video_codec: &str,
audio_codec: &str,
_container: &str,
container: &str,
) -> Result<()> {
let bitrate_kbps = video_bitrate_kbps(req)?;
let bitrate = format!("{bitrate_kbps}k");
@@ -434,14 +435,7 @@ fn two_pass_video(
.ok_or_else(|| anyhow!("scratch dir contains non-UTF8"))?;
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
let crop = crop_filter(req.crop);
let clicks = click_filters(
&req.clicks,
req.clip_width,
req.clip_height,
trim_offset(req),
);
let combined_vf = combined_video_filter(crop.as_ref(), clicks.as_ref());
let combined_vf = video_filters(req);
let mut pass1 = Command::new(ffmpeg);
pass1
@@ -450,10 +444,8 @@ fn two_pass_video(
.arg("-i")
.arg(&req.input);
apply_trim(&mut pass1, req);
if let Some(c) = &combined_vf {
pass1.args(["-vf", c]);
}
pass1
.args(["-vf", &combined_vf])
.args(["-c:v", video_codec])
.args(["-b:v", &bitrate])
.args(["-pass", "1"])
@@ -464,7 +456,6 @@ fn two_pass_video(
let tx = req.progress_tx.clone();
let dur = req.duration_secs;
let fps = req.fps;
let cancel = req.cancel.clone();
let pass_start = std::time::Instant::now();
run_with_progress(
@@ -473,7 +464,6 @@ fn two_pass_video(
1,
2,
dur,
fps,
tx.as_ref(),
cancel.as_ref(),
)?;
@@ -501,10 +491,8 @@ fn two_pass_video(
.arg("-i")
.arg(&req.input);
apply_trim(&mut pass2, req);
if let Some(c) = &combined_vf {
pass2.args(["-vf", c]);
}
pass2
.args(["-vf", &combined_vf])
.args(["-c:v", video_codec])
.args(["-b:v", &bitrate])
.args(["-pass", "2"])
@@ -516,7 +504,7 @@ fn two_pass_video(
} else {
pass2.arg("-an");
}
pass2.arg(&req.output);
pass2.args(["-abort_on", "empty_output_stream", "-f", container]).arg(&req.output);
let pass_start = std::time::Instant::now();
run_with_progress(
&mut pass2,
@@ -524,7 +512,6 @@ fn two_pass_video(
2,
2,
dur,
fps,
tx.as_ref(),
cancel.as_ref(),
)?;
@@ -567,7 +554,7 @@ fn calibrate_via_sample(
) -> Option<(u32, u32)> {
let sample_path = req.scratch_dir.join("gif-calib-sample.gif");
let sample_dur = 2.0_f64.min(req.duration_secs);
let sample_start = (req.duration_secs / 2.0 - sample_dur / 2.0).max(0.0);
let sample_start = trim_offset(req) + ((req.duration_secs - sample_dur) / 2.0).max(0.0);
// Defer cleanup until we've measured the sample: the guard owns a copy of
// the path, which lets the original move into the request below. Earlier
@@ -582,7 +569,6 @@ fn calibrate_via_sample(
sample_req.output = sample_path;
sample_req.trim_start_secs = Some(sample_start);
sample_req.trim_end_secs = Some(sample_start + sample_dur);
sample_req.deleted_frame_indices.clear();
sample_req.clicks.clear();
sample_req.progress_tx = None;
@@ -598,7 +584,8 @@ fn calibrate_via_sample(
// Back-compute the effective bytes/pixel from the sample. LZW on a short
// clip overstates per-frame cost slightly (less inter-frame reuse) so we
// apply a small correction factor toward the conservative side.
let aspect = aspect_ratio(req.clip_width, req.clip_height);
let (clip_width, clip_height) = req.crop.map_or((req.clip_width, req.clip_height), |r| (r.width, r.height));
let aspect = aspect_ratio(clip_width, clip_height);
let sample_h = round_u32(f64::from(est_width) / aspect);
let frames = (f64::from(est_fps) * sample_dur).max(1.0);
let measured_bpp =
@@ -611,17 +598,20 @@ fn calibrate_via_sample(
let ratio = assumed_bpp / blended_bpp;
// Only recalibrate if the gap is meaningful (>15%). Small gaps aren't
// worth the risk of overshooting on a noisy 2s sample.
if (ratio - 1.0).abs() < 0.15 {
if ratio >= 0.85 {
return None;
}
// Recompute target params with the corrected constant. Scale resolution
// by the sqrt of the ratio so file size scales roughly linearly.
let new_width = (round_u32(f64::from(est_width) * ratio.sqrt()) / 2).max(60) * 2;
let new_fps = round_u32(f64::from(est_fps) * ratio.sqrt())
.max(1)
.min(est_fps);
Some((new_width.min(1280), new_fps))
let (mut width, mut fps) = (est_width, est_fps);
shrink_gif_params(
req.gif_budget_mode,
gif_shrink_factor(req.gif_budget_mode, ratio.min(1.0)),
&mut width,
&mut fps,
);
Some((width, fps))
}
/// Per-mode raw shrink factor (before clamping to 0.6..0.9) given the
@@ -630,8 +620,8 @@ fn calibrate_via_sample(
/// match the dimension it is applied to.
fn gif_shrink_factor(mode: GifBudgetMode, ratio: f64) -> f64 {
match mode {
GifBudgetMode::Resolution => ratio.sqrt(),
GifBudgetMode::Framerate => ratio,
GifBudgetMode::Resolution => ratio,
GifBudgetMode::Framerate => ratio.sqrt(),
GifBudgetMode::Balanced => {
// Split the required reduction between resolution and fps so we
// reduce both proportionally rather than halving resolution alone.
@@ -644,15 +634,17 @@ fn gif_shrink_factor(mode: GifBudgetMode, ratio: f64) -> f64 {
/// keeping the width even (the `*2` after the halving clamp).
fn shrink_gif_params(mode: GifBudgetMode, factor: f64, width: &mut u32, fps: &mut u32) {
match mode {
GifBudgetMode::Resolution => {
GifBudgetMode::Framerate => {
*width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2;
}
GifBudgetMode::Framerate => {
*fps = round_u32(f64::from(*fps) * factor).max(1);
GifBudgetMode::Resolution => {
*fps = round_u32(f64::from(*fps) * factor)
.clamp(1, fps.saturating_sub(1).max(1));
}
GifBudgetMode::Balanced => {
*width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2;
*fps = round_u32(f64::from(*fps) * factor).max(1);
*fps = round_u32(f64::from(*fps) * factor)
.clamp(1, fps.saturating_sub(1).max(1));
}
}
}
@@ -676,7 +668,7 @@ fn gif_calibration(
Some((w, f))
}
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
fn gif_starting_params(req: &TranscodeRequest) -> (u32, u32) {
let budget_input = GifBudgetInput {
gif_colors: req.gif_colors,
target_bytes: req.target_bytes,
@@ -684,8 +676,12 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
duration_secs: req.duration_secs,
gif_budget_mode: req.gif_budget_mode,
};
let (mut scale_width, mut effective_fps) =
gif_params(&budget_input, req.clip_width, req.clip_height);
let (width, height) = req.crop.map_or((req.clip_width, req.clip_height), |r| (r.width, r.height));
gif_params(&budget_input, width, height)
}
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let (mut scale_width, mut effective_fps) = gif_starting_params(req);
// Calibrate the bytes/pixel constant by encoding a short sample first.
// The default 0.2 bytes/pixel assumption varies 3-5x by content; measuring
@@ -715,11 +711,6 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
{
bail!("export cancelled");
}
// Last resort: use minimal settings to hit the target
if attempt == max_retries - 1 {
scale_width = (scale_width / 2).max(60);
effective_fps = 1;
}
let pass_start = std::time::Instant::now();
encode_gif_pass(
ffmpeg,
@@ -781,12 +772,25 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
}
}
let previous = (scale_width, effective_fps);
shrink_gif_params(
req.gif_budget_mode,
factor,
&mut scale_width,
&mut effective_fps,
);
if (scale_width, effective_fps) == previous {
// Try the other setting when the preferred one hits its floor.
let fallback = match req.gif_budget_mode {
GifBudgetMode::Resolution => GifBudgetMode::Framerate,
GifBudgetMode::Framerate | GifBudgetMode::Balanced => GifBudgetMode::Resolution,
};
shrink_gif_params(fallback, gif_shrink_factor(fallback, ratio).clamp(0.6, 0.9),
&mut scale_width, &mut effective_fps);
if (scale_width, effective_fps) == previous {
break;
}
}
tracing::info!(
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps (factor={:.2})",
@@ -811,28 +815,15 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
Ok(())
}
fn encode_gif_pass(
ffmpeg: &Path,
req: &TranscodeRequest,
scale_width: u32,
effective_fps: u32,
attempt: u8,
max_attempts: u8,
) -> Result<()> {
fn gif_filters(req: &TranscodeRequest, scale_width: u32, effective_fps: u32) -> String {
let crop_prefix = crop_filter(req.crop)
.map(|c| format!("{c},"))
.unwrap_or_default();
let click_prefix = click_filters(
&req.clicks,
req.clip_width,
req.clip_height,
trim_offset(req),
)
.map(|c| format!("{c},"))
.unwrap_or_default();
let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices)
.map(|s| format!("{s},"))
let click_prefix = click_filters(&req.clicks, req.clip_width, req.clip_height)
.map(|c| format!("{c},"))
.unwrap_or_default();
let timeline = gif_timeline_filter(req, effective_fps);
let stats = "diff";
let dither = match req.gif_dither {
GifDither::FloydSteinberg => "floyd_steinberg",
@@ -843,16 +834,26 @@ fn encode_gif_pass(
// Single-pass approach: split the stream, generate palette from one copy,
// apply palette to the other. The fps filter handles frame rate conversion.
let scale = gif_rgb_scale_filter(scale_width);
let filter_complex = format!(
"{cprefix}{kprefix}fps={fps},{sprefix}{scale},split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors={colors}[p];[s1][p]paletteuse=dither={d}",
let colors = req.gif_colors;
let reserve = u8::from(colors > 2);
format!(
"{kprefix}{cprefix}{timeline},{scale},split[s0][s1];[s0]palettegen=stats_mode={stats}:max_colors={colors}:reserve_transparent={reserve}[p];[s1][p]paletteuse=dither={d}",
cprefix = crop_prefix,
kprefix = click_prefix,
sprefix = select_prefix,
fps = effective_fps,
scale = scale,
colors = req.gif_colors,
d = dither,
);
)
}
fn encode_gif_pass(
ffmpeg: &Path,
req: &TranscodeRequest,
scale_width: u32,
effective_fps: u32,
attempt: u8,
max_attempts: u8,
) -> Result<()> {
let filter_complex = gif_filters(req, scale_width, effective_fps);
tracing::info!(
"gif encode: fps={effective_fps} scale={scale_width} colors={} filter={filter_complex}",
@@ -865,10 +866,10 @@ fn encode_gif_pass(
.arg("-hide_banner")
.arg("-i")
.arg(&req.input);
apply_trim(&mut encode, req);
encode
.args(["-filter_complex", &filter_complex])
.args(["-loop", "0"])
.args(["-abort_on", "empty_output", "-f", "gif"])
.arg(&req.output);
run_with_progress(
&mut encode,
@@ -876,7 +877,6 @@ fn encode_gif_pass(
attempt,
max_attempts,
req.duration_secs,
effective_fps,
req.progress_tx.as_ref(),
req.cancel.as_ref(),
)?;
@@ -886,7 +886,7 @@ fn encode_gif_pass(
fn gif_rgb_scale_filter(width: u32) -> String {
format!(
"scale={width}:-1:flags=lanczos:in_color_matrix=bt709:in_range=tv:in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb:out_range=pc,format=rgb24"
"scale={width}:-1:flags=lanczos:in_color_matrix=bt709:in_range=tv:out_range=pc:in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb,format=rgb24"
)
}
@@ -970,181 +970,69 @@ pub(crate) fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32
}
}
pub(crate) fn render_preview(
ffmpeg: &Path,
input: &Path,
out_path: &Path,
midpoint_secs: f64,
target_width: u32,
) -> Result<()> {
if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent).context("creating preview parent")?;
}
let scale_filter = format!("scale={target_width}:-2");
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.args(["-ss", &format!("{midpoint_secs}")])
.arg("-i")
.arg(input)
.args(["-vf", &scale_filter])
.args(["-frames:v", "1"])
.arg(out_path);
run(&mut cmd, "preview render")
#[derive(Clone, Copy, Debug, serde::Serialize)]
pub(crate) struct OutputProperties {
pub width: u32,
pub height: u32,
pub fps: f64,
pub duration_secs: f64,
}
/// Render a GIF preview with actual palette and dithering applied.
/// Generates a palette from the full clip, then applies it to a single frame.
// Every argument is a distinct knob the caller already has in hand; bundling
// them into a struct would only move the same list one level up.
#[allow(
clippy::too_many_arguments,
reason = "flat parameter list mirrors the preview request fields the caller owns"
)]
pub(crate) fn render_gif_preview(
ffmpeg: &Path,
input: &Path,
out_path: &Path,
midpoint_secs: f64,
target_width: u32,
gif_colors: u16,
gif_dither: &str,
duration_secs: f64,
) -> Result<()> {
if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent).context("creating preview parent")?;
}
// The palette depends only on gif_colors and the sampled frame range, not
// on target_bytes or dither. Cache it keyed on those inputs so slider
// drags (which change target_bytes) skip the expensive palettegen pass.
let sample_start = (midpoint_secs - 1.0).max(0.0);
let sample_dur = duration_secs.min(2.0);
let palette_key = palette_cache_key(gif_colors, target_width, sample_start, sample_dur);
// The preview and its input both live in the scratch dir, so the preview's
// parent is the normal case. Fall back to the input's parent rather than
// panicking on a bare filename.
let palette_dir = out_path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.or_else(|| input.parent().filter(|p| !p.as_os_str().is_empty()))
.context("preview palette has no parent directory")?;
let palette_path = palette_dir.join(format!("preview-palette-{palette_key}.png"));
let need_regen = !palette_path.is_file();
if need_regen {
// Drop any stale palettes from previous inputs so temp doesn't grow.
clean_stale_palettes(palette_path.parent().unwrap_or(Path::new(".")));
let palette_filter = format!(
"{},palettegen=stats_mode=diff:max_colors={}",
gif_rgb_scale_filter(target_width),
gif_colors
);
let mut gen = Command::new(ffmpeg);
gen.arg("-y")
.arg("-hide_banner")
.args(["-ss", &format!("{sample_start}")])
.args(["-t", &format!("{sample_dur}")])
.arg("-i")
.arg(input)
.args(["-vf", &palette_filter])
.arg(&palette_path);
run(&mut gen, "gif preview palette")?;
}
// Apply palette to the target frame
let use_filter = format!(
"{}[x];[x][1:v]paletteuse=dither={}",
gif_rgb_scale_filter(target_width),
gif_dither
);
let mut encode = Command::new(ffmpeg);
encode
.arg("-y")
.arg("-hide_banner")
.args(["-ss", &format!("{midpoint_secs}")])
.arg("-i")
.arg(input)
.arg("-i")
.arg(&palette_path)
.args(["-lavfi", &use_filter])
.args(["-frames:v", "1"])
.arg(out_path);
// The palette is deliberately left in place: the cache key above exists so a
// render with the same inputs can skip palettegen entirely, and deleting it
// here meant every render regenerated it. clear_temp_segments sweeps
// preview-palette-*.png between recordings, and clean_stale_palettes drops
// the keys that no longer apply.
run(&mut encode, "gif preview encode")
}
/// Build a stable cache key for a GIF preview palette from the inputs that
/// actually affect palettegen output. Same inputs -> same palette.
fn palette_cache_key(
gif_colors: u16,
target_width: u32,
sample_start: f64,
sample_dur: f64,
) -> String {
format!("c{gif_colors}-w{target_width}-s{sample_start:.3}-d{sample_dur:.3}")
}
/// Remove old `preview-palette-*.png` files so only the current key remains.
fn clean_stale_palettes(dir: &Path) {
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
// Case-insensitive for the same reason as the temp sweep: these
// are the app's own files, but Windows keeps the case it was given.
let is_png = Path::new(name)
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("png"));
if name.starts_with("preview-palette-") && is_png {
drop(std::fs::remove_file(entry.path()));
}
}
}
}
}
pub(crate) fn extract_thumbnails(
ffmpeg: &Path,
input: &Path,
out_dir: &Path,
fps: u32,
crop: Option<CaptureRect>,
) -> Result<Vec<PathBuf>> {
std::fs::create_dir_all(out_dir).context("creating thumbnails dir")?;
for entry in std::fs::read_dir(out_dir).into_iter().flatten().flatten() {
drop(std::fs::remove_file(entry.path()));
}
let crop_prefix = crop_filter(crop)
.map(|c| format!("{c},"))
.unwrap_or_default();
let filter = format!("{crop_prefix}fps={fps},scale=120:-1:flags=lanczos");
let pattern = out_dir.join("thumb-%05d.png");
/// Inspect packet timing without decoding the video.
pub(crate) fn inspect_output(ffmpeg: &Path, path: &Path) -> Result<OutputProperties> {
use std::os::windows::process::CommandExt;
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
let mut cmd = Command::new(ffmpeg);
cmd.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(input)
.args(["-vf", &filter])
.arg(&pattern);
run(&mut cmd, "thumbnail extraction")?;
let output = cmd
.creation_flags(CREATE_NO_WINDOW.0)
.args(["-v", "error", "-nostdin", "-i"])
.arg(path)
.args(["-map", "0:v:0", "-c:v", "copy", "-f", "framecrc", "pipe:1"])
.output()
.context("reading rendered output details")?;
if !output.status.success() {
bail!(ffmpeg_failure_message("reading output details", output.status, &output.stderr));
}
parse_output_properties(&String::from_utf8_lossy(&output.stdout))
.ok_or_else(|| anyhow!("could not read the output dimensions or frame timing"))
}
let mut paths: Vec<PathBuf> = std::fs::read_dir(out_dir)?
.flatten()
.map(|e| e.path())
.filter(|p| {
p.extension().and_then(|s| s.to_str()) == Some("png")
&& p.file_name()
.and_then(|s| s.to_str())
.is_some_and(|s| s.starts_with("thumb-"))
})
.collect();
paths.sort();
Ok(paths)
fn parse_output_properties(report: &str) -> Option<OutputProperties> {
let (width, height) = report.lines()
.find_map(|line| line.strip_prefix("#dimensions 0: "))?.trim().split_once('x')?;
let (tick, timescale) = report.lines()
.find_map(|line| line.strip_prefix("#tb 0: "))?.trim().split_once('/')?;
let mut first = f64::INFINITY;
let mut end = f64::NEG_INFINITY;
let mut frames = 0u32;
for line in report.lines().filter(|line| line.starts_with('0')) {
let mut columns = line.split(',').skip(2);
let pts = columns.next()?.trim().parse::<f64>().ok()?;
let duration = columns.next()?.trim().parse::<f64>().ok()?;
first = first.min(pts);
end = end.max(pts + duration);
frames += 1;
}
let duration_secs = (end - first) * tick.parse::<f64>().ok()? / timescale.parse::<f64>().ok()?;
if !duration_secs.is_finite() || duration_secs <= 0.0 { return None; }
Some(OutputProperties {
width: width.parse().ok()?, height: height.parse().ok()?,
fps: f64::from(frames) / duration_secs, duration_secs,
})
}
pub(crate) fn timeline_thumbnails(ffmpeg: &Path, input: &Path, out_dir: &Path, seconds: f64) -> Result<Vec<PathBuf>> {
if !seconds.is_finite() || seconds <= 0.0 {
bail!("invalid clip duration for the timeline");
}
std::fs::create_dir_all(out_dir).context("creating timeline thumbnail folder")?;
let filter = format!("fps={:.6},scale=160:-2", (8.0 / seconds).min(120.0));
let mut cmd = Command::new(ffmpeg);
cmd.args(["-y", "-hide_banner", "-i"]).arg(input)
.args(["-vf", &filter, "-frames:v", "8"]).arg(out_dir.join("frame-%02d.jpg"));
run(&mut cmd, "timeline thumbnails")?;
Ok((1..=8).map(|i| out_dir.join(format!("frame-{i:02}.jpg"))).filter(|path| path.is_file()).collect())
}
pub(crate) fn display_preview(ffmpeg: &Path, x: i32, y: i32, width: u32, height: u32) -> Result<Vec<u8>> {
@@ -1351,7 +1239,7 @@ pub(crate) fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path
}
fn run(cmd: &mut Command, label: &str) -> Result<()> {
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None, false)?;
let output = run_impl(cmd, label, 0, 0, 0.0, None, None, false)?;
if !output.status.success() {
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
}
@@ -1362,19 +1250,12 @@ fn run(cmd: &mut Command, label: &str) -> Result<()> {
/// `progress_tx`, if provided, receives (pass, `total_passes`, percent) updates
/// driven by ffmpeg's stable key=value output (`out_time_us`) rather than
/// fragile stderr line parsing.
// Thin forwarder to run_impl, which needs the same list; a params struct here
// would just be reconstructed at each of the four call sites.
#[allow(
clippy::too_many_arguments,
reason = "thin forwarder for the ffmpeg invocation; callers already hold these as locals"
)]
fn run_with_progress(
cmd: &mut Command,
label: &str,
pass: u8,
total_passes: u8,
duration_secs: f64,
fps: u32,
progress_tx: Option<&Sender<EncodeProgress>>,
cancel: Option<&Arc<AtomicBool>>,
) -> Result<()> {
@@ -1387,7 +1268,6 @@ fn run_with_progress(
pass,
total_passes,
duration_secs,
fps,
progress_tx.cloned(),
cancel.cloned(),
true,
@@ -1452,7 +1332,6 @@ fn run_impl(
progress_pass: u8,
progress_total_passes: u8,
progress_duration_secs: f64,
_progress_fps: u32,
progress_tx: Option<Sender<EncodeProgress>>,
cancel: Option<Arc<AtomicBool>>,
read_stdout: bool,
@@ -1588,6 +1467,17 @@ mod tests {
use super::*;
#[test]
fn review_properties_use_muxed_frame_timing() {
let properties = parse_output_properties(concat!(
"#tb 0: 1/100\n#dimensions 0: 128x96\n",
"0, 0, 4, 3, 42, 0x00\n0, 3, 0, 4, 42, 0x00\n0, 6, 7, 3, 42, 0x00\n",
)).unwrap();
assert_eq!((properties.width, properties.height), (128, 96));
assert!((properties.duration_secs - 0.1).abs() < 0.000_001);
assert!((properties.fps - 30.0).abs() < 0.000_001);
}
fn dummy_request() -> TranscodeRequest {
let dir = std::env::temp_dir().join(format!("bytesize-encode-test-{}", std::process::id()));
TranscodeRequest {
@@ -1605,7 +1495,6 @@ mod tests {
crop: None,
gif_budget_mode: GifBudgetMode::Balanced,
gif_colors: 256,
deleted_frame_indices: vec![],
trim_start_secs: None,
trim_end_secs: None,
clicks: vec![],
@@ -1701,6 +1590,36 @@ mod tests {
assert!(filter.contains("format=rgb24"));
}
#[test]
fn audio_alignment_pads_whole_sample_frames_and_preserves_retry_gaps() {
let dir = std::env::temp_dir();
let id = std::process::id();
let first = TempFileGuard(dir.join(format!("bytesize-align-{id}-first.pcm")));
let retry = TempFileGuard(dir.join(format!("bytesize-align-{id}-retry.pcm")));
let out = TempFileGuard(dir.join(format!("bytesize-align-{id}-output.pcm")));
let pcm = |samples: &[f32]| {
samples.iter().copied().flat_map(f32::to_le_bytes).collect::<Vec<_>>()
};
std::fs::write(&first.0, pcm(&[0.1, 0.2, 0.3, 0.4])).unwrap();
std::fs::write(&retry.0, pcm(&[0.5, 0.6, 0.7, 0.8])).unwrap();
let segments = [
AudioSegment {
path: first.0.clone(), sample_rate: 10, channels: 2, start_secs: 0.12, end_secs: 0.3,
},
AudioSegment {
path: retry.0.clone(), sample_rate: 10, channels: 2, start_secs: 0.48, end_secs: 0.6,
},
];
assert_eq!(
assemble_pcm(Path::new("ffmpeg"), &segments, &out.0, 0.7).unwrap(),
Some((10, 2)),
);
assert_eq!(
std::fs::read(&out.0).unwrap(),
pcm(&[0., 0., 0.1, 0.2, 0.3, 0.4, 0., 0., 0., 0., 0.5, 0.6, 0., 0.]),
);
}
#[test]
fn crop_filter_output() {
let rect = CaptureRect {
@@ -1711,7 +1630,7 @@ mod tests {
};
assert_eq!(
crop_filter(Some(rect)),
Some("crop=100:200:10:20".to_string())
Some("crop=100:200:10:20:exact=1".to_string())
);
assert_eq!(crop_filter(None), None);
}
@@ -1726,7 +1645,7 @@ mod tests {
button: crate::clicks::MouseButton::Left,
})
.collect();
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
let filter = click_filters(&clicks, 1920, 1080).unwrap();
let count = filter.matches("drawbox").count();
assert_eq!(count, MAX_CLICK_HIGHLIGHTS);
}
@@ -1771,7 +1690,7 @@ mod tests {
button: crate::clicks::MouseButton::Left,
},
];
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
let filter = click_filters(&clicks, 1920, 1080).unwrap();
assert_eq!(filter.matches("drawbox").count(), 1);
assert!(filter.contains("x=488:y=388"));
// Every emitted box must be non-negative, or drawbox throws it away.
@@ -1779,48 +1698,33 @@ mod tests {
assert!(!filter.contains("y=-"));
}
/// A trim seeks past the head of the clip, which rebases the filter timeline
/// to zero, so a click recorded against clip time has to move back by the
/// same amount or it fires late by the length of the trim.
#[test]
fn click_times_are_rebased_by_the_trim() {
let clicks = vec![Click {
fn click_geometry_and_time_use_the_source_before_crop_and_trim() {
let mut req = dummy_request();
req.crop = Some(CaptureRect { x: 400, y: 300, width: 520, height: 380 });
req.trim_start_secs = Some(5.0);
req.clicks = vec![Click {
time_secs: 6.0,
x: 500,
y: 400,
button: crate::clicks::MouseButton::Left,
}];
let untrimmed = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
assert!(untrimmed.contains("between(t,5.950,6.250)"));
let trimmed = click_filters(&clicks, 1920, 1080, 5.0).unwrap();
assert!(trimmed.contains("between(t,0.950,1.250)"));
assert!(!trimmed.contains("6.250"));
}
/// A click that happened before the trimmed window has nothing left to draw.
#[test]
fn clicks_before_the_trim_are_dropped() {
let clicks = vec![Click {
time_secs: 1.0,
x: 500,
y: 400,
button: crate::clicks::MouseButton::Left,
}];
assert!(click_filters(&clicks, 1920, 1080, 5.0).is_none());
let filters = video_filters(&req);
assert!(filters.starts_with("drawbox=x=488:y=388:"));
assert!(filters.contains("between(t,5.950,6.250)"));
assert!(filters.ends_with(",crop=520:380:400:300:exact=1,fps=30"));
}
#[test]
fn gif_shrink_factor_resolution_uses_sqrt() {
// ratio 0.25 -> halving the *width* (which quarters pixels) needs sqrt(0.25)=0.5
let f = gif_shrink_factor(GifBudgetMode::Resolution, 0.25);
assert!((f - 0.5).abs() < 1e-9);
}
fn gif_budget_retries_preserve_the_selected_priority() {
let (mut width, mut fps) = (800, 20);
let mode = GifBudgetMode::Resolution;
shrink_gif_params(mode, gif_shrink_factor(mode, 0.5), &mut width, &mut fps);
assert_eq!((width, fps), (800, 10));
#[test]
fn gif_shrink_factor_framerate_is_linear() {
// ratio 0.5 -> halving fps needs factor 0.5
let f = gif_shrink_factor(GifBudgetMode::Framerate, 0.5);
assert!((f - 0.5).abs() < 1e-9);
let mode = GifBudgetMode::Framerate;
shrink_gif_params(mode, gif_shrink_factor(mode, 0.25), &mut width, &mut fps);
assert_eq!((width, fps), (400, 10));
}
#[test]
+419 -248
View File
@@ -67,9 +67,9 @@ pub struct AppState {
capture_transition: Mutex<()>,
pub picker: Mutex<Option<window_picker::PickerSession>>,
pub overlay_poll_shutdown: Arc<AtomicBool>,
pub export_cancel: Arc<AtomicBool>,
pub exporting: Arc<AtomicBool>,
encode_operation: Mutex<Option<Arc<AtomicBool>>>,
thumbnail_operation: Mutex<()>,
reviewed_output: Mutex<Option<ReviewedOutput>>,
pub overlay_aspect_ratio: Mutex<Option<f64>>,
/// (active flag, condvar) so the overlay click-through poll thread can park
/// itself when no overlay is on screen instead of waking every 80ms.
@@ -137,7 +137,7 @@ fn timestamp_slug() -> String {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
.as_millis()
.to_string()
}
@@ -304,7 +304,7 @@ async fn download_update(
fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
if state.capture_transition.try_lock().is_err()
|| lock(&state.session).is_some()
|| state.exporting.load(Ordering::SeqCst)
|| lock(&state.encode_operation).is_some()
|| state.unexported_clip.load(Ordering::Relaxed)
{
return Err("finish or discard the current recording before applying the update".to_string());
@@ -463,7 +463,7 @@ fn start_capture(
request: Option<StartCaptureRequest>,
) -> Result<(), String> {
let _transition = state.begin_capture_transition()?;
if state.exporting.load(Ordering::SeqCst) {
if lock(&state.encode_operation).is_some() {
return Err("wait for the current output operation".to_string());
}
{
@@ -480,6 +480,7 @@ fn start_capture(
let _thumbnails = state.thumbnail_operation.try_lock()
.map_err(|_| "wait for thumbnail generation to finish".to_string())?;
*lock(&state.last_clip) = None;
*lock(&state.reviewed_output) = None;
state.unexported_clip.store(false, Ordering::Relaxed);
clear_temp_segments(&state.app_dir, true);
@@ -770,10 +771,11 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
#[tauri::command]
fn discard_clip(state: State<'_, AppState>) -> Result<(), String> {
let _transition = state.begin_capture_transition()?;
if state.exporting.load(Ordering::SeqCst) {
if lock(&state.encode_operation).is_some() {
return Err("wait for the current preview or export".to_string());
}
*lock(&state.last_clip) = None;
*lock(&state.reviewed_output) = None;
state.unexported_clip.store(false, Ordering::Relaxed);
Ok(())
}
@@ -785,14 +787,14 @@ pub struct ExportRequest {
pub fps: u32,
pub keep_audio: bool,
#[serde(default)]
pub deleted_frame_indices: Vec<u32>,
#[serde(default)]
pub trim_start_secs: Option<f64>,
#[serde(default)]
pub trim_end_secs: Option<f64>,
#[serde(default)]
pub output_path: Option<String>,
#[serde(default)]
pub overwrite: bool,
#[serde(default)]
pub crop: Option<CaptureRect>,
#[serde(default)]
pub gif_budget_mode: GifBudgetMode,
@@ -803,11 +805,8 @@ pub struct ExportRequest {
}
#[tauri::command]
fn default_output_path(state: State<'_, AppState>, format: Format) -> String {
let dir = output_dir(&state.app_dir, &lock(&state.config));
dir.join(format!("bytesize-{}.{}", timestamp_slug(), ext_for(format)))
.to_string_lossy()
.into_owned()
fn default_output_path(state: State<'_, AppState>, format: Format) -> Result<PathBuf, String> {
export_path(&state, format, None)
}
#[derive(Debug, Deserialize)]
@@ -821,8 +820,6 @@ pub struct PreviewRequest {
pub gif_dither: Option<GifDither>,
#[serde(default)]
pub gif_colors: Option<u16>,
/// Optional clip dimensions/duration. Required by `estimate_gif_params`,
/// unused by `render_preview` (which uses the current `last_clip`).
#[serde(default)]
pub clip_width: u32,
#[serde(default)]
@@ -831,62 +828,6 @@ pub struct PreviewRequest {
pub duration_secs: Option<f64>,
}
#[tauri::command(async)]
fn render_preview(state: State<'_, AppState>, request: PreviewRequest) -> Result<PathBuf, String> {
let clip = lock(&state.last_clip)
.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".to_string());
}
let target_width: u32 = if request.format == Format::Gif {
let budget = encode::GifBudgetInput {
gif_colors: request.gif_colors.unwrap_or(256),
target_bytes: request.target_bytes,
fps: request.fps,
duration_secs: clip.duration_secs,
gif_budget_mode: request.gif_budget_mode,
};
let (w, _) = encode::gif_params(&budget, clip.width, clip.height);
w
} else {
clip.width.clamp(160, 1280)
};
let preview_path = temp_dir(&state.app_dir).join("preview.png");
let midpoint = (clip.duration_secs / 2.0).max(0.0);
if request.format == Format::Gif {
let dither_str = match request.gif_dither.unwrap_or(GifDither::FloydSteinberg) {
GifDither::FloydSteinberg => "floyd_steinberg",
GifDither::Bayer => "bayer:bayer_scale=3",
GifDither::None => "none",
};
encode::render_gif_preview(
&ffmpeg,
&clip.temp_path,
&preview_path,
midpoint,
target_width,
request.gif_colors.unwrap_or(256),
dither_str,
clip.duration_secs,
)
.map_err(|e| format!("{e:#}"))?;
} else {
encode::render_preview(
&ffmpeg,
&clip.temp_path,
&preview_path,
midpoint,
target_width,
)
.map_err(|e| format!("{e:#}"))?;
}
Ok(preview_path)
}
#[derive(Debug, Serialize)]
pub struct GifEstimate {
pub width: u32,
@@ -1003,6 +944,103 @@ mod tests {
use super::*;
#[test]
fn export_preserves_existing_file_until_authorized_publish() -> Result<()> {
let dir = std::env::temp_dir().join(format!("bytesize-export-test-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let old = encode::TempFileGuard(dir.join("output.mp4"));
std::fs::write(&old.0, b"existing")?;
let staged = encode::TempFileGuard::create_in(&dir, "export", "tmp")?;
std::fs::write(&staged.0, b"new export")?;
assert!(publish_export(&staged.0, &old.0, false).is_err());
assert_eq!(std::fs::read(&old.0)?, b"existing");
publish_export(&staged.0, &old.0, true)?;
assert_eq!(std::fs::read(&old.0)?, b"new export");
drop((old, staged));
std::fs::remove_dir(dir)?;
Ok(())
}
#[test]
fn saving_reviewed_output_preserves_preview_bytes_and_keeps_the_preview() -> Result<()> {
let dir = std::env::temp_dir().join(format!("bytesize-review-test-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let artifact = encode::TempFileGuard::create_in(&dir, "output-review", "gif")?;
let encoded = b"GIF89a\x80\x00\x60\x00\x00\xff\x01\x3b";
std::fs::write(&artifact.0, encoded)?;
let preview = OutputPreview {
id: "reviewed-file".to_string(), path: artifact.0.clone(), format: Format::Gif,
size_bytes: encoded.len() as u64, target_bytes: 1024,
media: encode::OutputProperties { width: 128, height: 96, fps: 5.0, duration_secs: 1.0 },
};
let staging = encode::TempFileGuard::create_in(&dir, "export", "tmp")?;
let destination = encode::TempFileGuard::create_in(&dir, "saved", "gif")?;
std::fs::write(&destination.0, b"existing output")?;
assert!(copy_reviewed_file(&preview, &staging.0, &destination.0, false).is_err());
assert_eq!(std::fs::read(&destination.0)?, b"existing output");
copy_reviewed_file(&preview, &staging.0, &destination.0, true)?;
assert_eq!(std::fs::read(&destination.0)?, encoded);
assert_eq!(std::fs::read(&artifact.0)?, encoded);
drop((artifact, staging, destination));
std::fs::remove_dir(dir)?;
Ok(())
}
#[test]
#[ignore = "requires an FFmpeg build with H.264 and VP9; set BYTESIZE_TEST_FFMPEG"]
fn encodes_inspects_and_saves_reviewed_media() -> Result<()> {
let ffmpeg = std::env::var_os("BYTESIZE_TEST_FFMPEG").map(PathBuf::from)
.ok_or_else(|| anyhow!("set BYTESIZE_TEST_FFMPEG to ffmpeg.exe"))?;
let dir = std::env::temp_dir().join(format!("bytesize-media-review-test-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let source = encode::TempFileGuard::create_in(&dir, "sample", "mp4")?;
let status = std::process::Command::new(&ffmpeg)
.args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=128x96:rate=10:duration=2", "-c:v", "libx264"])
.arg(&source.0).status()?;
anyhow::ensure!(status.success(), "could not generate sample video");
for format in [Format::Gif, Format::Mp4, Format::Webm] {
let artifact = encode::TempFileGuard::create_in(&dir, "output-review", ext_for(format))?;
let req = encode::TranscodeRequest {
input: source.0.clone(), output: artifact.0.clone(), format, target_bytes: 102_400,
duration_secs: 1.0, fps: 10, keep_audio: false, gif_colors: 128,
gif_dither: GifDither::Bayer, gif_budget_mode: GifBudgetMode::Balanced,
webm_codec: config::WebmCodec::Vp9, mp4_codec: config::Mp4Codec::H264,
scratch_dir: dir.clone(), crop: None,
trim_start_secs: Some(0.3), trim_end_secs: Some(1.3),
clicks: Vec::new(), clip_width: 128, clip_height: 96, progress_tx: None, cancel: None,
};
encode::transcode(&ffmpeg, &req)?;
let media = encode::inspect_output(&ffmpeg, &artifact.0)?;
assert!(media.width > 0 && media.height > 0 && media.fps > 0.0);
assert!((media.duration_secs - 1.0).abs() < 0.15, "{format:?}: {media:?}");
let preview = OutputPreview {
id: "review".to_string(), path: artifact.0.clone(), format,
size_bytes: std::fs::metadata(&artifact.0)?.len(), target_bytes: req.target_bytes, media,
};
let staging = encode::TempFileGuard::create_in(&dir, "export", "tmp")?;
let output = encode::TempFileGuard::create_in(&dir, "saved", ext_for(format))?;
copy_reviewed_file(&preview, &staging.0, &output.0, true)?;
assert_eq!(std::fs::read(&output.0)?, std::fs::read(&artifact.0)?);
}
drop(source);
std::fs::remove_dir(dir)?;
Ok(())
}
#[test]
fn a_second_instance_cannot_lock_the_same_folder() -> Result<()> {
let dir = std::env::temp_dir().join(format!("bytesize-lock-test-{}", std::process::id()));
let first = lock_instance(&dir)?;
assert!(lock_instance(&dir).is_err());
drop(first);
drop(lock_instance(&dir)?);
let temp = temp_dir(&dir);
std::fs::remove_file(temp.join("instance.lock"))?;
std::fs::remove_dir(temp)?;
std::fs::remove_dir(dir)?;
Ok(())
}
fn make_request(target_bytes: u64, fps: u32, mode: GifBudgetMode) -> PreviewRequest {
PreviewRequest {
format: Format::Gif,
@@ -1117,39 +1155,13 @@ mod tests {
}
#[tauri::command(async)]
fn extract_thumbnails(state: State<'_, AppState>, fps: u32) -> Result<Vec<PathBuf>, String> {
let _thumbnails = lock(&state.thumbnail_operation);
let clip = lock(&state.last_clip)
.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".to_string());
}
let thumbs_dir = temp_dir(&state.app_dir).join("thumbs");
encode::extract_thumbnails(&ffmpeg, &clip.temp_path, &thumbs_dir, fps, clip.crop)
.map_err(|e| format!("{e:#}"))
}
#[tauri::command(async)]
fn render_raw_preview(state: State<'_, AppState>, timestamp: f64) -> Result<PathBuf, String> {
let clip = lock(&state.last_clip)
.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".to_string());
}
let out_path = temp_dir(&state.app_dir).join("raw-preview.png");
encode::render_preview(
&ffmpeg,
&clip.temp_path,
&out_path,
timestamp,
clip.width.min(1280),
)
.map_err(|e| format!("{e:#}"))?;
Ok(out_path)
fn timeline_thumbnails(state: State<'_, AppState>) -> Result<Vec<PathBuf>, String> {
let _page = lock(&state.thumbnail_operation);
let clip = lock(&state.last_clip).clone().ok_or_else(|| "no recorded clip available".to_string())?;
let clip_name = clip.temp_path.file_stem().ok_or_else(|| "invalid clip file name".to_string())?;
let dir = temp_dir(&state.app_dir).join("thumbs").join("timeline").join(clip_name);
encode::timeline_thumbnails(&bootstrap::ffmpeg_path(&state.app_dir), &clip.temp_path, &dir, clip.duration_secs)
.map_err(|error| format!("{error:#}"))
}
#[tauri::command(async)]
@@ -1172,6 +1184,23 @@ pub struct ExportResult {
pub met_target: bool,
}
#[derive(Clone, Serialize)]
struct OutputPreview {
id: String,
path: PathBuf,
format: Format,
size_bytes: u64,
target_bytes: u64,
#[serde(flatten)]
media: encode::OutputProperties,
}
struct ReviewedOutput {
preview: OutputPreview,
source: PathBuf,
_file: encode::TempFileGuard,
}
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 44.0;
const OVERLAY_TOOLBAR_WIDTH_LOGICAL_PX: f64 = 380.0;
@@ -1185,7 +1214,6 @@ fn cleanup_temp_on_exit(app: &AppHandle) {
clear_temp_segments(&st.app_dir, false);
}
/// Keep click-through decisions in the poller so its cached state stays current.
fn lock_instance(app_dir: &Path) -> std::io::Result<std::fs::File> {
use std::os::windows::fs::OpenOptionsExt;
@@ -1210,7 +1238,7 @@ fn close_main(window: &tauri::Window) {
let app = window.app_handle();
let owner = window.hwnd().ok().map(|handle| HWND(handle.0));
let transitioning = state.capture_transition.try_lock().is_err();
if transitioning || lock(&state.session).is_some() || state.exporting.load(Ordering::SeqCst)
if transitioning || lock(&state.session).is_some() || lock(&state.encode_operation).is_some()
|| state.thumbnail_operation.try_lock().is_err()
{
// SAFETY: The owner is the main window. Both strings have static storage.
@@ -1770,6 +1798,15 @@ fn reveal_in_explorer(path: String) -> Result<(), String> {
Ok(())
}
#[tauri::command]
fn open_url(url: String) -> Result<(), String> {
let url = reqwest::Url::parse(&url).map_err(|e| format!("invalid URL: {e}"))?;
if !matches!(url.scheme(), "http" | "https") || !url.has_host() {
return Err("only http/https URLs are supported".to_string());
}
open_shell_target(std::ffi::OsStr::new(url.as_str()))
}
fn open_shell_target(target: &std::ffi::OsStr) -> Result<(), String> {
use windows::core::{w, HSTRING, PCWSTR};
use windows::Win32::UI::Shell::ShellExecuteW;
@@ -1795,15 +1832,6 @@ fn open_shell_target(target: &std::ffi::OsStr) -> Result<(), String> {
Ok(())
}
#[tauri::command]
fn open_url(url: String) -> Result<(), String> {
let url = reqwest::Url::parse(&url).map_err(|e| format!("invalid URL: {e}"))?;
if !matches!(url.scheme(), "http" | "https") || !url.has_host() {
return Err("only http/https URLs are supported".to_string());
}
open_shell_target(std::ffi::OsStr::new(url.as_str()))
}
#[derive(Debug, Serialize)]
pub struct DiagnosticsInfo {
pub app_version: String,
@@ -1892,7 +1920,9 @@ fn open_log_dir(state: State<'_, AppState>) -> Result<(), String> {
#[tauri::command]
fn cancel_export(state: State<'_, AppState>) {
state.export_cancel.store(true, Ordering::SeqCst);
if let Some(cancel) = lock(&state.encode_operation).as_ref() {
cancel.store(true, Ordering::SeqCst);
}
}
#[tauri::command(async)]
@@ -1910,161 +1940,303 @@ fn codec_availability(state: State<'_, AppState>) -> Result<encode::CodecAvailab
Ok(encode::codec_availability(&ffmpeg))
}
/// Clears the export flag on every exit path, including the `?` returns below.
struct ExportGuard(Arc<AtomicBool>);
struct EncodeOperation<'a> {
slot: &'a Mutex<Option<Arc<AtomicBool>>>,
cancel: Arc<AtomicBool>,
}
impl Drop for ExportGuard {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
impl<'a> EncodeOperation<'a> {
fn begin(state: &'a AppState) -> Result<Self, String> {
let _transition = state.begin_capture_transition()?;
if lock(&state.session).is_some() {
return Err("finish recording before preparing output".to_string());
}
let mut active = lock(&state.encode_operation);
if active.is_some() {
return Err("an export or preview is already running".to_string());
}
let cancel = Arc::new(AtomicBool::new(false));
*active = Some(cancel.clone());
Ok(Self { slot: &state.encode_operation, cancel })
}
}
// One export is one transaction: resolve the output path, translate the trim
// and crop into encoder terms, run the encode, and report the size. Splitting
// it would mean threading the same resolved state through the pieces.
#[allow(
clippy::too_many_lines,
reason = "one export transaction; the request translation feeds directly into the encode call"
)]
impl Drop for EncodeOperation<'_> {
fn drop(&mut self) {
*lock(self.slot) = None;
}
}
fn export_path(state: &AppState, format: Format, entered: Option<&str>) -> Result<PathBuf, String> {
let directory = output_dir(&state.app_dir, &lock(&state.config));
let mut path = entered.map(str::trim).filter(|path| !path.is_empty()).map_or_else(
|| directory.join(format!("bytesize-{}.{}", timestamp_slug(), ext_for(format))),
PathBuf::from,
);
if path.is_relative() {
path = state.app_dir.join(path);
}
if path.is_dir() || !path.set_extension(ext_for(format)) {
return Err("choose a file name for the export".to_string());
}
Ok(path)
}
#[derive(Serialize)]
struct ExportDestination {
path: PathBuf,
exists: bool,
}
#[tauri::command]
async fn export(
app: AppHandle,
fn export_destination(
state: State<'_, AppState>,
format: Format,
path: String,
) -> Result<ExportDestination, String> {
let path = export_path(&state, format, Some(&path))?;
let exists = path.try_exists().map_err(|e| e.to_string())?;
Ok(ExportDestination { path, exists })
}
fn transcode_request(
state: &AppState,
request: ExportRequest,
) -> Result<ExportResult, String> {
if state.exporting.swap(true, Ordering::SeqCst) {
return Err("an export is already running".to_string());
output: PathBuf,
cancel: Arc<AtomicBool>,
) -> Result<encode::TranscodeRequest, String> {
let cfg = lock(&state.config).clone();
let clip = lock(&state.last_clip)
.clone()
.ok_or_else(|| "no recorded clip available".to_string())?;
let start = request.trim_start_secs.unwrap_or(0.0);
let end = request.trim_end_secs.unwrap_or(clip.duration_secs);
if !start.is_finite() || !end.is_finite() || start < 0.0 || end > clip.duration_secs || end <= start {
return Err("choose a valid trim range".to_string());
}
let _export = ExportGuard(state.exporting.clone());
let (cfg, clip, app_dir, export_cancel) = {
let cfg = lock(&state.config).clone();
let clip = lock(&state.last_clip)
.clone()
.ok_or_else(|| "no recorded clip available".to_string())?;
(
cfg,
clip,
state.app_dir.clone(),
state.export_cancel.clone(),
)
};
let ffmpeg = bootstrap::ffmpeg_path(&app_dir);
if !ffmpeg.is_file() {
return Err("ffmpeg.exe not found - run the encoder setup first".to_string());
}
let out_path: PathBuf = match request.output_path.as_deref() {
Some(p) if !p.trim().is_empty() => PathBuf::from(p),
_ => {
let out_dir = output_dir(&app_dir, &cfg);
out_dir.join(format!(
"bytesize-{}.{}",
timestamp_slug(),
ext_for(request.format)
))
if let Some(crop) = request.crop {
if crop.width < 2 || crop.height < 2 || crop.width % 2 != 0 || crop.height % 2 != 0
|| crop.x < 0 || crop.y < 0
|| crop.x.cast_unsigned().saturating_add(crop.width) > clip.width
|| crop.y.cast_unsigned().saturating_add(crop.height) > clip.height
{
return Err("choose an in-frame crop with even width and height of at least 2 pixels".to_string());
}
};
if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("creating output dir: {e:#}"))?;
}
if request.fps == 0 {
return Err("choose an export frame rate above zero".to_string());
}
let trim_start = request.trim_start_secs.filter(|s| *s > 0.001);
let trim_end = request
.trim_end_secs
.filter(|e| *e < clip.duration_secs - 0.001);
let effective_duration = match (trim_start, trim_end) {
(Some(s), Some(e)) => (e - s).max(0.1),
(Some(s), None) => (clip.duration_secs - s).max(0.1),
(None, Some(e)) => e.max(0.1),
(None, None) => clip.duration_secs,
};
let duration_secs = end - start;
let (src_w, src_origin) = if let Some(c) = clip.crop {
(c.width, (c.x, c.y))
} else {
(clip.monitor_width.max(1), (0, 0))
};
let scale = f64::from(clip.width) / f64::from(src_w);
let transformed_clicks: Vec<clicks::Click> = clip
.clicks
.iter()
.map(|c| clicks::Click {
time_secs: c.time_secs,
x: encode::round_i32(f64::from(c.x - src_origin.0) * scale),
y: encode::round_i32(f64::from(c.y - src_origin.1) * scale),
button: c.button,
})
.collect();
let (src_w, src_h, src_x, src_y) = clip.crop.map_or(
(clip.monitor_width, clip.monitor_height, 0, 0),
|crop| (crop.width, crop.height, crop.x, crop.y),
);
let scale_x = f64::from(clip.width) / f64::from(src_w.max(1));
let scale_y = f64::from(clip.height) / f64::from(src_h.max(1));
let clicks = clip.clicks.iter()
.filter(|click| click.time_secs + 0.25 >= start && click.time_secs - 0.05 < end)
.map(|click| clicks::Click {
time_secs: click.time_secs,
x: encode::round_i32((f64::from(click.x) - f64::from(src_x)) * scale_x),
y: encode::round_i32((f64::from(click.y) - f64::from(src_y)) * scale_y),
button: click.button,
}).collect();
let req = encode::TranscodeRequest {
input: clip.temp_path.clone(),
output: out_path.clone(),
Ok(encode::TranscodeRequest {
input: clip.temp_path,
output,
format: request.format,
target_bytes: request.target_bytes,
duration_secs: effective_duration,
duration_secs,
fps: request.fps,
keep_audio: request.keep_audio,
gif_dither: request.gif_dither.unwrap_or(cfg.export.gif_dither),
gif_colors: request.gif_colors.unwrap_or(256),
webm_codec: cfg.export.webm_codec,
mp4_codec: cfg.export.mp4_codec,
scratch_dir: temp_dir(&app_dir),
scratch_dir: temp_dir(&state.app_dir),
crop: request.crop,
gif_budget_mode: request.gif_budget_mode,
deleted_frame_indices: request.deleted_frame_indices,
trim_start_secs: trim_start,
trim_end_secs: trim_end,
clicks: transformed_clicks,
trim_start_secs: request.trim_start_secs,
trim_end_secs: request.trim_end_secs,
clicks,
clip_width: clip.width,
clip_height: clip.height,
progress_tx: None,
cancel: Some(export_cancel.clone()),
};
cancel: Some(cancel),
})
}
fn publish_export(staging: &Path, output: &Path, overwrite: bool) -> Result<()> {
if overwrite {
std::fs::rename(staging, output)?;
} else {
use windows::core::HSTRING;
use windows::Win32::Storage::FileSystem::MoveFileW;
let staging = HSTRING::from(staging.as_os_str());
let output = HSTRING::from(output.as_os_str());
// SAFETY: Both paths are NUL-terminated and live through the call.
unsafe { MoveFileW(&staging, &output) }?;
}
Ok(())
}
async fn run_output_encode(
app: AppHandle,
ffmpeg: PathBuf,
mut request: encode::TranscodeRequest,
) -> Result<(), String> {
let (tx, rx) = std::sync::mpsc::channel();
let mut req_with_progress = req;
req_with_progress.progress_tx = Some(tx);
let app_handle = app.clone();
// Spawn a thread to forward encode progress to the frontend. The encoder
// owns total_passes: 2 for two-pass video, max_retries (up to 12) for GIF
// so the progress bar accumulates across retry attempts.
std::thread::spawn(move || {
while let Ok(progress) = rx.recv() {
drop(app_handle.emit(
"encode-progress",
encode::EncodeProgress {
pass: progress.pass,
total_passes: progress.total_passes,
percent: progress.percent,
},
));
request.progress_tx = Some(tx);
let progress = std::thread::spawn(move || {
while let Ok(update) = rx.recv() {
drop(app.emit("encode-progress", update));
}
});
export_cancel.store(false, Ordering::SeqCst);
// Run the (potentially minutes-long) ffmpeg encode on a blocking thread so
// we don't hold a Tauri async worker for the whole duration.
let ffmpeg_arc = Arc::new(ffmpeg);
let ffmpeg_for_task = ffmpeg_arc.clone();
let result = tauri::async_runtime::spawn_blocking(move || {
encode::transcode(&ffmpeg_for_task, &req_with_progress)
tauri::async_runtime::spawn_blocking(move || {
let result = encode::transcode(&ffmpeg, &request);
drop(request);
drop(progress.join());
result
})
.await
.map_err(|e| format!("encode task panicked: {e:#}"))?;
result.map_err(|e| format!("{e:#}"))?;
.map_err(|e| format!("encode task failed: {e:#}"))?
.map_err(|e| format!("{e:#}"))
}
let size_bytes = std::fs::metadata(&out_path).map_or(0, |m| m.len());
fn output_size(path: &Path) -> Result<u64, String> {
let size = std::fs::metadata(path)
.map_err(|e| format!("checking encoded output: {e:#}"))?.len();
if size == 0 { return Err("the encoder produced an empty file".to_string()); }
Ok(size)
}
#[tauri::command]
async fn render_output_preview(
app: AppHandle,
state: State<'_, AppState>,
request: ExportRequest,
) -> Result<OutputPreview, String> {
let operation = EncodeOperation::begin(&state)?;
let format = request.format;
let target_bytes = request.target_bytes;
let dir = temp_dir(&state.app_dir);
let staging = encode::TempFileGuard::create_in(&dir, "output-review", ext_for(format))
.map_err(|e| format!("creating output preview file: {e:#}"))?;
let path = staging.0.clone();
let req = transcode_request(&state, request, path.clone(), operation.cancel.clone())?;
let source = req.input.clone();
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
run_output_encode(app, ffmpeg.clone(), req).await?;
if operation.cancel.load(Ordering::SeqCst) { return Err("preview cancelled".to_string()); }
let size_bytes = output_size(&path)?;
let inspection_path = path.clone();
let media = tauri::async_runtime::spawn_blocking(move || encode::inspect_output(&ffmpeg, &inspection_path))
.await.map_err(|e| format!("output inspection task failed: {e:#}"))?
.map_err(|e| format!("{e:#}"))?;
if operation.cancel.load(Ordering::SeqCst) { return Err("preview cancelled".to_string()); }
let id = path.file_stem().and_then(std::ffi::OsStr::to_str)
.ok_or_else(|| "could not identify the output preview".to_string())?.to_string();
let preview = OutputPreview { id, path, format, size_bytes, target_bytes, media };
*lock(&state.reviewed_output) = Some(ReviewedOutput { preview: preview.clone(), source, _file: staging });
Ok(preview)
}
fn reviewed_output(state: &AppState, preview_id: &str) -> Result<OutputPreview, String> {
let clip = lock(&state.last_clip);
lock(&state.reviewed_output).as_ref()
.filter(|item| item.preview.id == preview_id && item.preview.path.is_file()
&& clip.as_ref().is_some_and(|clip| clip.temp_path == item.source))
.map(|item| item.preview.clone())
.ok_or_else(|| "this output preview is unavailable. Render the current edits again.".to_string())
}
#[tauri::command]
fn open_output_preview(state: State<'_, AppState>, preview_id: &str) -> Result<(), String> {
let preview = reviewed_output(&state, preview_id)?;
open_shell_target(preview.path.as_os_str())
}
fn stage_export(
state: &AppState,
format: Format,
entered: Option<&str>,
overwrite: bool,
) -> Result<(PathBuf, encode::TempFileGuard), String> {
let output = export_path(state, format, entered)?;
let exists = output.try_exists().map_err(|e| e.to_string())?;
if exists && !overwrite { return Err("the output file already exists".to_string()); }
let canonical = std::fs::canonicalize(&output).ok();
let matches = |source: &Path| {
source == output || canonical.as_ref().is_some_and(|output| {
std::fs::canonicalize(source).is_ok_and(|source| source == *output)
})
};
if lock(&state.last_clip).as_ref().is_some_and(|clip| matches(&clip.temp_path))
|| lock(&state.reviewed_output).as_ref().is_some_and(|item| matches(&item.preview.path))
{
return Err("choose a destination outside the recording and preview files".to_string());
}
let parent = output.parent().ok_or_else(|| "choose an output folder".to_string())?;
std::fs::create_dir_all(parent).map_err(|e| format!("creating output folder: {e:#}"))?;
let staging = encode::TempFileGuard::create_in(parent, "export", "tmp")
.map_err(|e| format!("creating export staging file: {e:#}"))?;
Ok((output, staging))
}
fn finish_export(state: &AppState, output_path: PathBuf, size_bytes: u64, target_bytes: u64) -> ExportResult {
state.unexported_clip.store(false, Ordering::Relaxed);
Ok(ExportResult {
met_target: size_bytes <= request.target_bytes,
target_bytes: request.target_bytes,
output_path: out_path,
size_bytes,
})
ExportResult { met_target: size_bytes <= target_bytes, target_bytes, output_path, size_bytes }
}
fn copy_reviewed_file(preview: &OutputPreview, staging: &Path, output: &Path, overwrite: bool) -> Result<()> {
let copied = std::fs::copy(&preview.path, staging)?;
anyhow::ensure!(copied == preview.size_bytes, "the reviewed file changed on disk");
publish_export(staging, output, overwrite)
}
#[tauri::command]
async fn save_output_preview(
state: State<'_, AppState>,
preview_id: String,
output_path: String,
overwrite: bool,
) -> Result<ExportResult, String> {
let _operation = EncodeOperation::begin(&state)?;
let preview = reviewed_output(&state, &preview_id)?;
let (output, staging) = stage_export(&state, preview.format, Some(&output_path), overwrite)?;
let target = output.clone();
let (size_bytes, target_bytes) = (preview.size_bytes, preview.target_bytes);
tauri::async_runtime::spawn_blocking(move || copy_reviewed_file(&preview, &staging.0, &target, overwrite))
.await.map_err(|e| format!("save task failed: {e:#}"))?
.map_err(|e| format!("saving the reviewed file: {e:#}"))?;
Ok(finish_export(&state, output, size_bytes, target_bytes))
}
#[tauri::command]
async fn export(
app: AppHandle,
state: State<'_, AppState>,
request: ExportRequest,
) -> Result<ExportResult, String> {
let operation = EncodeOperation::begin(&state)?;
let target_bytes = request.target_bytes;
let overwrite = request.overwrite;
let (out_path, staging) = stage_export(&state, request.format, request.output_path.as_deref(), overwrite)?;
let req = transcode_request(&state, request, staging.0.clone(), operation.cancel.clone())?;
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
run_output_encode(app, ffmpeg, req).await?;
if operation.cancel.load(Ordering::SeqCst) {
return Err("export cancelled".to_string());
}
let size_bytes = output_size(&staging.0)?;
publish_export(&staging.0, &out_path, overwrite)
.map_err(|e| format!("saving export: {e:#}"))?;
Ok(finish_export(&state, out_path, size_bytes, target_bytes))
}
fn show_startup_error(message: &str) {
@@ -2092,7 +2264,6 @@ fn show_startup_error(message: &str) {
)]
pub fn run() {
let app_dir = exe_dir().expect("resolve exe directory");
let _instance = match lock_instance(&app_dir) {
Ok(lock) => lock,
Err(e) => {
@@ -2165,11 +2336,11 @@ pub fn run() {
unexported_clip: AtomicBool::new(false),
session: Mutex::new(None),
capture_transition: Mutex::new(()),
thumbnail_operation: Mutex::new(()),
picker: Mutex::new(None),
overlay_poll_shutdown: Arc::new(AtomicBool::new(false)),
export_cancel: Arc::new(AtomicBool::new(false)),
exporting: Arc::new(AtomicBool::new(false)),
encode_operation: Mutex::new(None),
thumbnail_operation: Mutex::new(()),
reviewed_output: Mutex::new(None),
overlay_aspect_ratio: Mutex::new(None),
overlay_poll_live: Arc::new((Mutex::new(false), std::sync::Condvar::new())),
};
@@ -2243,9 +2414,7 @@ pub fn run() {
let cfg = lock(&st.config).clone();
(cfg.updates.check_on_launch, cfg)
};
// Result is not Drop, so the old drop() here did nothing beyond
// extending its lifetime; the hotkey outcome is logged upstream.
let _hotkeys = register_hotkeys(app.handle(), &cfg);
drop(register_hotkeys(app.handle(), &cfg));
{
let st = app.state::<AppState>();
start_overlay_clickthrough_poll(
@@ -2289,7 +2458,6 @@ pub fn run() {
download_update,
apply_update,
pending_update,
check_for_updates,
start_capture,
pause_capture,
resume_capture,
@@ -2298,10 +2466,12 @@ pub fn run() {
discard_clip,
export,
default_output_path,
extract_thumbnails,
render_preview,
export_destination,
timeline_thumbnails,
preview_display,
render_raw_preview,
render_output_preview,
save_output_preview,
open_output_preview,
estimate_gif_params,
estimate_gif_params_table,
reveal_in_explorer,
@@ -2317,6 +2487,7 @@ pub fn run() {
open_window_picker,
close_window_picker,
get_overlay_rect,
check_for_updates,
cancel_export,
codec_availability,
diagnostics_info,
-164
View File
@@ -1,164 +0,0 @@
/* ============================================================
ByteSize - Noir Precision Design System
Ultra-dark instrument panel aesthetic.
Electric teal accent. Monospace data readouts.
============================================================ */
@import url('https://fonts.bunny.net/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;1,9..40,400&family=JetBrains+Mono:wght@400;500&display=swap');
/* ---- Dark theme (default) ---- */
:root,
[data-theme="dark"] {
/* Backgrounds - layered near-blacks */
--bg: #09090B;
--bg-2: #0E0E11;
--bg-3: #13131A;
--bg-4: #1A1A22;
/* Accent - electric teal */
--accent: #14B8A6;
--accent-hover: #2DD4BF;
--accent-dim: rgba(20, 184, 166, 0.10);
--accent-glow: rgba(20, 184, 166, 0.25);
--accent-text: #020617;
/* Semantic - recording */
--recording: #22C55E;
--recording-dim: rgba(34, 197, 94, 0.10);
--recording-glow: rgba(34, 197, 94, 0.20);
/* Semantic - stop / danger */
--stop: #EF4444;
--stop-hover: #F87171;
--stop-dim: rgba(239, 68, 68, 0.10);
/* Semantic - error */
--err: #EF4444;
--err-border: rgba(239, 68, 68, 0.30);
--err-dim: rgba(239, 68, 68, 0.08);
/* Semantic - warning */
--warn: #EAB308;
--warn-dim: rgba(234, 179, 8, 0.08);
/* Borders */
--border: rgba(255, 255, 255, 0.06);
--border-2: rgba(255, 255, 255, 0.10);
--border-3: rgba(255, 255, 255, 0.14);
/* Text */
--text: #E4E4E7;
--text-2: #A1A1AA;
--text-3: #71717A;
--text-4: #52525B;
/* Typography */
--sans: 'DM Sans', system-ui, sans-serif;
--mono: 'JetBrains Mono', ui-monospace, monospace;
/* Radii */
--r-sm: 3px;
--r-md: 6px;
--r-lg: 8px;
color-scheme: dark;
}
/* ---- Light theme ---- */
[data-theme="light"] {
--bg: #FAFAFA;
--bg-2: #F4F4F5;
--bg-3: #E4E4E7;
--bg-4: #D4D4D8;
--accent: #0D9488;
--accent-hover: #0F766E;
--accent-dim: rgba(13, 148, 136, 0.08);
--accent-glow: rgba(13, 148, 136, 0.15);
--accent-text: #FFFFFF;
--recording: #16A34A;
--recording-dim: rgba(22, 163, 74, 0.08);
--recording-glow: rgba(22, 163, 74, 0.12);
--stop: #DC2626;
--stop-hover: #B91C1C;
--stop-dim: rgba(220, 38, 38, 0.08);
--err: #DC2626;
--err-border: rgba(220, 38, 38, 0.25);
--err-dim: rgba(220, 38, 38, 0.06);
--warn: #CA8A04;
--warn-dim: rgba(202, 138, 4, 0.06);
--border: rgba(0, 0, 0, 0.08);
--border-2: rgba(0, 0, 0, 0.12);
--border-3: rgba(0, 0, 0, 0.18);
--text: #18181B;
--text-2: #52525B;
--text-3: #71717A;
--text-4: #A1A1AA;
color-scheme: light;
}
/* ---- Reset & base ---- */
*, *::before, *::after {
box-sizing: border-box;
}
html {
font-family: var(--sans);
font-size: 14px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
margin: 0;
background: var(--bg);
color: var(--text);
min-height: 100vh;
}
/* ---- Selection ---- */
::selection {
background: var(--accent-dim);
color: var(--text);
}
/* ---- Scrollbar ---- */
::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb {
background: var(--border-2);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover { background: var(--text-4); }
/* ---- Focus ---- */
:focus-visible {
outline: none;
box-shadow: 0 0 0 1px var(--accent), 0 0 0 3px var(--accent-glow);
border-radius: var(--r-sm);
}
/* ---- Reduced motion ---- */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
.phase-dot.pulse,
.bar,
.blink,
.enc-fill,
.fill,
.audio-dot.active,
.dot.pulse {
animation: none !important;
transition: none !important;
}
}
+69 -179
View File
@@ -1,201 +1,91 @@
<script lang="ts">
import { IconArrowRight, IconCrop } from "./ui/icons"
import type { Format, GifBudgetMode, GifDither, RecordedClip } from "./api"
import { minTargetMB, maxTargetMB } from "./exportSizing"
import Dropdown from "./ui/Dropdown.svelte"
import NumberField from "./ui/NumberField.svelte"
import Segmented from "./ui/Segmented.svelte"
import Slider from "./ui/Slider.svelte"
import Toggle from "./ui/Toggle.svelte"
import { appear } from "./ui/motion"
import GifControls from "./GifControls.svelte"
import type { Format, GifBudgetMode, GifDither } from "./api"
import { maxTargetMB, minTargetMB } from "./exportSizing"
import OutputDestination from "./OutputDestination.svelte"
let {
clip,
format,
targetMB = $bindable(),
fps = $bindable(),
keepAudio = $bindable(),
gifBudgetMode = $bindable(),
gifDither = $bindable(),
gifColors = $bindable(),
cropEnabled = $bindable(),
cropX = $bindable(),
cropY = $bindable(),
cropW = $bindable(),
cropH = $bindable(),
outputPath = $bindable(),
previewDims,
trimmedDuration,
onPreview,
onPathInput,
onBrowse,
onExport,
onDiscard,
clip, format, onFormat, targetMB = $bindable(), fps = $bindable(), keepAudio = $bindable(),
gifBudgetMode = $bindable(), gifDither = $bindable(), gifColors = $bindable(),
cropEnabled = $bindable(), cropX = $bindable(), cropY = $bindable(), cropW = $bindable(), cropH = $bindable(),
outputPath = $bindable(), invalidDraft = $bindable(), estimatedOutput, trimmedDuration, cropInvalid, disabled,
reviewState, onPathInput, onBrowse, onReview, onSave,
}: {
clip: { duration_secs: number; width: number; height: number }
format: Format
targetMB: number
fps: number
keepAudio: boolean
gifBudgetMode: GifBudgetMode
gifDither: GifDither
gifColors: number
cropEnabled: boolean
cropX: number
cropY: number
cropW: number
cropH: number
outputPath: string
previewDims: string
trimmedDuration: number
onPreview: () => void
onPathInput: () => void
onBrowse: () => void
onExport: () => void
onDiscard: () => void
clip: RecordedClip; format: Format; onFormat: (format: Format) => void; targetMB: number; fps: number; keepAudio: boolean
gifBudgetMode: GifBudgetMode; gifDither: GifDither; gifColors: number; cropEnabled: boolean
cropX: number; cropY: number; cropW: number; cropH: number; outputPath: string; invalidDraft: string | null
estimatedOutput: string; trimmedDuration: number; cropInvalid: boolean; disabled: boolean
reviewState: "none" | "current" | "stale"
onPathInput: () => void; onBrowse: () => void; onReview: () => void; onSave: () => void
} = $props()
const formats = [{value:"mp4",label:"MP4"},{value:"webm",label:"WebM"},{value:"gif",label:"GIF"}] as const
const rates = [1,2,5,10,15,24,30,60].map(value => ({ value, label: value + " FPS" }))
let max = $derived(maxTargetMB(trimmedDuration))
let min = $derived(Math.min(minTargetMB(trimmedDuration), max))
function clampCrop() {
cropX = Math.max(0, Math.min(cropX, Math.max(0, clip.width - 1)))
cropY = Math.max(0, Math.min(cropY, Math.max(0, clip.height - 1)))
cropW = Math.max(1, Math.min(cropW, clip.width - cropX))
cropH = Math.max(1, Math.min(cropH, clip.height - cropY))
}
let cropInvalid = $derived.by(() => {
if (!cropEnabled) return false
return cropX < 0 || cropY < 0 || cropW < 1 || cropH < 1
|| cropX + cropW > clip.width
|| cropY + cropH > clip.height
$effect(() => {
if (targetMB < min || targetMB > max) targetMB = Math.max(min, Math.min(max, targetMB))
})
</script>
<div class="edit-right">
<div class="control-group">
<div class="control-head">
<span class="section-title">Target size</span>
<span class="mono size-readout">{targetMB.toFixed(1)} MB</span>
<aside class="rail" aria-label="Export settings">
<div class="rail-group">
<h2>Export settings</h2>
<Segmented label="Output format" value={format} options={formats} onchange={onFormat} {disabled} />
<div>
<div class="row between"><span>Target size</span><output class="mono">{targetMB.toFixed(1)} MB</output></div>
<Slider label="Target size" bind:value={targetMB} {min} {max} step={.1} {disabled} valueText={targetMB.toFixed(1) + " megabytes"} />
</div>
<input
type="range"
class="styled-range"
min={minTargetMB(clip.duration_secs)}
max={maxTargetMB(clip.duration_secs)}
step="0.1"
aria-label="target size"
bind:value={targetMB}
onchange={onPreview}
/>
<p class="estimate">{previewDims} &middot; {fps}fps &middot; {trimmedDuration.toFixed(1)}s</p>
</div>
{#if format === "gif"}
<GifControls
bind:budgetMode={gifBudgetMode}
bind:dither={gifDither}
bind:colors={gifColors}
onChange={onPreview}
/>
{/if}
<div class="control-row">
<label class="control">
<span class="control-label">FPS</span>
<select bind:value={fps} onchange={onPreview}>
{#each [1, 2, 5, 10, 15, 24, 30, 60] as f}<option value={f}>{f}</option>{/each}
</select>
</label>
{#if format !== "gif"}
<label class="check-control">
<input type="checkbox" bind:checked={keepAudio} />
<span>Keep audio</span>
</label>
{/if}
</div>
<div class="control-group">
<div class="control-head">
<span class="section-title">Crop</span>
<label class="check-control compact">
<input type="checkbox" bind:checked={cropEnabled} />
<span>Enable</span>
</label>
<div class="split-field">
<div class="form-field"><span>Export FPS</span><Dropdown label="Export FPS" bind:value={fps} options={rates} {disabled} /></div>
{#if format !== "gif"}<div class="row between audio"><span>Keep audio</span><Toggle label="Keep audio" bind:checked={keepAudio} {disabled} /></div>{/if}
</div>
</div>
<div class="rail-group">
<div class="row between"><span class="row"><IconCrop size={17} />Crop</span><Toggle label="Crop" bind:checked={cropEnabled} {disabled} /></div>
{#if cropEnabled}
<div class="crop-grid" class:invalid={cropInvalid}>
<label class="crop-field">
<span>X</span>
<input type="number" min="0" max={clip.width} bind:value={cropX} onblur={clampCrop} />
</label>
<label class="crop-field">
<span>Y</span>
<input type="number" min="0" max={clip.height} bind:value={cropY} onblur={clampCrop} />
</label>
<label class="crop-field">
<span>W</span>
<input type="number" min="1" max={clip.width} bind:value={cropW} onblur={clampCrop} />
</label>
<label class="crop-field">
<span>H</span>
<input type="number" min="1" max={clip.height} bind:value={cropH} onblur={clampCrop} />
</label>
<div class="split-field" use:appear>
<div class="form-field"><span>Left</span><NumberField label="Crop left" bind:value={cropX} min={0} max={clip.width} {disabled} /></div>
<div class="form-field"><span>Top</span><NumberField label="Crop top" bind:value={cropY} min={0} max={clip.height} {disabled} /></div>
<div class="form-field"><span>Width</span><NumberField label="Crop width" bind:value={cropW} min={2} max={clip.width} step={2} {disabled} /></div>
<div class="form-field"><span>Height</span><NumberField label="Crop height" bind:value={cropH} min={2} max={clip.height} step={2} {disabled} /></div>
</div>
{#if cropInvalid}<p class="note error" role="alert">Keep the crop inside the clip. Width and height must be even and at least 2 px.</p>{/if}
{/if}
</div>
<div class="control-group">
<span class="section-title">Output</span>
<div class="path-row">
<input type="text" class="path-input" bind:value={outputPath} oninput={onPathInput} aria-label="output file path" />
<button class="btn-ghost" onclick={onBrowse}>Browse</button>
{#if format === "gif"}
<div class="rail-group" use:appear>
<GifControls bind:budgetMode={gifBudgetMode} bind:dither={gifDither} bind:colors={gifColors} {disabled} />
</div>
{/if}
<div class="rail-group">
<OutputDestination bind:path={outputPath} bind:invalidDraft {disabled} {onPathInput} {onBrowse} />
</div>
<div class="edit-actions">
<button class="btn-primary" onclick={onExport} disabled={cropInvalid}>Export</button>
<button class="btn-ghost" onclick={onDiscard}>Discard</button>
<div class="footer">
<div class="row between wrap note"><span>{estimatedOutput}</span><span class="mono">{trimmedDuration.toFixed(2)} s</span></div>
{#if reviewState === "stale"}<p class="note">Output preview is out of date.</p>{/if}
<button type="button" class="button primary full" onclick={onReview} disabled={disabled || cropInvalid}>
{reviewState === "current" ? "Review output" : "Render output preview"}<IconArrowRight size={17} />
</button>
<button type="button" class="button ghost full" onclick={onSave} disabled={disabled || cropInvalid || invalidDraft !== null}>
{reviewState === "current" ? "Save reviewed " + format.toUpperCase() : "Save " + format.toUpperCase() + " without preview"}
</button>
</div>
</div>
</aside>
<style>
.edit-right {
background: var(--bg);
display: flex;
flex-direction: column;
gap: 20px;
overflow: auto;
min-height: 0;
padding: 20px;
border-left: 1px solid var(--border);
}
@media (max-width: 720px) {
.edit-right { border-left: none; border-top: 1px solid var(--border); }
}
.control-group { display: flex; flex-direction: column; gap: 8px; }
.control-head { display: flex; justify-content: space-between; align-items: center; }
.section-title { font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.1em; color: var(--text-3); }
.size-readout { font-size: 14px; color: var(--text); }
.styled-range { -webkit-appearance: none; appearance: none; width: 100%; height: 3px; background: var(--bg-3); border-radius: 2px; outline: none; cursor: pointer; }
.styled-range::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 14px; height: 14px; border-radius: 50%; background: var(--accent); border: 2px solid var(--bg); cursor: pointer; transition: transform 80ms; }
.styled-range::-webkit-slider-thumb:hover { transform: scale(1.2); }
.estimate { margin: 0; font-size: 11px; color: var(--text-3); font-family: var(--mono); }
.control-row { display: flex; gap: 16px; align-items: flex-end; }
.control { display: flex; flex-direction: column; gap: 6px; }
.control-label { font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--text-3); }
select { padding: 7px 10px; background: var(--bg-2); border: 1px solid var(--border); color: var(--text); border-radius: var(--r-sm); font-family: var(--mono); font-size: 12px; cursor: pointer; outline: none; }
select:focus { border-color: var(--accent); }
.check-control { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--text-2); cursor: pointer; }
.check-control.compact { font-size: 11px; }
.check-control input[type="checkbox"] { width: 14px; height: 14px; accent-color: var(--accent); cursor: pointer; }
.crop-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
.crop-grid.invalid input { border-color: var(--err); background: var(--err-dim); }
.crop-field { display: flex; flex-direction: column; gap: 4px; }
.crop-field span { font-size: 10px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text-3); }
.crop-field input { padding: 6px 8px; background: var(--bg-2); border: 1px solid var(--border); color: var(--text); border-radius: var(--r-sm); font-family: var(--mono); font-size: 12px; outline: none; width: 100%; }
.crop-field input:focus { border-color: var(--accent); }
.path-row { display: flex; gap: 6px; }
.path-input { flex: 1; padding: 7px 10px; background: var(--bg-2); border: 1px solid var(--border); color: var(--text); border-radius: var(--r-sm); font-family: var(--mono); font-size: 11px; outline: none; }
.path-input:focus { border-color: var(--accent); }
.btn-primary { padding: 10px 24px; background: var(--accent); border: none; color: var(--accent-text); border-radius: var(--r-sm); font-family: var(--sans); font-size: 13px; font-weight: 600; cursor: pointer; transition: background 80ms; white-space: nowrap; }
.btn-primary:hover:not(:disabled) { background: var(--accent-hover); }
.btn-primary:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-ghost { padding: 10px 18px; background: transparent; border: 1px solid var(--border-2); color: var(--text-3); border-radius: var(--r-sm); font-family: var(--sans); font-size: 13px; cursor: pointer; transition: border-color 80ms, color 80ms; white-space: nowrap; }
.btn-ghost:hover { border-color: var(--border-3); color: var(--text); }
.edit-actions { display: flex; gap: 10px; margin-top: auto; padding-top: 8px; }
.rail { display:flex; flex-direction:column; gap:16px; padding:20px; min-width:0; background:var(--caption); }
.rail-group { display:grid; gap:12px; }
.rail-group + .rail-group { border-top:var(--edge) solid var(--rule); padding-top:12px; }
.audio { align-self:end; min-height:38px; }
.footer { display:grid; gap:12px; margin-top:auto; border-top:var(--edge) solid var(--rule); padding-top:12px; }
.footer .primary { min-height:44px; }
.error { color:var(--alert); }
</style>
+15 -124
View File
@@ -1,131 +1,22 @@
<script lang="ts">
import type { GifBudgetMode, GifDither } from "./api"
import Dropdown from "./ui/Dropdown.svelte"
import Slider from "./ui/Slider.svelte"
let {
budgetMode = $bindable(),
dither = $bindable(),
colors = $bindable(),
onChange,
}: {
budgetMode: GifBudgetMode
dither: GifDither
colors: number
onChange: () => void
let { budgetMode = $bindable(), dither = $bindable(), colors = $bindable(), disabled = false }: {
budgetMode: GifBudgetMode; dither: GifDither; colors: number; disabled?: boolean
} = $props()
const priorities = [
{ value:"balanced", label:"Balanced" }, { value:"resolution", label:"Preserve resolution" }, { value:"framerate", label:"Preserve frame rate" },
] as const
const dithers = [{ value:"floyd_steinberg",label:"Floyd-Steinberg" }, { value:"bayer",label:"Bayer" }, { value:"none",label:"None" }] as const
</script>
<div class="control-group">
<span class="section-title">Budget priority</span>
<div class="fmt-bar">
{#each (["resolution", "framerate", "balanced"] as const) as m}
<button
class="fmt-chip"
class:active={budgetMode === m}
onclick={() => { budgetMode = m; onChange() }}
>{m === "resolution" ? "Resolution" : m === "framerate" ? "Framerate" : "Balanced"}</button>
{/each}
</div>
<p class="estimate">
{budgetMode === "resolution" ? "Keeps resolution high, may reduce FPS" :
budgetMode === "framerate" ? "Keeps FPS high, may reduce resolution" :
"Balances resolution and FPS"}
</p>
<h3>GIF compression</h3>
<div class="form-field"><span>Budget priority</span><Dropdown label="GIF budget priority" bind:value={budgetMode} options={priorities} {disabled} /></div>
<div>
<div class="row between"><span>Palette colors</span><output class="mono">{colors}</output></div>
<Slider label="GIF palette colors" bind:value={colors} min={2} max={256} {disabled} />
</div>
<div class="control-group">
<span class="section-title">Colors</span>
<div class="control-head">
<input
type="range"
class="styled-range"
min={2}
max={256}
step={1}
aria-label="colors"
bind:value={colors}
onchange={onChange}
/>
<span class="mono" style="min-width:32px;text-align:right">{colors}</span>
</div>
<p class="estimate">{colors <= 32 ? "Low - small file, posterized" : colors <= 128 ? "Medium - balanced" : "High - full color"}</p>
</div>
<div class="control-group">
<span class="section-title">Dithering</span>
<div class="fmt-bar">
{#each (["floyd_steinberg", "bayer", "none"] as const) as d}
<button
class="fmt-chip"
class:active={dither === d}
onclick={() => { dither = d; onChange() }}
>{d === "floyd_steinberg" ? "Floyd-Steinberg" : d === "bayer" ? "Bayer" : "None"}</button>
{/each}
</div>
<p class="estimate">{dither === "floyd_steinberg" ? "Smooth gradients, slightly larger" : dither === "bayer" ? "Patterned, smaller file" : "No dithering, smallest file"}</p>
</div>
<style>
.control-group { display: flex; flex-direction: column; gap: 8px; }
.control-head { display: flex; justify-content: space-between; align-items: center; }
.section-title {
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--text-3);
}
.estimate {
margin: 0;
font-size: 11px;
color: var(--text-3);
font-family: var(--mono);
}
.fmt-bar {
display: flex;
gap: 2px;
padding: 3px;
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--r-sm);
width: fit-content;
}
.fmt-chip {
padding: 5px 14px;
background: transparent;
border: 1px solid transparent;
color: var(--text-3);
border-radius: var(--r-sm);
font-family: var(--mono);
font-size: 11px;
font-weight: 500;
letter-spacing: 0.04em;
cursor: pointer;
transition: all 80ms;
}
.fmt-chip:hover { color: var(--text-2); }
.fmt-chip.active { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
.styled-range {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 3px;
background: var(--bg-3);
border-radius: 2px;
outline: none;
cursor: pointer;
}
.styled-range::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 14px; height: 14px;
border-radius: 50%;
background: var(--accent);
border: 2px solid var(--bg);
cursor: pointer;
transition: transform 80ms;
}
.styled-range::-webkit-slider-thumb:hover { transform: scale(1.2); }
.mono { font-family: var(--mono); }
</style>
<div class="form-field"><span>Dithering</span><Dropdown label="GIF dithering" bind:value={dither} options={dithers} {disabled} /></div>
+338 -485
View File
File diff suppressed because it is too large Load Diff
+41
View File
@@ -0,0 +1,41 @@
<script lang="ts">
import { IconArrowRight, IconFolder } from "./ui/icons"
let { path = $bindable(), invalidDraft = $bindable(), disabled, onPathInput, onBrowse }: {
path: string; invalidDraft: string | null; disabled: boolean; onPathInput: () => void; onBrowse: () => void
} = $props()
const id = $props.id()
let separator = $derived(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")))
let filename = $derived(path.slice(separator + 1))
let folder = $derived(path.slice(0, separator + 1))
function editName(event: Event) {
const name = (event.currentTarget as HTMLInputElement).value
invalidDraft = !name.trim() || /[<>:"/\\|?*]/.test(name) ? name : null
if (invalidDraft === null) path = folder + name
onPathInput()
}
</script>
<div class="stack output-destination">
<div class="form-field">
<label for={id}>File name</label>
<input {id} class="field mono" value={invalidDraft ?? filename} oninput={editName} {disabled} aria-invalid={invalidDraft !== null} />
{#if invalidDraft !== null}<p class="note error" role="alert">Enter a file name without path characters.</p>{/if}
</div>
<div class="form-field">
<span>Save to</span>
<button type="button" class="button destination" onclick={onBrowse} {disabled} aria-label="Choose output folder" title={folder}>
<IconFolder size={17} /><span class="mono path-line">{folder || "Default output folder"}</span><IconArrowRight size={16} />
</button>
</div>
</div>
<style>
.output-destination, .form-field { grid-template-columns:minmax(0,1fr); min-width:0; }
.destination {
display:grid; grid-template-columns:auto minmax(0,1fr) auto; width:100%; min-width:0;
text-align:left; background:var(--input);
}
.error { color:var(--alert); }
</style>
+112 -55
View File
@@ -1,64 +1,121 @@
<script lang="ts">
import { convertFileSrc } from "./api"
import { trimPreviewState } from "./trimPreviewState.svelte"
import { IconPlayerPauseFilled, IconPlayerPlayFilled, IconPlayerSkipBackFilled, IconPlayerSkipForwardFilled, IconVolume, IconVolumeOff } from "./ui/icons"
import { untrack } from "svelte"
import { convertFileSrc, type CaptureRect } from "./api"
import { appear, bound, timecode } from "./ui/motion"
let {
previewPath,
previewLoading,
previewCacheBust,
}: {
previewPath: string | null
previewLoading: boolean
previewCacheBust: number
let { path, label, dimensions, seek = null, playbackRangeOnly = false, frameStep = .04,
playhead = $bindable(0), trimStart, trimEnd, crop, onOpenFile }: {
path: string; label: string; dimensions: string; seek?: { seconds: number } | null
playbackRangeOnly?: boolean; frameStep?: number
playhead?: number; trimStart: number; trimEnd: number
crop?: CaptureRect & { imageWidth: number; imageHeight: number }
onOpenFile?: () => void
} = $props()
let player: HTMLVideoElement | undefined = $state()
let playing = $state(false)
let muted = $state(false)
let loadError = $state(false)
let pending: { seconds: number } | null = null
$effect(() => {
const request = seek
if (!request) return
untrack(() => {
pending = request
if (player?.readyState) applySeek(player)
})
})
function applySeek(video: HTMLVideoElement) {
if (!pending || !Number.isFinite(video.duration)) return
video.pause()
video.currentTime = bound(pending.seconds, 0, Math.max(0, video.duration - .001))
pending = null
}
function updateTime() {
if (!player || player.seeking || pending) return
playhead = player.currentTime
if (!player.paused && playhead >= trimEnd) {
player.pause()
player.currentTime = Math.min(trimEnd, player.duration)
}
}
function metadata() {
if (!player) return
loadError = false
if (pending) applySeek(player)
else player.currentTime = bound(playhead, 0, Math.max(0, player.duration - .001))
}
async function play() {
if (!player || !player.readyState) return
if (!player.paused) return player.pause()
if (pending) applySeek(player)
if (player.currentTime < trimStart || player.currentTime >= trimEnd - .001) player.currentTime = trimStart
try { await player.play() } catch { loadError = true }
}
function step(delta: number) {
if (!player || !player.readyState) return
player.pause()
const current = pending?.seconds ?? player.currentTime
pending = null
player.currentTime = bound(current + delta, playbackRangeOnly ? trimStart : 0,
playbackRangeOnly ? Math.min(player.duration, trimEnd) : player.duration)
playhead = player.currentTime
}
</script>
{#if trimPreviewState.dragging && trimPreviewState.path}
<div class="preview-box">
<img src={convertFileSrc(trimPreviewState.path) + "?t=" + trimPreviewState.bust} alt="preview frame" class="preview-img"/>
<div class="preview-loading">original</div>
<figure class="viewer">
<figcaption class="row between wrap">
<strong>{label}</strong><span class="mono note">{dimensions}</span>
</figcaption>
{#key path}
<div class="media" use:appear>
<!-- svelte-ignore a11y_media_has_caption (A local user recording has no caption track.) -->
<video src={convertFileSrc(path)} bind:this={player} preload="auto" playsinline aria-label={label}
{muted} onplay={() => playing = true} onpause={() => playing = false} onended={() => playing = false}
ontimeupdate={updateTime} onloadedmetadata={metadata} onerror={() => { loadError = true; playing = false }}></video>
{#if crop}
<span class="crop-guide" aria-hidden="true"
style:inset={crop.y / crop.imageHeight * 100 + "% " + (crop.imageWidth - crop.x - crop.width) / crop.imageWidth * 100 + "% " + (crop.imageHeight - crop.y - crop.height) / crop.imageHeight * 100 + "% " + crop.x / crop.imageWidth * 100 + "%"}></span>
{/if}
</div>
{/key}
{#if loadError}
<div class="notice problem row between wrap" role="alert">
<p>The clip could not be played here.</p>
{#if onOpenFile}<button type="button" class="button" onclick={onOpenFile}>Open rendered file</button>{/if}
</div>
{/if}
<div class="transport">
<button type="button" class="button ghost icon-only mute" aria-label={muted ? "Unmute preview" : "Mute preview"} onclick={() => muted = !muted}>
{#if muted}<IconVolumeOff size={18} />{:else}<IconVolume size={18} />{/if}
</button>
<div class="row">
<button type="button" class="button ghost icon-only" aria-label="Previous frame" onclick={() => step(-frameStep)}><IconPlayerSkipBackFilled size={16} /></button>
<button type="button" class="button icon-only" aria-label={playing ? "Pause preview" : "Play preview"} onclick={play}>
{#if playing}<IconPlayerPauseFilled size={16} />{:else}<IconPlayerPlayFilled size={16} />{/if}
</button>
<button type="button" class="button ghost icon-only" aria-label="Next frame" onclick={() => step(frameStep)}><IconPlayerSkipForwardFilled size={16} /></button>
</div>
<span class="mono note"><strong>{timecode(playhead)}</strong> / {timecode(trimEnd)}</span>
</div>
{:else if previewPath}
<div class="preview-box">
<img src={convertFileSrc(previewPath) + "?t=" + previewCacheBust} alt="preview frame" class="preview-img"/>
{#if previewLoading}<div class="preview-loading">rendering</div>{/if}
</div>
{:else}
<div class="preview-box empty">
<span class="preview-placeholder">preview</span>
</div>
{/if}
</figure>
<style>
.preview-box {
position: relative;
border-radius: var(--r-sm);
overflow: hidden;
background: var(--bg-2);
border: 1px solid var(--border);
display: grid;
place-items: center;
aspect-ratio: 16 / 9;
}
.preview-img {
width: 100%;
height: 100%;
object-fit: contain;
display: block;
}
.preview-placeholder {
font-size: 11px;
color: var(--text-4);
text-transform: uppercase;
letter-spacing: 0.08em;
}
.preview-loading {
position: absolute; inset: 0;
background: rgba(0,0,0,0.5);
display: grid; place-items: center;
font-size: 11px;
color: var(--text-3);
text-transform: uppercase;
letter-spacing: 0.06em;
}
.viewer { padding:8px; display:grid; gap:8px; border:var(--edge) solid var(--rule); border-radius:var(--radius); background:var(--input); }
figcaption { padding:0 4px; }
.media { margin:auto; position:relative; width:min(100%,560px); border-radius:var(--control-radius); overflow:hidden; }
video { display:block; width:100%; max-height:48vh; object-fit:contain; background:#101417; }
.crop-guide { position:absolute; pointer-events:none; border:var(--edge) dashed var(--signal); outline:3px solid #172125; }
.transport { display:grid; grid-template-columns:1fr auto 1fr; align-items:center; gap:4px; }
.transport .button { min-height:34px; }
.transport > span { justify-self:end; white-space:nowrap; text-align:right; }
.transport strong { color:var(--ink); }
@media(max-width:460px) { .transport { grid-template-columns:auto 1fr; } .mute { display:none; } }
</style>
+68
View File
@@ -0,0 +1,68 @@
<script lang="ts">
import { IconPlayerPlayFilled } from "./ui/icons"
import { convertFileSrc, type OutputPreview, type RecordedClip } from "./api"
import Preview from "./Preview.svelte"
import Segmented from "./ui/Segmented.svelte"
import { bound } from "./ui/motion"
let { clip, output, trimStart, trimEnd, onOpenFile }: {
clip: RecordedClip; output: OutputPreview; trimStart: number; trimEnd: number; onOpenFile: () => void
} = $props()
const sources = [{ value: "original", label: "Original" }, { value: "output", label: "Output" }] as const
let source = $state<"original" | "output">("output")
let playhead = $state(0)
let replay = $state(0)
let gifError = $state(false)
function choose(next: typeof source) {
const start = source === "original" ? trimStart : 0
const offset = output.format === "gif" ? 0 : playhead - start
playhead = next === "original"
? trimStart + bound(offset, 0, trimEnd - trimStart)
: bound(offset, 0, output.duration_secs)
source = next
if (output.format === "gif" && next === "output") restartGif()
}
function restartGif() {
gifError = false
replay++
}
</script>
<div class="stack">
<div class="compare"><Segmented label="Compare original and output" value={source} options={sources} onchange={choose} kind="neutral" /></div>
{#key source}
{#if source === "output" && output.format === "gif"}
<figure class="gif-viewer">
<figcaption class="row between wrap"><strong>Encoded GIF</strong><span class="mono note">{output.width} × {output.height}</span></figcaption>
{#key replay}
<img src={convertFileSrc(output.path) + (replay ? "?play=" + replay : "")} alt="Rendered output GIF" onerror={() => gifError = true} />
{/key}
{#if gifError}
<div class="notice problem row between wrap" role="alert">
<p>The GIF could not be played here.</p><button type="button" class="button" onclick={onOpenFile}>Open rendered file</button>
</div>
{:else}
<div class="row between wrap">
<span class="note">Looping GIF</span>
<button type="button" class="button ghost" onclick={restartGif}><IconPlayerPlayFilled size={15} />Restart GIF</button>
</div>
{/if}
</figure>
{:else if source === "output"}
<Preview path={output.path} label="Encoded output" dimensions={output.width + " × " + output.height}
bind:playhead trimStart={0} trimEnd={output.duration_secs} frameStep={1 / output.fps} playbackRangeOnly {onOpenFile} />
{:else}
<Preview path={clip.temp_path} label="Original recording" dimensions={clip.width + " × " + clip.height}
bind:playhead {trimStart} {trimEnd} playbackRangeOnly />
{/if}
{/key}
</div>
<style>
.compare { width:min(100%,240px); }
.gif-viewer { display:grid; gap:8px; padding:8px; border:var(--edge) solid var(--rule); border-radius:var(--radius); background:var(--input); }
figcaption, .gif-viewer > .row { padding-inline:4px; }
img { display:block; margin:auto; max-width:100%; max-height:48vh; object-fit:contain; border-radius:var(--control-radius); background:#101417; }
</style>
+178 -153
View File
@@ -1,170 +1,195 @@
<script lang="ts">
import { api } from "./api"
import { trimPreviewState } from "./trimPreviewState.svelte"
import { IconGripVertical } from "./ui/icons"
import { convertFileSrc } from "./api"
import { animate, bound, timecode } from "./ui/motion"
let {
clip,
trimStart = $bindable(),
trimEnd = $bindable(),
}: {
clip: { temp_path: string; duration_secs: number; width: number; height: number }
trimStart: number
trimEnd: number
type Edge = "start" | "end"
type Drag = { pointer: number } & ({ edge: "seek" } | { edge: Edge; lastX: number })
let { clip, trimStart = $bindable(), trimEnd = $bindable(), playhead, frames, keptDuration, onSeek }: {
clip: { duration_secs: number }; trimStart: number; trimEnd: number
playhead: number; frames: string[]; keptDuration: number
onSeek: (seconds: number) => void
} = $props()
let length = $derived(clip.duration_secs)
let minimum = $derived(Math.min(.1, length))
let active = $state<Edge | "seek" | null>(null)
let hovered = $state<Edge | null>(null)
let focused = $state<Edge | null>(null)
let cue = $state<HTMLElement>()
let track: HTMLDivElement
let drag: Drag | undefined
let error = $state<Edge | null>(null)
let shown = $derived(active ?? focused ?? hovered)
const hintId = $props.id()
const boundaries = [{ key: "start", title: "Start" }, { key: "end", title: "End" }] as const
const percent = (value: number) => (length > 0 ? bound(value / length, 0, 1) * 100 : 0) + "%"
let marks = $derived(Array.from({length:25}, (_, index) => ({ index, time: length * index / 24 })))
let trackEl: HTMLDivElement | null = $state(null)
let lastTrimPreview = 0
function pointerToSecs(e: PointerEvent): number {
if (!trackEl) return 0
const rect = trackEl.getBoundingClientRect()
const x = e.clientX - rect.left
const ratio = Math.max(0, Math.min(1, x / rect.width))
return ratio * clip.duration_secs
$effect(() => {
if (cue) animate(cue, { opacity: shown ? 1 : 0, y: shown ? 0 : 4 })
})
function limits(edge: Edge): [number, number] {
return edge === "start" ? [0, Math.max(0, trimEnd - minimum)] : [Math.min(length, trimStart + minimum), length]
}
async function updateTrimPreview(secs: number) {
const now = Date.now()
if (now - lastTrimPreview < 100) return
lastTrimPreview = now
try {
trimPreviewState.path = await api.renderRawPreview(secs)
trimPreviewState.bust = Date.now()
} catch {
lastTrimPreview = 0
function cut(edge: Edge, seconds: number) {
const next = bound(seconds, ...limits(edge))
if (edge === "start") trimStart = next
else trimEnd = next
error = null
onSeek(next)
}
function pointerDown(event: PointerEvent, edge: Edge | "seek") {
if (event.button !== 0 || drag) return
event.stopPropagation()
event.preventDefault()
const target = event.currentTarget as HTMLElement
target.focus({ preventScroll: true })
target.setPointerCapture(event.pointerId)
drag = edge === "seek" ? { pointer: event.pointerId, edge } : { pointer: event.pointerId, edge, lastX: event.clientX }
active = edge
if (edge === "seek") pointerMove(event)
}
function pointerMove(event: PointerEvent) {
if (!drag || drag.pointer !== event.pointerId) return
if (!(event.buttons & 1)) { clearDrag(); return }
const { left, top, bottom, width } = track.getBoundingClientRect()
if (width <= 0) return
if (drag.edge === "seek") {
onSeek(bound((event.clientX - left) / width * length, 0, length))
return
}
// Scale the delta so moving away from the bar doesn't shift the cut.
const deltaX = event.clientX - drag.lastX
drag.lastX = event.clientX
if (deltaX === 0) return
const distance = Math.max(0, top - event.clientY, event.clientY - bottom)
const speed = Math.max(.08, 48 / (48 + distance))
const current = drag.edge === "start" ? trimStart : trimEnd
cut(drag.edge, current + deltaX / width * length * speed)
}
function endDrag(event: PointerEvent) {
if (drag?.pointer === event.pointerId) clearDrag()
}
function clearDrag() {
drag = undefined
active = null
}
function startDrag(which: "start" | "end", e: PointerEvent) {
trimPreviewState.dragging = which
const el = e.currentTarget as HTMLElement
el.setPointerCapture(e.pointerId)
void updateTrimPreview(which === "start" ? trimStart : trimEnd)
function key(event: KeyboardEvent, edge: Edge | "seek") {
const [min, max] = edge === "seek" ? [0, length] : limits(edge)
const current = edge === "seek" ? playhead : edge === "start" ? trimStart : trimEnd
const increment = event.shiftKey ? 1 : .04
const values: Record<string, number> = { Home:min, End:max, ArrowLeft:current-increment, ArrowDown:current-increment,
ArrowRight:current+increment, ArrowUp:current+increment }
if (!Object.hasOwn(values,event.key)) return
event.preventDefault()
if (edge === "seek") onSeek(bound(values[event.key], min, max))
else cut(edge, values[event.key])
}
function onDrag(e: PointerEvent) {
if (!trimPreviewState.dragging) return
const secs = pointerToSecs(e)
if (trimPreviewState.dragging === "start") {
trimStart = Math.min(secs, trimEnd - 0.1)
} else {
trimEnd = Math.max(secs, trimStart + 0.1)
}
void updateTrimPreview(secs)
function commitTime(event: Event, edge: Edge) {
const field = event.currentTarget as HTMLInputElement
const parts = /^(?:(\d+):)?(\d+(?:[.,]\d+)?|[.,]\d+)$/.exec(field.value.trim())
const seconds = parts ? Number(parts[2].replace(",", ".")) : NaN
if (!Number.isFinite(seconds) || (parts?.[1] && seconds >= 60)) { error = edge; return }
cut(edge, seconds + Number(parts?.[1] || 0) * 60)
field.value = timecode(edge === "start" ? trimStart : trimEnd)
}
function endDrag(e: PointerEvent) {
const el = e.currentTarget as HTMLElement
el.releasePointerCapture(e.pointerId)
trimPreviewState.dragging = null
trimPreviewState.path = null
}
function onTrackClick(e: PointerEvent) {
if (!trackEl) return
const secs = pointerToSecs(e)
const distToStart = Math.abs(secs - trimStart)
const distToEnd = Math.abs(secs - trimEnd)
if (distToStart < distToEnd) {
trimStart = Math.min(secs, trimEnd - 0.1)
} else {
trimEnd = Math.max(secs, trimStart + 0.1)
}
}
let trimmedDuration = $derived(Math.max(0.1, trimEnd - trimStart))
</script>
<div class="trim-block">
<div class="trim-labels">
<span class="mono">{trimStart.toFixed(2)}s</span>
<span class="trim-kept">{trimmedDuration.toFixed(2)}s kept</span>
<span class="mono">{trimEnd.toFixed(2)}s</span>
<svelte:window onpointermove={pointerMove} onpointerup={endDrag} onpointercancel={endDrag} onblur={clearDrag} />
<section class="timeline" aria-label="Trim clip">
<header class="row between wrap">
<div><h3>Trim clip</h3><p class="note" id={hintId}>While dragging a handle, move up or down for finer control.</p></div>
<div class="row wrap">
<span class="kept row note">Kept <strong class="mono">{keptDuration.toFixed(2)} s</strong></span>
<button type="button" class="button ghost" disabled={trimStart === 0 && trimEnd === length}
onclick={() => { trimStart = 0; trimEnd = length; error = null }}>Reset trim</button>
</div>
</header>
<div class="scale">
<div class="ruler mono" aria-hidden="true">
{#each marks as mark}
<span class="tick-mark" class:major={mark.index % 6 === 0} style:left={percent(mark.time)}>
{#if mark.index % 6 === 0}<span>{mark.index === 24 ? timecode(mark.time) : timecode(mark.time).split(".")[0]}</span>{/if}
</span>
{/each}
</div>
<div class="track" bind:this={track} style:--trim-start={percent(trimStart)} style:--trim-end={percent(trimEnd)}>
<div class="filmstrip" aria-hidden="true">
{#each frames as path}<img src={convertFileSrc(path)} alt="" />{/each}
</div>
<div class="trim-range" aria-hidden="true"></div>
<div class="playhead" aria-hidden="true" style:left={percent(playhead)}></div>
<div class="scrub" role="slider" tabindex="0" aria-label="Playback position" aria-valuemin={0} aria-valuemax={length}
aria-valuenow={bound(playhead,0,length)} aria-valuetext={timecode(playhead)}
onpointerdown={event => pointerDown(event,"seek")} onkeydown={event => key(event,"seek")}></div>
{#each boundaries as edge}
{@const value = edge.key === "start" ? trimStart : trimEnd}
<div class="trim-handle" class:start={edge.key === "start"} class:end={edge.key === "end"} style:left={percent(value)}
role="slider" tabindex="0" aria-label={"Trim " + edge.key} aria-describedby={hintId} aria-valuemin={limits(edge.key)[0]} aria-valuemax={limits(edge.key)[1]}
aria-valuenow={value} aria-valuetext={timecode(value)}
onpointerdown={event => pointerDown(event,edge.key)}
onpointerenter={() => hovered = edge.key} onpointerleave={() => hovered = null}
onfocus={event => { if (event.currentTarget.matches(":focus-visible")) focused = edge.key }}
onblur={() => focused = null} onkeydown={event => key(event,edge.key)}>
<IconGripVertical size={17} aria-hidden="true" />
</div>
{/each}
<span class="cue mono" bind:this={cue} aria-hidden="true" style:--cue={percent(shown === "start" ? trimStart : shown === "end" ? trimEnd : playhead)}>
{shown === "start" ? "Start " + timecode(trimStart) : shown === "end" ? "End " + timecode(trimEnd) : timecode(playhead)}
</span>
</div>
</div>
<div
class="trim-track"
bind:this={trackEl}
onpointerdown={onTrackClick}
role="none"
>
<div class="trim-range" style="left:{(trimStart/clip.duration_secs)*100}%; right:{(1-trimEnd/clip.duration_secs)*100}%"></div>
<div
class="trim-handle trim-start"
style="left:{(trimStart/clip.duration_secs)*100}%"
role="slider"
aria-label="trim start"
aria-valuemin={0}
aria-valuemax={trimEnd - 0.1}
aria-valuenow={trimStart}
tabindex="0"
onpointerdown={(e) => startDrag("start", e)}
onpointermove={onDrag}
onpointerup={endDrag}
onkeydown={(e) => {
const step = e.shiftKey ? 0.5 : 0.05
if (e.key === "ArrowLeft") { trimStart = Math.max(0, trimStart - step); e.preventDefault() }
else if (e.key === "ArrowRight") { trimStart = Math.min(trimEnd - 0.1, trimStart + step); e.preventDefault() }
}}
></div>
<div
class="trim-handle trim-end"
style="left:{(trimEnd/clip.duration_secs)*100}%"
role="slider"
aria-label="trim end"
aria-valuemin={trimStart + 0.1}
aria-valuemax={clip.duration_secs}
aria-valuenow={trimEnd}
tabindex="0"
onpointerdown={(e) => startDrag("end", e)}
onpointermove={onDrag}
onpointerup={endDrag}
onkeydown={(e) => {
const step = e.shiftKey ? 0.5 : 0.05
if (e.key === "ArrowLeft") { trimEnd = Math.max(trimStart + 0.1, trimEnd - step); e.preventDefault() }
else if (e.key === "ArrowRight") { trimEnd = Math.min(clip.duration_secs, trimEnd + step); e.preventDefault() }
}}
></div>
<div class="times">
{#each boundaries as edge}
<div class="row trim-value">
<label for={"time-" + edge.key}>{edge.title}</label>
<input class="field mono" id={"time-" + edge.key} type="text" inputmode="decimal"
value={timecode(edge.key === "start" ? trimStart : trimEnd)} aria-invalid={error === edge.key}
onchange={event => commitTime(event,edge.key)} onkeydown={event => {
if (event.key === "Enter") event.currentTarget.blur()
else if (event.key === "Escape") { event.currentTarget.value = timecode(edge.key === "start" ? trimStart : trimEnd); error = null }
}} />
<button type="button" class="button ghost" aria-label={"Set trim " + edge.key + " to playhead"} onclick={() => cut(edge.key,playhead)}>Set to playhead</button>
</div>
{/each}
</div>
<input type="range" min="0" max={clip.duration_secs} step="0.05" value={trimStart}
oninput={(e) => { const v = parseFloat((e.currentTarget as HTMLInputElement).value); trimStart = Math.min(v, trimEnd - 0.1) }}
class="sr-only" aria-label="trim start seconds" />
<input type="range" min="0" max={clip.duration_secs} step="0.05" value={trimEnd}
oninput={(e) => { const v = parseFloat((e.currentTarget as HTMLInputElement).value); trimEnd = Math.max(v, trimStart + 0.1) }}
class="sr-only" aria-label="trim end seconds" />
</div>
{#if error}<p class="problem note" role="alert">Enter seconds or a time such as 00:04.25.</p>{/if}
</section>
<style>
.trim-block { display: flex; flex-direction: column; gap: 8px; }
.trim-track {
position: relative;
height: 4px;
background: var(--bg-3);
border-radius: 2px;
cursor: pointer;
}
.trim-range {
position: absolute; top: 0; bottom: 0;
background: var(--accent);
border-radius: 2px;
pointer-events: none;
}
.trim-handle {
position: absolute; top: 50%; transform: translate(-50%, -50%);
width: 12px; height: 22px;
background: var(--accent);
border-radius: var(--r-sm);
cursor: ew-resize;
z-index: 1;
touch-action: none;
}
.trim-handle:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--accent-glow); }
.trim-labels {
display: flex;
justify-content: space-between;
font-size: 11px;
color: var(--text-3);
font-family: var(--mono);
}
.trim-kept { color: var(--accent); }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
.timeline { margin-top:16px; display:grid; gap:12px; background:var(--input); border:var(--edge) solid var(--rule); padding:12px; border-radius:var(--radius); --grip:26px; container-type:inline-size; }
header .note { margin-top:4px; }
.kept { padding:4px 8px; background:var(--caption); border-radius:var(--control-radius); }
.kept strong { color:var(--ink); }
header .button { min-height:32px; font-size:12px; }
.scale { padding-inline:var(--grip); }
.ruler { position:relative; height:26px; color:var(--muted); }
.tick-mark { position:absolute; bottom:0; height:4px; border-left:3px solid var(--rule); }
.tick-mark.major { height:7px; border-color:var(--field); }
.tick-mark.major > span { position:absolute; bottom:8px; transform:translateX(-50%); white-space:nowrap; font-size:10px; }
.tick-mark:last-child { transform:translateX(-3px); }
.tick-mark:last-child > span { right:0; transform:none; }
.track { height:clamp(58px,6vw,82px); position:relative; }
.filmstrip { position:absolute; inset:0; display:flex; gap:3px; border-radius:var(--mark-radius); overflow:hidden; background:var(--raised); }
.filmstrip img { min-width:0; flex:1 1 0; height:100%; object-fit:cover; }
.filmstrip::after { content:""; position:absolute; inset:0; background:linear-gradient(90deg,#0d151cd9 0 var(--trim-start),transparent var(--trim-start) var(--trim-end),#0d151cd9 var(--trim-end) 100%); }
.trim-range { position:absolute; inset:0 calc(100% - var(--trim-end)) 0 var(--trim-start); border-block:var(--edge) solid var(--signal); pointer-events:none; }
.scrub { position:absolute; inset:0; cursor:ew-resize; touch-action:none; }
.trim-handle { position:absolute; top:0; bottom:0; z-index:2; width:var(--grip); background:var(--signal); color:var(--signal-ink); display:grid; place-items:center; cursor:ew-resize; touch-action:none; }
.trim-handle.start { transform:translateX(-100%); border-radius:var(--control-radius) 0 0 var(--control-radius); }
.trim-handle.end { border-radius:0 var(--control-radius) var(--control-radius) 0; }
:global(:root[data-theme="light"]) .trim-handle { border:3px solid #52682b; }
.playhead { position:absolute; z-index:3; top:-4px; bottom:-4px; transform:translateX(-50%); width:var(--edge); background:#f0f2e9; outline:3px solid #141b2299; pointer-events:none; }
.playhead::before { content:""; position:absolute; left:-4px; width:11px; height:5px; background:inherit; border-radius:2px 2px 0 0; }
.cue { position:absolute; z-index:4; bottom:calc(100% + 8px); left:clamp(58px,var(--cue),calc(100% - 58px)); transform:translateX(-50%); opacity:0; pointer-events:none; white-space:nowrap; padding:4px 8px; border-radius:var(--control-radius); background:#263139; color:#f0f2e9; }
.times { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; }
.trim-value { padding:4px 8px; border-radius:var(--control-radius); background:var(--caption); }
.trim-value label { font-size:12px; }
.trim-value input { width:10ch; padding:4px; min-height:30px; }
.trim-value button { margin-left:auto; min-height:30px; font-size:12px; padding:4px 8px; }
.problem { color:var(--alert); }
@container (max-width:420px) { .times { grid-template-columns:1fr; } .tick-mark:nth-child(7) > span,.tick-mark:nth-child(19) > span { display:none; } }
</style>
+21 -7
View File
@@ -115,10 +115,10 @@ export type ExportRequest = {
target_bytes: number
fps: number
keep_audio: boolean
deleted_frame_indices: number[]
trim_start_secs?: number | null
trim_end_secs?: number | null
output_path?: string | null
overwrite?: boolean
crop?: CaptureRect | null
gif_budget_mode?: GifBudgetMode
gif_dither?: GifDither
@@ -132,6 +132,18 @@ export type ExportResult = {
met_target: boolean
}
export type OutputPreview = {
id: string
path: string
format: Format
size_bytes: number
target_bytes: number
width: number
height: number
fps: number
duration_secs: number
}
export type HotkeyRegistrationResult = {
start_ok: boolean | null
stop_ok: boolean | null
@@ -197,6 +209,8 @@ export const api = {
stopCapture: () => invoke<RecordedClip>("stop_capture"),
discardClip: () => invoke<void>("discard_clip"),
export: (request: ExportRequest) => invoke<ExportResult>("export", { request }),
exportDestination: (format: Format, path: string) =>
invoke<{ path: string; exists: boolean }>("export_destination", { format, path }),
revealInExplorer: (path: string) => invoke<void>("reveal_in_explorer", { path }),
showOverlay: () => invoke<void>("show_overlay"),
openWindowPicker: () => invoke<void>("open_window_picker"),
@@ -209,11 +223,13 @@ export const api = {
invoke<void>("set_overlay_to_window", { x, y, width, height }),
listWindows: () => invoke<WindowInfo[]>("list_windows"),
getOverlayRect: () => invoke<CaptureRect>("get_overlay_rect"),
extractThumbnails: (fps: number) =>
invoke<string[]>("extract_thumbnails", { fps }),
timelineThumbnails: () => invoke<string[]>("timeline_thumbnails"),
previewDisplay: (x: number, y: number) => invoke<ArrayBuffer>("preview_display", { x, y }),
renderPreview: (format: Format, fps: number, target_bytes: number, gif_budget_mode?: GifBudgetMode, gif_dither?: GifDither, gif_colors?: number) =>
invoke<string>("render_preview", { request: { format, fps, target_bytes, gif_budget_mode, gif_dither, gif_colors } }),
renderOutputPreview: (request: ExportRequest) =>
invoke<OutputPreview>("render_output_preview", { request }),
saveOutputPreview: (previewId: string, outputPath: string, overwrite: boolean) =>
invoke<ExportResult>("save_output_preview", { previewId, outputPath, overwrite }),
openOutputPreview: (previewId: string) => invoke<void>("open_output_preview", { previewId }),
estimateGifParams: (input: {
format: Format
fps: number
@@ -237,8 +253,6 @@ export const api = {
duration_secs: number
}) =>
invoke<GifEstimateTable>("estimate_gif_params_table", { request: input }),
renderRawPreview: (timestamp: number) =>
invoke<string>("render_raw_preview", { timestamp }),
defaultOutputPath: (format: Format) =>
invoke<string>("default_output_path", { format }),
openUrl: (url: string) => invoke<void>("open_url", { url }),
-15
View File
@@ -1,15 +0,0 @@
export const trimPreviewState = $state<{
dragging: "start" | "end" | null
path: string | null
bust: number
}>({
dragging: null,
path: null,
bust: 0,
})
export function resetTrimPreview() {
trimPreviewState.dragging = null
trimPreviewState.path = null
trimPreviewState.bust = 0
}
-1
View File
@@ -1,5 +1,4 @@
import { mount } from "svelte"
import "./app.css"
import "./ui.css"
import App from "./App.svelte"
import { installMotion } from "./lib/ui/motion"