remove and restore gif frames

This commit is contained in:
2026-10-28 19:52:00 +02:00
parent b4d1d6c734
commit 15d2074393
8 changed files with 532 additions and 123 deletions
+178 -12
View File
@@ -12,7 +12,7 @@ use anyhow::{anyhow, bail, Context, Result};
use crate::clicks::Click;
use crate::config::{Format, GifBudgetMode, GifDither, Mp4Codec, WebmCodec};
use crate::CaptureRect;
use crate::{CaptureRect, SourceRange};
// Used both for bitrate budget calculation and final mux. Must be consistent.
const AUDIO_BITRATE_KBPS: u64 = 192;
@@ -102,6 +102,7 @@ pub(crate) struct TranscodeRequest {
pub crop: Option<CaptureRect>,
pub gif_budget_mode: GifBudgetMode,
pub gif_colors: u16,
pub gif_removed_ranges: Vec<SourceRange>,
pub trim_start_secs: Option<f64>,
pub trim_end_secs: Option<f64>,
pub clicks: Vec<Click>,
@@ -194,20 +195,66 @@ fn apply_trim(cmd: &mut Command, req: &TranscodeRequest) {
}
}
pub(crate) fn gif_cuts(mut ranges: Vec<SourceRange>, start: f64, end: f64) -> Result<Vec<SourceRange>> {
if ranges.iter().any(|range| !range.start_secs.is_finite() || !range.end_secs.is_finite()
|| range.start_secs < 0.0 || range.end_secs <= range.start_secs) {
bail!("invalid GIF frame removal range");
}
ranges.sort_by(|a, b| a.start_secs.total_cmp(&b.start_secs));
let mut merged: Vec<SourceRange> = Vec::new();
for range in ranges {
let start_secs = range.start_secs.max(start);
let end_secs = range.end_secs.min(end);
if end_secs <= start_secs { continue; }
if let Some(previous) = merged.last_mut().filter(|previous| previous.end_secs >= start_secs) {
previous.end_secs = previous.end_secs.max(end_secs);
} else {
merged.push(SourceRange { start_secs, end_secs });
}
}
Ok(merged)
}
fn gif_timeline_filter(req: &TranscodeRequest, effective_fps: u32) -> String {
let mut trim = Vec::new();
use std::fmt::Write as _;
if req.gif_removed_ranges.is_empty() {
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}");
return if trim.is_empty() {
fps
} else {
format!("trim={},setpts=PTS-STARTPTS,{fps}", trim.join(":"))
};
}
// Cut before resampling so changing FPS can't bring removed frames back.
// Only subtract gaps after the first kept frame.
let deleted: Vec<String> = req
.gif_removed_ranges
.iter()
.map(|range| format!("gte(t,{})*lt(t,{})", range.start_secs, range.end_secs))
.collect();
let gaps: Vec<String> = req.gif_removed_ranges.iter().map(|range| {
let end = range.end_secs;
let length = end - range.start_secs;
format!("(gte(PTS*TB,{end})-gte(STARTPTS*TB,{end}))*{length}")
}).collect();
let mut keep = format!("not({})", deleted.join("+"));
if let Some(start) = req.trim_start_secs {
trim.push(format!("start={start}"));
let _ = write!(keep, "*gte(t,{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 _ = write!(keep, "*lt(t,{end})");
}
format!("settb=AVTB,select='{keep}',setpts='PTS-STARTPTS-({})/TB',fps={effective_fps}:eof_action=pass,trim=duration={}",
gaps.join("+"), req.duration_secs)
}
fn crop_filter(crop: Option<CaptureRect>) -> Option<String> {
@@ -658,7 +705,7 @@ fn gif_calibration(
width: u32,
fps: u32,
) -> Option<(u32, u32)> {
if req.duration_secs <= 4.0 {
if req.duration_secs <= 4.0 || !req.gif_removed_ranges.is_empty() {
return None;
}
let (w, f) = calibrate_via_sample(ffmpeg, req, width, fps)?;
@@ -823,7 +870,7 @@ fn gif_filters(req: &TranscodeRequest, scale_width: u32, effective_fps: u32) ->
.map(|c| format!("{c},"))
.unwrap_or_default();
let timeline = gif_timeline_filter(req, effective_fps);
let stats = "diff";
let stats = if req.gif_removed_ranges.is_empty() { "diff" } else { "full" };
let dither = match req.gif_dither {
GifDither::FloydSteinberg => "floyd_steinberg",
@@ -1022,6 +1069,12 @@ fn parse_output_properties(report: &str) -> Option<OutputProperties> {
})
}
#[derive(serde::Serialize)]
pub(crate) struct ThumbnailPage {
pub paths: Vec<PathBuf>,
pub has_more: bool,
}
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");
@@ -1050,6 +1103,58 @@ pub(crate) fn display_preview(ffmpeg: &Path, x: i32, y: i32, width: u32, height:
Ok(output.stdout)
}
pub(crate) fn extract_thumbnails(
ffmpeg: &Path,
input: &Path,
out_dir: &Path,
fps: u32,
start: u32,
) -> Result<ThumbnailPage> {
const PAGE_SIZE: usize = 80;
if !(1..=60).contains(&fps) {
bail!("thumbnail frame rate must be between 1 and 60");
}
let page_dir = out_dir.join(format!("{fps}-{start}"));
std::fs::create_dir_all(&page_dir).context("creating thumbnail page")?;
for entry in std::fs::read_dir(&page_dir)?.flatten() {
drop(std::fs::remove_file(entry.path()));
}
// Seek in whole seconds to keep the sampling grid aligned with source time.
// A second of preroll gives the FPS filter the same frames at the page edge.
let seek_seconds = (start / fps).saturating_sub(1);
let page_start = start - seek_seconds * fps;
let filter = format!("fps={fps},trim=start_frame={page_start},setpts=PTS-STARTPTS,scale=120:-1:flags=lanczos");
let pattern = page_dir.join("thumb-%03d.png");
let mut cmd = Command::new(ffmpeg);
cmd.args(["-y", "-hide_banner"]);
if seek_seconds > 0 { cmd.arg("-ss").arg(seek_seconds.to_string()); }
cmd.arg("-i").arg(input)
.args(["-vf", &filter, "-frames:v", &(PAGE_SIZE + 1).to_string()])
.arg(&pattern);
run(&mut cmd, "thumbnail extraction")?;
let mut paths: Vec<PathBuf> = std::fs::read_dir(&page_dir)?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("png")))
.collect();
paths.sort();
let has_more = paths.len() > PAGE_SIZE;
if has_more {
if let Some(extra) = paths.pop() {
drop(std::fs::remove_file(extra));
}
}
for entry in std::fs::read_dir(out_dir)?.flatten() {
let path = entry.path();
if path != page_dir && entry.file_type().is_ok_and(|kind| kind.is_dir()) {
drop(std::fs::remove_dir_all(path));
}
}
Ok(ThumbnailPage { paths, has_more })
}
pub(crate) fn mux_with_audio(
ffmpeg: &Path,
video: &Path,
@@ -1495,6 +1600,7 @@ mod tests {
crop: None,
gif_budget_mode: GifBudgetMode::Balanced,
gif_colors: 256,
gif_removed_ranges: vec![],
trim_start_secs: None,
trim_end_secs: None,
clicks: vec![],
@@ -1590,6 +1696,66 @@ mod tests {
assert!(filter.contains("format=rgb24"));
}
#[test]
fn gif_cuts_are_applied_before_output_frame_rate_conversion() {
let mut req = dummy_request();
req.gif_removed_ranges = vec![SourceRange { start_secs: 0.4, end_secs: 0.5 }];
req.trim_start_secs = Some(0.2);
req.trim_end_secs = Some(0.8);
let selection = "settb=AVTB,select='not(gte(t,0.4)*lt(t,0.5))*gte(t,0.2)*lt(t,0.8)'";
let first = gif_timeline_filter(&req, 30);
assert!(first.starts_with(selection));
assert!(first.contains("setpts='PTS-STARTPTS-"));
req.fps = 5;
assert_eq!(gif_timeline_filter(&req, 5), first.replace("fps=30", "fps=5"));
}
#[test]
#[ignore = "requires FFmpeg; set BYTESIZE_TEST_FFMPEG"]
fn gif_source_cuts_close_gaps_without_reintroducing_frames_at_another_fps() -> 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-gif-cuts-test-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let input = TempFileGuard::create_in(&dir, "source", "mp4")?;
let mut source = Command::new(&ffmpeg);
source.args(["-y", "-hide_banner"]);
for color in ["green", "red", "blue"] {
source.args(["-f", "lavfi", "-i", &format!("color=c={color}:size=128x96:rate=10:duration=1")]);
}
source.args(["-filter_complex", "concat=n=3:v=1:a=0", "-c:v", "libx264"]).arg(&input.0);
run(&mut source, "test recording")?;
for fps in [5, 10] {
let output = TempFileGuard::create_in(&dir, "review", "gif")?;
let mut request = dummy_request();
request.input = input.0.clone();
request.output = output.0.clone();
request.scratch_dir = dir.clone();
request.format = Format::Gif;
request.target_bytes = 1_000_000;
request.clip_width = 128;
request.clip_height = 96;
request.duration_secs = 2.0;
request.fps = fps;
request.gif_removed_ranges = vec![SourceRange { start_secs: 1.0, end_secs: 2.0 }];
transcode(&ffmpeg, &request)?;
let media = inspect_output(&ffmpeg, &output.0)?;
assert!((media.duration_secs - 2.0).abs() < 0.02, "{media:?}");
let pixels = Command::new(&ffmpeg).args(["-v", "error", "-i"]).arg(&output.0)
.args(["-vf", "scale=1:1", "-fps_mode", "passthrough", "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1"]).output()?;
assert!(pixels.status.success());
let frames: Vec<_> = pixels.stdout.chunks_exact(3).collect();
assert_eq!(frames.len(), (fps * 2) as usize);
assert!(frames.iter().all(|pixel| pixel[0] < 30), "the red frames should stay removed at {fps} FPS");
assert!(frames.first().is_some_and(|first| first[1] > 80));
assert!(frames.last().is_some_and(|last| last[2] > 150), "expected blue at {fps} FPS, got {frames:?}");
}
drop(input);
std::fs::remove_dir(dir)?;
Ok(())
}
#[test]
fn audio_alignment_pads_whole_sample_frames_and_preserves_retry_gaps() {
let dir = std::env::temp_dir();
+46 -3
View File
@@ -55,6 +55,12 @@ pub struct CaptureRect {
pub height: u32,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub struct SourceRange {
pub start_secs: f64,
pub end_secs: f64,
}
pub struct AppState {
pub app_dir: PathBuf,
pub config: Mutex<Config>,
@@ -787,6 +793,10 @@ pub struct ExportRequest {
pub fps: u32,
pub keep_audio: bool,
#[serde(default)]
pub deleted_frame_indices: Vec<u32>,
#[serde(default)]
pub gif_removed_ranges: Vec<SourceRange>,
#[serde(default)]
pub trim_start_secs: Option<f64>,
#[serde(default)]
pub trim_end_secs: Option<f64>,
@@ -1005,7 +1015,7 @@ mod tests {
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,
scratch_dir: dir.clone(), crop: None, gif_removed_ranges: Vec::new(),
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,
};
@@ -1154,6 +1164,24 @@ mod tests {
}
}
#[tauri::command(async)]
fn extract_thumbnails(
state: State<'_, AppState>, fps: u32, start: u32,
) -> Result<encode::ThumbnailPage, String> {
let _page = 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 clip_name = clip.temp_path.file_stem().ok_or_else(|| "invalid clip file name".to_string())?;
let thumbs_dir = temp_dir(&state.app_dir).join("thumbs").join(clip_name);
encode::extract_thumbnails(&ffmpeg, &clip.temp_path, &thumbs_dir, fps, start)
.map_err(|e| format!("{e:#}"))
}
#[tauri::command(async)]
fn timeline_thumbnails(state: State<'_, AppState>) -> Result<Vec<PathBuf>, String> {
let _page = lock(&state.thumbnail_operation);
@@ -2001,7 +2029,7 @@ fn export_destination(
fn transcode_request(
state: &AppState,
request: ExportRequest,
mut request: ExportRequest,
output: PathBuf,
cancel: Arc<AtomicBool>,
) -> Result<encode::TranscodeRequest, String> {
@@ -2027,7 +2055,20 @@ fn transcode_request(
return Err("choose an export frame rate above zero".to_string());
}
let duration_secs = end - start;
let mut duration_secs = end - start;
let mut gif_removed_ranges = Vec::new();
if request.format == Format::Gif {
let rate = f64::from(request.fps);
request.gif_removed_ranges.extend(request.deleted_frame_indices.iter().map(|index| SourceRange {
start_secs: f64::from(*index) / rate,
end_secs: (f64::from(*index) + 1.0) / rate,
}));
gif_removed_ranges = encode::gif_cuts(request.gif_removed_ranges, start, end).map_err(|e| e.to_string())?;
duration_secs -= gif_removed_ranges.iter().map(|cut| cut.end_secs - cut.start_secs).sum::<f64>();
if duration_secs <= 0.01 {
return Err("restore frames or extend the trim to keep part of the GIF".to_string());
}
}
let (src_w, src_h, src_x, src_y) = clip.crop.map_or(
(clip.monitor_width, clip.monitor_height, 0, 0),
@@ -2059,6 +2100,7 @@ fn transcode_request(
scratch_dir: temp_dir(&state.app_dir),
crop: request.crop,
gif_budget_mode: request.gif_budget_mode,
gif_removed_ranges,
trim_start_secs: request.trim_start_secs,
trim_end_secs: request.trim_end_secs,
clicks,
@@ -2467,6 +2509,7 @@ pub fn run() {
export,
default_output_path,
export_destination,
extract_thumbnails,
timeline_thumbnails,
preview_display,
render_output_preview,
+5 -4
View File
@@ -15,13 +15,13 @@
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,
outputPath = $bindable(), invalidDraft = $bindable(), estimatedOutput, trimmedDuration, cropInvalid, emptyGif, disabled,
reviewState, onPathInput, onBrowse, onReview, onSave,
}: {
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
estimatedOutput: string; trimmedDuration: number; cropInvalid: boolean; emptyGif: boolean; disabled: boolean
reviewState: "none" | "current" | "stale"
onPathInput: () => void; onBrowse: () => void; onReview: () => void; onSave: () => void
} = $props()
@@ -71,10 +71,11 @@
<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}>
{#if emptyGif}<p class="note error" role="alert">Restore frames or extend the trim to keep part of the GIF.</p>{/if}
<button type="button" class="button primary full" onclick={onReview} disabled={disabled || cropInvalid || emptyGif}>
{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}>
<button type="button" class="button ghost full" onclick={onSave} disabled={disabled || cropInvalid || emptyGif || invalidDraft !== null}>
{reviewState === "current" ? "Save reviewed " + format.toUpperCase() : "Save " + format.toUpperCase() + " without preview"}
</button>
</div>
+227 -93
View File
@@ -1,102 +1,236 @@
<script lang="ts">
import { convertFileSrc } from "./api"
import { gsap } from "gsap"
import { untrack } from "svelte"
import type { Action } from "svelte/action"
import { api, convertFileSrc, type SourceRange } from "./api"
import { clipRanges, mergeRanges, rangesDuration, subtractRanges } from "./gifFrames"
import { IconArrowLeft, IconArrowRight, IconCheck, IconChevronDown, IconMinus, IconScissors } from "./ui/icons"
import { animate, bound, disclosure, fadeMotion, timecode } from "./ui/motion"
let {
thumbnails,
deletedFrames,
loading,
onToggle,
onClear,
}: {
thumbnails: string[]
deletedFrames: Set<number>
loading: boolean
onToggle: (idx: number) => void
onClear: () => void
import { scrollbar } from "./ui/scrollbar"
let { fps, playhead, trimStart, trimEnd, removed = $bindable(), disabled, onSeek }: {
fps: number; playhead: number; trimStart: number; trimEnd: number; removed: SourceRange[]
disabled: boolean; onSeek: (seconds: number) => void
} = $props()
const pageSize = 80
const panelId = $props.id()
let open = $state(false)
let strip = $state<HTMLDivElement>()
let chevron = $state<HTMLElement>()
let page = $state<{ start: number; fps: number; paths: string[] }>()
let failure = $state("")
let retry = $state(0)
let selected = $state<SourceRange[]>([])
let anchor: number | null = null
let focusFrame = $state<number>()
let queue = Promise.resolve()
let firstFrame = $derived(Math.floor(trimStart * fps + 0.000_001))
let lastFrame = $derived(Math.max(firstFrame, Math.ceil(trimEnd * fps - 0.000_001) - 1))
let activeFrame = $derived(bound(Math.floor(playhead * fps + 0.000_001), firstFrame, lastFrame))
let start = $derived(Math.floor(activeFrame / pageSize) * pageSize)
let visiblePage = $derived(page?.start === start && page?.fps === fps ? page : undefined)
let activeSelection = $derived(clipRanges(selected, trimStart, trimEnd))
let selectedCount = $derived.by(() => activeSelection.reduce((total, range) =>
total + Math.ceil(range.end_secs * fps - 0.000_001) - Math.floor(range.start_secs * fps + 0.000_001), 0))
let removedTime = $derived(rangesDuration(clipRanges(removed, trimStart, trimEnd)))
let nextCuts = $derived(mergeRanges([...removed, ...activeSelection]))
let additionalTime = $derived(rangesDuration(subtractRanges(activeSelection, removed)))
let keepsFrames = $derived(trimEnd - trimStart - rangesDuration(clipRanges(nextCuts, trimStart, trimEnd)) > .01)
let canRestore = $derived(activeSelection.some(range => coverage(removed, range) > 0))
function coverage(ranges: SourceRange[], range: SourceRange) {
const length = range.end_secs - range.start_secs
return length > 0 ? bound(rangesDuration(clipRanges(ranges, range.start_secs, range.end_secs)) / length, 0, 1) : 0
}
function span(first: number, last = first): SourceRange {
return { start_secs: Math.max(trimStart, Math.min(first, last) / fps), end_secs: Math.min(trimEnd, (Math.max(first, last) + 1) / fps) }
}
function seek(frame: number) {
onSeek(Math.max(trimStart, frame / fps))
}
function choose(frame: number, range: boolean, extra: boolean) {
const selection = span(range ? anchor ?? frame : frame, frame)
if (extra) {
selected = !range && coverage(selected, selection) > 0
? subtractRanges(selected, [selection]) : mergeRanges([...selected, selection])
} else {
selected = [selection]
}
if (!range || anchor === null) anchor = frame
seek(frame)
}
function removeSelected() {
if (!disabled && keepsFrames && additionalTime > 0.000_001) removed = nextCuts
}
function restoreSelected() {
removed = subtractRanges(removed, activeSelection)
}
function key(event: KeyboardEvent, frame: number) {
if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) {
event.preventDefault()
const next = event.key === "Home" ? firstFrame : event.key === "End" ? lastFrame
: bound(frame + (event.key === "ArrowRight" ? 1 : -1), firstFrame, lastFrame)
if (next === frame) return
focusFrame = next
choose(next, event.shiftKey, event.ctrlKey || event.metaKey)
} else if (event.key === "Delete") {
event.preventDefault()
removeSelected()
} else if (event.key === "Escape") {
event.preventDefault()
selected = []
anchor = null
}
}
function toggle(opening: boolean) {
open = opening
if (chevron) animate(chevron, { rotation: opening ? 180 : 0 })
if (!opening) {
selected = []
anchor = null
focusFrame = undefined
}
}
$effect(() => {
void fps
untrack(() => { selected = []; anchor = null })
})
$effect(() => {
void retry
const offset = start
const rate = fps
if (!open || visiblePage) return
let current = true
failure = ""
queue = queue.then(async () => {
if (!current) return
try {
const result = await api.extractThumbnails(rate, offset)
if (current) page = { start: offset, fps: rate, paths: result.paths }
} catch (error) {
if (current) failure = String(error)
}
})
return () => { current = false }
})
$effect(() => {
const frame = activeFrame
if (!open || !strip || !visiblePage) return
const item = strip.querySelector<HTMLElement>("[data-frame='" + frame + "']")
if (!item) return
if (focusFrame === frame) { item.focus({ preventScroll: true }); focusFrame = undefined }
if (item.offsetLeft < strip.scrollLeft || item.offsetLeft + item.offsetWidth > strip.scrollLeft + strip.clientWidth) {
animate(strip, { scrollLeft: Math.max(0, item.offsetLeft - (strip.clientWidth - item.offsetWidth) / 2) })
}
})
type FrameState = { selected: boolean; removed: number; active: boolean }
const frameMotion: Action<HTMLElement, FrameState> = (node, state) => {
const values = (state: FrameState) => ({ "--selected": Number(state.selected), "--removed": state.removed, "--active": Number(state.active) })
gsap.set(node, values(state))
return { update: next => animate(node, values(next)), destroy: () => gsap.killTweensOf(node) }
}
const availability: Action<HTMLElement, boolean> = (node, enabled) => {
const opacity = (enabled: boolean) => ({ opacity: enabled ? 1 : .54 })
gsap.set(node, opacity(enabled))
return { update: next => animate(node, opacity(next)), destroy: () => gsap.killTweensOf(node) }
}
let canRemove = $derived(!disabled && keepsFrames && additionalTime > 0.000_001)
let canRestoreAll = $derived(!disabled && removed.length > 0)
</script>
<div class="frames-block">
<div class="frames-head">
<span class="section-title">Frames</span>
{#if deletedFrames.size > 0}
<button class="text-btn" onclick={onClear}>Clear ({deletedFrames.size})</button>
{/if}
</div>
{#if loading}
<p class="frames-hint">extracting...</p>
{:else}
<div class="frames-strip">
{#each thumbnails as path, idx}
<button
class="frame-thumb"
class:del={deletedFrames.has(idx)}
onclick={() => onToggle(idx)}
aria-pressed={deletedFrames.has(idx)}
aria-label="frame {idx+1} - {deletedFrames.has(idx) ? 'deleted, click to restore' : 'click to delete'}"
title={deletedFrames.has(idx) ? "restore" : "delete"}
>
<img src={convertFileSrc(path)} alt="" loading="lazy" />
<span class="frame-idx">{idx+1}</span>
</button>
{/each}
<details class="frame-tool" use:disclosure={toggle}>
<summary class="row between" aria-controls={panelId}>
<span class="row"><IconScissors size={17} />{#key open}<span in:fadeMotion>{open ? "Done removing frames" : "Remove frames"}</span>{/key}</span>
<span class="row"><span class="note mono">{removedTime > 0 ? removedTime.toFixed(2) + " s removed" : ""}</span><span class="chevron" bind:this={chevron}><IconChevronDown size={16} /></span></span>
</summary>
<div class="disclosure-body" id={panelId} inert={!open}>
<div class="frame-content stack">
<div class="row between wrap">
<p class="note">Click to inspect. Shift-click for a range, Ctrl-click to toggle individual frames.</p>
<div class="row">
<button type="button" class="button ghost icon-only" aria-label="Previous frames" disabled={disabled || start <= firstFrame}
onclick={() => seek(Math.max(firstFrame, start - 1))}><IconArrowLeft size={16} /></button>
<button type="button" class="button ghost icon-only" aria-label="Next frames" disabled={disabled || start + pageSize > lastFrame}
onclick={() => seek(start + pageSize)}><IconArrowRight size={16} /></button>
</div>
</div>
<div class="thumbnail-scroll">
<div class="strip" bind:this={strip} use:scrollbar={"x"} role="group" aria-label="GIF frames" aria-busy={!visiblePage && !failure}>
{#if open && visiblePage}
{#each visiblePage.paths as path, index (index)}
{@const frame = visiblePage.start + index}
{@const interval = span(frame)}
{#if frame >= firstFrame && frame <= lastFrame}
{@const cut = coverage(removed, interval)}
{@const picked = coverage(activeSelection, interval) > 0}
<button type="button" class="button thumb" data-frame={frame} tabindex={frame === activeFrame ? 0 : -1}
use:frameMotion={{ selected: picked, removed: cut > 0 ? Math.max(.65, cut) : 0, active: frame === activeFrame }}
{disabled} aria-pressed={picked}
aria-label={"Frame " + (frame + 1) + " at " + timecode(frame / fps) + (cut > .999 ? ", removed" : cut > 0 ? ", partly removed" : "")}
onclick={event => choose(frame, event.shiftKey, event.ctrlKey || event.metaKey)} onkeydown={event => key(event, frame)}>
<div class="thumbnail">
{#if path}<img src={convertFileSrc(path)} alt="" draggable="false" in:fadeMotion />{/if}
<span class="omitted"><IconMinus size={13} /></span><span class="picked"><IconCheck size={13} /></span>
</div>
<span class="mono timestamp">{timecode(frame / fps)}</span>
</button>
{/if}
{/each}
{:else if failure}
<div class="row between wrap">
<p class="note selectable" role="alert">{failure}</p>
<button type="button" class="button" onclick={() => retry++}>Retry thumbnails</button>
</div>
{:else}
<p class="note">Loading frames...</p>
{/if}
</div>
</div>
<div class="row between wrap">
<p class="note" aria-live="polite">{selectedCount ? selectedCount + (selectedCount === 1 ? " frame selected" : " frames selected") : "Select frames to remove or restore."}</p>
<div class="row wrap">
<button type="button" class="button ghost" use:availability={canRestoreAll} disabled={!canRestoreAll} onclick={() => removed = []}>Restore all</button>
<button type="button" class="button ghost" use:availability={!disabled && canRestore} disabled={disabled || !canRestore} onclick={restoreSelected}>Restore selected</button>
<button type="button" class="button" use:availability={canRemove} disabled={!canRemove} onclick={removeSelected}>Remove selected</button>
</div>
</div>
{#if !keepsFrames && additionalTime > 0.000_001}<p class="note" role="status" transition:fadeMotion>Keep part of the GIF inside the trim.</p>{/if}
</div>
{/if}
</div>
</div>
</details>
<style>
.frames-block { display: flex; flex-direction: column; gap: 8px; }
.frames-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);
}
.frames-hint { margin: 0; font-size: 11px; color: var(--text-3); }
.frames-strip {
display: flex;
gap: 4px;
overflow-x: auto;
padding-bottom: 4px;
}
.frames-strip::-webkit-scrollbar { height: 3px; }
.frames-strip::-webkit-scrollbar-thumb { background: var(--border-2); border-radius: 2px; }
.frame-thumb {
flex: 0 0 auto;
position: relative;
padding: 0;
border: 1px solid transparent;
border-radius: var(--r-sm);
background: transparent;
cursor: pointer;
overflow: hidden;
transition: border-color 80ms;
}
.frame-thumb img { display: block; width: 64px; height: auto; border-radius: 2px; }
.frame-thumb:hover { border-color: var(--accent); }
.frame-thumb.del img { opacity: 0.2; filter: grayscale(1); }
.frame-thumb.del { border-color: var(--err); }
.frame-idx {
position: absolute; bottom: 2px; right: 3px;
font-family: var(--mono); font-size: 9px;
color: var(--text-3);
background: rgba(0,0,0,0.6);
padding: 0 3px;
border-radius: 2px;
}
.text-btn {
background: none;
border: none;
color: var(--accent);
cursor: pointer;
font-size: 11px;
font-family: var(--sans);
padding: 0;
transition: color 80ms;
}
.text-btn:hover { color: var(--accent-hover); }
.frame-tool { border-top:1px solid var(--rule); padding-top:10px; }
summary { width:100%; min-height:36px; padding:7px 10px; border-radius:var(--control-radius); background:var(--caption); }
summary::marker { content:""; }
summary::-webkit-details-marker { display:none; }
.chevron { display:grid; place-items:center; color:var(--muted); }
.frame-content { min-width:0; padding-top:12px; }
.frame-content .button { min-height:32px; font-size:12px; }
.thumbnail-scroll { position:relative; min-width:0; }
.strip { position:relative; display:flex; gap:7px; overflow:auto hidden; min-height:91px; padding:5px 5px 14px; }
.thumb { display:grid; flex:0 0 79px; align-content:start; gap:0; padding:0; border-radius:6px; background:var(--caption);
box-shadow:inset 0 0 0 2px color-mix(in srgb,transparent,var(--signal) calc(var(--selected,0) * 100%)); }
.thumbnail { position:relative; width:75px; height:45px; margin:2px 2px 0; border-radius:3px; background:var(--raised); }
.thumbnail img { display:block; width:100%; height:45px; object-fit:cover; border-radius:3px; filter:grayscale(var(--removed,0)) brightness(calc(1 - var(--removed,0) * .48)); }
.thumbnail span { position:absolute; top:3px; width:17px; height:17px; display:grid; place-items:center; border-radius:3px; }
.omitted { left:3px; background:var(--alert); color:var(--alert-ink); opacity:var(--removed,0); }
.picked { right:3px; background:var(--signal); color:var(--signal-ink); opacity:var(--selected,0); }
.timestamp { padding:3px 1px; color:color-mix(in srgb,var(--muted),var(--ink) calc(var(--active,0) * 100%)); }
.thumb:focus-visible { outline-offset:1px; }
</style>
+21 -6
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { onDestroy, onMount } from "svelte"
import { api, convertFileSrc, formatBytes, type Config, type CaptureConfig, type Format, type GifBudgetMode, type GifDither, type RecordedClip, type ExportResult, type ExportRequest, type OutputPreview, type CaptureRect } from "./api"
import { api, convertFileSrc, formatBytes, type Config, type CaptureConfig, type Format, type GifBudgetMode, type GifDither, type RecordedClip, type ExportResult, type ExportRequest, type OutputPreview, type CaptureRect, type SourceRange } from "./api"
import { open } from "@tauri-apps/plugin-dialog"
import { emit, listen } from "@tauri-apps/api/event"
import { monitorFromPoint, primaryMonitor, type Monitor } from "@tauri-apps/api/window"
@@ -18,8 +18,10 @@
import Preview from "./Preview.svelte"
import ReviewPlayer from "./ReviewPlayer.svelte"
import OutputDestination from "./OutputDestination.svelte"
import FramesStrip from "./FramesStrip.svelte"
import ExportSidebar from "./ExportSidebar.svelte"
import { minTargetMB } from "./exportSizing"
import { clipRanges, rangesDuration } from "./gifFrames"
type Phase = "idle" | "recording" | "paused" | "editing" | "review" | "exporting" | "done" | "export-error" | "export-canceled"
const workflow = ["Record", "Trim", "Review output", "Save"]
@@ -57,6 +59,7 @@
let cropW: number = $state(0)
let cropH: number = $state(0)
let removedFrames = $state<SourceRange[]>([])
// Preview
let renderedOutput = $state<{ file: OutputPreview; key: string } | null>(null)
@@ -116,7 +119,9 @@
let sourceLabel = $derived.by(() => source === "window" ? "Selected window" : source === "region" ? "Custom region" : "Primary display")
let currentImage = $derived.by(() => displayImage?.x === currentMonitor?.position.x && displayImage?.y === currentMonitor?.position.y ? displayImage?.url : undefined)
let trimmedDuration = $derived(Math.max(0, trimEnd - trimStart))
let activeGifCuts = $derived.by(() => format === "gif" ? clipRanges(removedFrames, trimStart, trimEnd) : [])
let trimmedDuration = $derived(Math.max(0, trimEnd - trimStart - rangesDuration(activeGifCuts)))
let emptyGif = $derived.by(() => format === "gif" && activeGifCuts.length > 0 && trimmedDuration <= .01)
let cropInvalid = $derived.by(() => !!clip && cropEnabled && (
![cropX, cropY, cropW, cropH].every(Number.isInteger)
|| cropX < 0 || cropY < 0 || cropW < 2 || cropH < 2 || cropW % 2 !== 0 || cropH % 2 !== 0
@@ -393,6 +398,7 @@
if (source !== "display") toastOnFail(api.hideOverlay())
frameOpen = false
clip = c
removedFrames = []
playhead = 0
timelineFrames = []
void api.timelineThumbnails().then(paths => { if (clip?.temp_path === c.temp_path) timelineFrames = paths }).catch(console.warn)
@@ -469,6 +475,7 @@
format, fps, crop,
target_bytes: Math.round(targetMB * 1_048_576),
keep_audio: keepAudio && format !== "gif",
gif_removed_ranges: activeGifCuts,
trim_start_secs: trimStart > 0 ? trimStart : null,
trim_end_secs: clip && trimEnd < clip.duration_secs ? trimEnd : null,
gif_budget_mode: format === "gif" ? gifBudgetMode : undefined,
@@ -478,7 +485,7 @@
}
async function reviewOutput() {
if (!clip || cropInvalid || previewLoading || exportPending) return
if (!clip || cropInvalid || emptyGif || previewLoading || exportPending) return
phase = "review"
if (outputPreview) return
const request = currentEditRequest()
@@ -520,7 +527,7 @@
}
async function saveOutput() {
if (!clip || exportPending || previewLoading || cropInvalid || invalidOutputName !== null) return
if (!clip || exportPending || previewLoading || cropInvalid || emptyGif || invalidOutputName !== null) return
const reviewed = outputPreview
if (phase === "review" && !reviewed) return
exportPending = true
@@ -559,6 +566,7 @@
function startOver() {
clip = null; exportResult = null; errMsg = null; encodeProgress = null
removedFrames = []
renderedOutput = null
previewFailure = ""
previewSeek = null
@@ -804,11 +812,18 @@
seek={previewSeek} bind:playhead {trimStart} {trimEnd}
crop={cropEnabled && !cropInvalid ? { x: cropX, y: cropY, width: cropW, height: cropH, imageWidth: clip.width, imageHeight: clip.height } : undefined} />
<TrimPanel {clip} bind:trimStart bind:trimEnd {playhead} frames={timelineFrames} keptDuration={trimmedDuration}
onSeek={seekPreview} />
removals={format === "gif" ? removedFrames : []} onSeek={seekPreview}>
{#snippet gifFrames()}
{#if format === "gif"}
<FramesStrip {fps} {playhead} {trimStart} {trimEnd}
bind:removed={removedFrames} disabled={exportPending} onSeek={seekPreview} />
{/if}
{/snippet}
</TrimPanel>
</div>
<ExportSidebar {clip} {format} onFormat={changeFormat} bind:targetMB bind:fps bind:keepAudio bind:gifBudgetMode bind:gifDither bind:gifColors
bind:cropEnabled bind:cropX bind:cropY bind:cropW bind:cropH bind:outputPath bind:invalidDraft={invalidOutputName}
{estimatedOutput} {trimmedDuration} {cropInvalid} {reviewState}
{estimatedOutput} {trimmedDuration} {cropInvalid} {emptyGif} {reviewState}
disabled={previewLoading || exportPending} onPathInput={() => pathOverridden = true} onBrowse={browseOutput}
onReview={reviewOutput} onSave={saveOutput} />
</section>
+14 -5
View File
@@ -1,14 +1,15 @@
<script lang="ts">
import { IconGripVertical } from "./ui/icons"
import { convertFileSrc } from "./api"
import { animate, bound, timecode } from "./ui/motion"
import type { Snippet } from "svelte"
import { convertFileSrc, type SourceRange } from "./api"
import { animate, bound, fadeMotion, timecode } from "./ui/motion"
type Edge = "start" | "end"
type Drag = { pointer: number } & ({ edge: "seek" } | { edge: Edge; lastX: number })
let { clip, trimStart = $bindable(), trimEnd = $bindable(), playhead, frames, keptDuration, onSeek }: {
let { clip, trimStart = $bindable(), trimEnd = $bindable(), playhead, frames, keptDuration, removals, gifFrames, onSeek }: {
clip: { duration_secs: number }; trimStart: number; trimEnd: number
playhead: number; frames: string[]; keptDuration: number
onSeek: (seconds: number) => void
playhead: number; frames: string[]; keptDuration: number; removals: SourceRange[]
gifFrames?: Snippet; onSeek: (seconds: number) => void
} = $props()
let length = $derived(clip.duration_secs)
let minimum = $derived(Math.min(.1, length))
@@ -120,6 +121,11 @@
<div class="filmstrip" aria-hidden="true">
{#each frames as path}<img src={convertFileSrc(path)} alt="" />{/each}
</div>
<div class="removals" aria-hidden="true">
{#each removals as range (range.start_secs + "-" + range.end_secs)}
<span class="removed-range" style:left={percent(range.start_secs)} style:right={"calc(100% - " + percent(range.end_secs) + ")"} transition:fadeMotion></span>
{/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}
@@ -156,6 +162,7 @@
</div>
{/each}
</div>
{@render gifFrames?.()}
{#if error}<p class="problem note" role="alert">Enter seconds or a time such as 00:04.25.</p>{/if}
</section>
@@ -176,6 +183,8 @@
.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%); }
.removals { position:absolute; inset:0; pointer-events:none; clip-path:inset(0 calc(100% - var(--trim-end)) 0 var(--trim-start)); }
.removed-range { position:absolute; top:0; bottom:0; min-width:1px; border-bottom:4px solid var(--alert); background:color-mix(in srgb,var(--alert-plane) 74%,transparent); }
.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; }
+5
View File
@@ -115,6 +115,7 @@ export type ExportRequest = {
target_bytes: number
fps: number
keep_audio: boolean
gif_removed_ranges?: SourceRange[]
trim_start_secs?: number | null
trim_end_secs?: number | null
output_path?: string | null
@@ -125,6 +126,8 @@ export type ExportRequest = {
gif_colors?: number
}
export type SourceRange = { start_secs: number; end_secs: number }
export type ExportResult = {
output_path: string
size_bytes: number
@@ -223,6 +226,8 @@ 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, start: number) =>
invoke<{ paths: string[]; has_more: boolean }>("extract_thumbnails", { fps, start }),
timelineThumbnails: () => invoke<string[]>("timeline_thumbnails"),
previewDisplay: (x: number, y: number) => invoke<ArrayBuffer>("preview_display", { x, y }),
renderOutputPreview: (request: ExportRequest) =>
+36
View File
@@ -0,0 +1,36 @@
import type { SourceRange } from "./api"
const EPSILON = 0.000_001
export function mergeRanges(ranges: readonly SourceRange[]): SourceRange[] {
const sorted = [...ranges].sort((a, b) => a.start_secs - b.start_secs)
const merged: SourceRange[] = []
for (const range of sorted) {
const previous = merged.at(-1)
if (previous && range.start_secs <= previous.end_secs + EPSILON) {
previous.end_secs = Math.max(previous.end_secs, range.end_secs)
} else {
merged.push({ ...range })
}
}
return merged
}
export function clipRanges(ranges: readonly SourceRange[], start: number, end: number): SourceRange[] {
return ranges.map(range => ({ start_secs: Math.max(start, range.start_secs), end_secs: Math.min(end, range.end_secs) }))
.filter(range => range.end_secs - range.start_secs > EPSILON)
}
export function subtractRanges(ranges: readonly SourceRange[], subtracted: readonly SourceRange[]): SourceRange[] {
return subtracted.reduce<SourceRange[]>((remaining, cut) => remaining.flatMap(range => {
if (cut.end_secs <= range.start_secs || cut.start_secs >= range.end_secs) return [range]
const pieces = []
if (cut.start_secs - range.start_secs > EPSILON) pieces.push({ start_secs: range.start_secs, end_secs: cut.start_secs })
if (range.end_secs - cut.end_secs > EPSILON) pieces.push({ start_secs: cut.end_secs, end_secs: range.end_secs })
return pieces
}), [...ranges])
}
export function rangesDuration(ranges: readonly SourceRange[]) {
return ranges.reduce((duration, range) => duration + range.end_secs - range.start_secs, 0)
}