pick the gif key color from the preview

This commit is contained in:
2026-11-15 20:18:00 +02:00
parent 81478cd08c
commit 8123558ad8
6 changed files with 170 additions and 8 deletions
+32 -1
View File
@@ -954,6 +954,32 @@ fn gif_rgb_scale_filter(width: u32, key: Option<GifColorKey>) -> String {
}
}
pub(crate) fn sample_gif_key_color(
ffmpeg: &Path, input: &Path, width: u32, x: u32, y: u32, seconds: f64,
) -> Result<String> {
use std::os::windows::process::CommandExt;
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
let scale = gif_source_rgb_scale(width);
let filter = format!("{scale},format=rgba,crop=1:1:{x}:{y}:exact=1,format=rgb24");
// Back off a microsecond so the seek includes the displayed frame.
let time = format!("{:.6}", (seconds - 0.000_001).max(0.0));
let output = Command::new(ffmpeg)
.creation_flags(CREATE_NO_WINDOW.0)
.args(["-v", "error", "-nostdin", "-ss", &time, "-i"])
.arg(input)
.args(["-vf", &filter, "-frames:v", "1", "-f", "rawvideo", "pipe:1"])
.output()
.context("sampling the recording color")?;
if !output.status.success() {
bail!(ffmpeg_failure_message("sampling the recording color", output.status, &output.stderr));
}
let [red, green, blue] = output.stdout.as_slice() else {
bail!("no frame color at the requested position");
};
Ok(format!("#{red:02x}{green:02x}{blue:02x}"))
}
#[derive(Debug, Clone)]
pub(crate) struct GifBudgetInput {
pub gif_colors: u16,
@@ -1797,7 +1823,12 @@ mod tests {
"-c:v", "libx264", "-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709"]).arg(&input.0);
run(&mut source, "test recording")?;
for key in [None, Some(GifColorKey { rgb: 0x00_ff_00, tolerance: 8 })] {
let green = sample_gif_key_color(&ffmpeg, &input.0, 128, 96, 48, 0.0)?;
let red = sample_gif_key_color(&ffmpeg, &input.0, 128, 96, 48, 1.0)?;
assert!(green.starts_with("#00f"), "{green}");
assert!(red.starts_with("#f"), "{red}");
let rgb = u32::from_str_radix(green.trim_start_matches('#'), 16)?;
for key in [None, Some(GifColorKey { rgb, tolerance: 8 })] {
let output = TempFileGuard::create_in(&dir, "review", "gif")?;
let mut request = dummy_request();
request.format = Format::Gif;
+12
View File
@@ -1166,6 +1166,17 @@ mod tests {
}
}
#[tauri::command(async)]
fn sample_gif_key_color(state: State<'_, AppState>, x: u32, y: u32, seconds: f64) -> Result<String, String> {
let clip = lock(&state.last_clip).clone().ok_or_else(|| "no recorded clip available".to_string())?;
if !seconds.is_finite() || seconds < 0.0 || x >= clip.width || y >= clip.height {
return Err("choose a pixel inside the recording".to_string());
}
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
encode::sample_gif_key_color(&ffmpeg, &clip.temp_path, clip.width, x, y, seconds.min(clip.duration_secs))
.map_err(|error| format!("{error:#}"))
}
#[tauri::command(async)]
fn extract_thumbnails(
state: State<'_, AppState>, fps: u32, start: u32,
@@ -2516,6 +2527,7 @@ pub fn run() {
export,
default_output_path,
export_destination,
sample_gif_key_color,
extract_thumbnails,
timeline_thumbnails,
preview_display,
+6
View File
@@ -523,6 +523,11 @@
previewSeek = { seconds, scrub }
}
function pickGifKeyColor(color: string) {
gifColorKey = { ...gifColorKey, color, enabled: true }
gifColors = Math.max(3, gifColors)
}
function changeFormat(next: Format) {
format = next
if (outputPath.trim()) {
@@ -817,6 +822,7 @@
</header>
<Preview path={clip.temp_path} label="Original recording" dimensions={clip.width + " × " + clip.height}
seek={previewSeek} bind:playhead {trimStart} {trimEnd}
onPickColor={format === "gif" && !previewLoading && !exportPending ? pickGifKeyColor : undefined}
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}
removals={format === "gif" ? removedFrames : []} onSeek={seekPreview}>
+117 -7
View File
@@ -1,23 +1,104 @@
<script lang="ts">
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"
import { IconColorPicker, IconPlayerPauseFilled, IconPlayerPlayFilled, IconPlayerSkipBackFilled, IconPlayerSkipForwardFilled, IconVolume, IconVolumeOff } from "./ui/icons"
import { onDestroy, tick, untrack } from "svelte"
import { api, convertFileSrc, type CaptureRect } from "./api"
import { appear, bound, fadeMotion, timecode } from "./ui/motion"
let { path, label, dimensions, seek = null, playbackRangeOnly = false, frameStep = .04,
playhead = $bindable(0), trimStart, trimEnd, crop, onOpenFile }: {
playhead = $bindable(0), trimStart, trimEnd, crop, onOpenFile, onPickColor }: {
path: string; label: string; dimensions: string; seek?: { seconds: number; scrub?: boolean } | null
playbackRangeOnly?: boolean; frameStep?: number
playhead?: number; trimStart: number; trimEnd: number
crop?: CaptureRect & { imageWidth: number; imageHeight: number }
onOpenFile?: () => void
onPickColor?: (color: string) => void
} = $props()
let player: HTMLVideoElement | undefined = $state()
let playing = $state(false)
let muted = $state(false)
let loadError = $state(false)
let frameReady = $state(false)
let pickingColor = $state(false)
let samplingColor = $state(false)
let colorError = $state("")
let pickButton = $state<HTMLButtonElement>()
let sampleTarget = $state<HTMLButtonElement>()
let pending: { seconds: number } | null = null
let presentedTime: number | undefined
let sampleRevision = 0
onDestroy(() => { sampleRevision++ })
$effect(() => {
if (onPickColor) return
sampleRevision++
pickingColor = false
samplingColor = false
colorError = ""
})
$effect(() => {
const video = player
if (!video || !onPickColor || typeof video.requestVideoFrameCallback !== "function") return
let request = video.requestVideoFrameCallback(function report(_now, frame) {
presentedTime = frame.mediaTime
request = video.requestVideoFrameCallback(report)
})
return () => {
video.cancelVideoFrameCallback(request)
presentedTime = undefined
}
})
async function toggleColorPicker() {
if (pickingColor) return finishColorPicker()
if (!player || !frameReady) return
player.pause()
colorError = ""
pickingColor = true
await tick()
sampleTarget?.focus({ preventScroll: true })
}
function finishColorPicker() {
sampleRevision++
pickingColor = false
samplingColor = false
colorError = ""
pickButton?.focus({ preventScroll: true })
}
async function sampleColor(event: MouseEvent) {
if (!player || !pickingColor || !onPickColor || samplingColor) return
if (player.seeking || player.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) {
colorError = "Wait for the frame to load, then try again."
return
}
const { videoWidth, videoHeight } = player
const rect = player.getBoundingClientRect()
const scale = Math.min(rect.width / videoWidth, rect.height / videoHeight)
if (!Number.isFinite(scale) || scale <= 0) return
// Ignore the bars that object-fit can leave around the video.
const x = event.detail === 0 ? videoWidth / 2
: (event.clientX - rect.left - (rect.width - videoWidth * scale) / 2) / scale
const y = event.detail === 0 ? videoHeight / 2
: (event.clientY - rect.top - (rect.height - videoHeight * scale) / 2) / scale
if (x < 0 || y < 0 || x >= videoWidth || y >= videoHeight) return
const revision = ++sampleRevision
samplingColor = true
colorError = ""
try {
const color = await api.sampleGifKeyColor(Math.floor(x), Math.floor(y), presentedTime ?? player.currentTime)
if (revision === sampleRevision && onPickColor) {
onPickColor(color)
finishColorPicker()
}
} catch {
if (revision === sampleRevision) colorError = "Couldn't read the frame color. Try another frame or use GIF settings."
} finally {
if (revision === sampleRevision) samplingColor = false
}
}
$effect(() => {
const request = seek
@@ -76,22 +157,46 @@
}
</script>
<svelte:window onkeydown={event => {
if (pickingColor && event.key === "Escape") {
event.preventDefault()
finishColorPicker()
}
}} />
<figure class="viewer">
<figcaption class="row between wrap">
<strong>{label}</strong><span class="mono note">{dimensions}</span>
<strong>{label}</strong>
<div class="row wrap">
<span class="mono note">{dimensions}</span>
{#if onPickColor}
<button type="button" class="button ghost eyedropper" bind:this={pickButton} onclick={toggleColorPicker}
disabled={!frameReady} aria-pressed={pickingColor}><IconColorPicker size={16} />Pick key color</button>
{/if}
</div>
</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} onseeked={finishSeek} onloadedmetadata={metadata} onerror={() => { loadError = true; playing = false }}></video>
ontimeupdate={updateTime} onseeked={finishSeek} onloadedmetadata={metadata} onloadstart={() => { frameReady = false }}
onloadeddata={() => { frameReady = true }} onerror={() => { loadError = true; playing = false; frameReady = 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}
{#if pickingColor && onPickColor}
<button type="button" class="sample-target" bind:this={sampleTarget} onclick={sampleColor}
aria-busy={samplingColor} aria-label="Sample a color from the recording. Enter samples the center."></button>
{/if}
</div>
{/key}
{#if pickingColor && onPickColor}
<p class="note color-hint" transition:fadeMotion role="status">
{samplingColor ? "Reading frame color..." : colorError || "Click the background to pick its color. Press Esc to cancel."}
</p>
{/if}
{#if loadError}
<div class="notice problem row between wrap" role="alert">
<p>The clip could not be played here.</p>
@@ -116,9 +221,14 @@
<style>
.viewer { padding:8px; display:grid; gap:8px; border:var(--edge) solid var(--rule); border-radius:var(--radius); background:var(--input); }
figcaption { padding:0 4px; }
.eyedropper { min-height:28px; padding:4px 7px; font-size:12px; }
.eyedropper[aria-pressed="true"] { color:var(--signal); }
.color-hint { 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; }
.sample-target { position:absolute; inset:0; padding:0; border:0; background:transparent; cursor:crosshair; }
.sample-target:focus-visible { outline-offset:-4px; }
.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; }
+2
View File
@@ -230,6 +230,8 @@ export const api = {
getOverlayRect: () => invoke<CaptureRect>("get_overlay_rect"),
extractThumbnails: (fps: number, start: number) =>
invoke<{ paths: string[]; has_more: boolean }>("extract_thumbnails", { fps, start }),
sampleGifKeyColor: (x: number, y: number, seconds: number) =>
invoke<string>("sample_gif_key_color", { x, y, seconds }),
timelineThumbnails: () => invoke<string[]>("timeline_thumbnails"),
previewDisplay: (x: number, y: number) => invoke<ArrayBuffer>("preview_display", { x, y }),
renderOutputPreview: (request: ExportRequest) =>
+1
View File
@@ -6,6 +6,7 @@ export { default as IconArrowRight } from "@tabler/icons-svelte/icons/arrow-righ
export { default as IconCheck } from "@tabler/icons-svelte/icons/check"
export { default as IconChevronDown } from "@tabler/icons-svelte/icons/chevron-down"
export { default as IconCircleCheck } from "@tabler/icons-svelte/icons/circle-check"
export { default as IconColorPicker } from "@tabler/icons-svelte/icons/color-picker"
export { default as IconCopy } from "@tabler/icons-svelte/icons/copy"
export { default as IconCrop } from "@tabler/icons-svelte/icons/crop"
export { default as IconDeviceDesktop } from "@tabler/icons-svelte/icons/device-desktop"