tighten export and capture handling

This commit is contained in:
2026-06-04 23:09:13 +03:00
parent a48d82ddc9
commit 4ca802ef71
14 changed files with 736 additions and 456 deletions
+122 -68
View File
@@ -176,6 +176,17 @@ fn capture_thread(
unsafe { unsafe {
let _ = client.Stop(); let _ = client.Stop();
} }
// Drain any remaining packets that were buffered before Stop().
// Without this, the last ~5ms of audio would be silently dropped.
drain_remaining_packets(
&capture_client,
channels,
bits_per_sample,
is_float,
&mut writer,
)?;
writer.flush().context("flushing audio writer")?; writer.flush().context("flushing audio writer")?;
result result
@@ -198,74 +209,7 @@ fn capture_loop(
}; };
while packet_length > 0 { while packet_length > 0 {
let mut data_ptr = std::ptr::null_mut(); write_next_packet(capture_client, channels, bits_per_sample, is_float, writer)?;
let mut num_frames_available = 0u32;
let mut flags = 0u32;
// SAFETY: GetBuffer provides valid data_ptr and metadata for the current packet.
unsafe {
capture_client
.GetBuffer(
&mut data_ptr,
&mut num_frames_available,
&mut flags,
None,
None,
)
.context("GetBuffer")?;
}
if num_frames_available > 0 {
let is_silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0;
let samples = (num_frames_available as usize) * (channels as usize);
if is_silent {
let zero_bytes = samples * 4;
let zeros = vec![0u8; zero_bytes];
writer.write_all(&zeros).context("writing silent audio")?;
} else if is_float {
let num_bytes = samples * (bits_per_sample as usize / 8);
// SAFETY: data_ptr from GetBuffer is valid for num_bytes.
let slice = unsafe {
std::slice::from_raw_parts(data_ptr as *const u8, num_bytes)
};
writer.write_all(slice).context("writing audio data")?;
} else {
match bits_per_sample {
16 => {
// SAFETY: data_ptr from GetBuffer points to valid i16 samples.
let i16_slice = unsafe {
std::slice::from_raw_parts(data_ptr as *const i16, samples)
};
for &sample in i16_slice {
let f = sample as f32 / 32768.0;
writer
.write_all(&f.to_le_bytes())
.context("writing f32 sample")?;
}
}
32 => {
// SAFETY: data_ptr from GetBuffer points to valid i32 samples.
let i32_slice = unsafe {
std::slice::from_raw_parts(data_ptr as *const i32, samples)
};
for &sample in i32_slice {
let f = sample as f32 / 2147483648.0;
writer
.write_all(&f.to_le_bytes())
.context("writing f32 sample")?;
}
}
_ => bail!("unsupported bits per sample: {bits_per_sample}"),
}
}
}
// SAFETY: Releases the buffer obtained from GetBuffer. Standard WASAPI pattern.
unsafe {
capture_client
.ReleaseBuffer(num_frames_available)
.context("ReleaseBuffer")?;
}
// SAFETY: Standard WASAPI query for the next available packet size. // SAFETY: Standard WASAPI query for the next available packet size.
packet_length = unsafe { packet_length = unsafe {
@@ -279,3 +223,113 @@ fn capture_loop(
} }
Ok(()) Ok(())
} }
fn write_next_packet(
capture_client: &IAudioCaptureClient,
channels: u16,
bits_per_sample: u16,
is_float: bool,
writer: &mut BufWriter<File>,
) -> Result<()> {
let mut data_ptr = std::ptr::null_mut();
let mut num_frames_available = 0u32;
let mut flags = 0u32;
// SAFETY: GetBuffer provides valid data_ptr and metadata for the current packet.
unsafe {
capture_client
.GetBuffer(
&mut data_ptr,
&mut num_frames_available,
&mut flags,
None,
None,
)
.context("GetBuffer")?;
}
let write_result = (|| -> Result<()> {
if num_frames_available == 0 {
return Ok(());
}
let is_silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0;
let samples = (num_frames_available as usize) * (channels as usize);
if is_silent {
let zeros = vec![0u8; samples * 4];
writer.write_all(&zeros).context("writing silent audio")?;
} else if is_float {
let num_bytes = samples * (bits_per_sample as usize / 8);
// SAFETY: data_ptr from GetBuffer is valid for num_bytes.
let slice = unsafe { std::slice::from_raw_parts(data_ptr as *const u8, num_bytes) };
writer.write_all(slice).context("writing audio data")?;
} else {
match bits_per_sample {
16 => {
// SAFETY: data_ptr from GetBuffer points to valid i16 samples.
let i16_slice =
unsafe { std::slice::from_raw_parts(data_ptr as *const i16, samples) };
for &sample in i16_slice {
let f = sample as f32 / 32768.0;
writer
.write_all(&f.to_le_bytes())
.context("writing f32 sample")?;
}
}
32 => {
// SAFETY: data_ptr from GetBuffer points to valid i32 samples.
let i32_slice =
unsafe { std::slice::from_raw_parts(data_ptr as *const i32, samples) };
for &sample in i32_slice {
let f = sample as f32 / 2147483648.0;
writer
.write_all(&f.to_le_bytes())
.context("writing f32 sample")?;
}
}
_ => bail!("unsupported bits per sample: {bits_per_sample}"),
}
}
Ok(())
})();
// SAFETY: Releases the buffer obtained from GetBuffer. Standard WASAPI pattern.
let release_result = unsafe {
capture_client
.ReleaseBuffer(num_frames_available)
.context("ReleaseBuffer")
};
write_result?;
release_result?;
Ok(())
}
fn drain_remaining_packets(
capture_client: &IAudioCaptureClient,
channels: u16,
bits_per_sample: u16,
is_float: bool,
writer: &mut BufWriter<File>,
) -> Result<()> {
// SAFETY: Standard WASAPI query for the next available packet size.
let mut packet_length = unsafe {
capture_client
.GetNextPacketSize()
.context("GetNextPacketSize")?
};
while packet_length > 0 {
write_next_packet(capture_client, channels, bits_per_sample, is_float, writer)?;
// SAFETY: Standard WASAPI query for the next available packet size.
packet_length = unsafe {
capture_client
.GetNextPacketSize()
.context("GetNextPacketSize")?
};
}
Ok(())
}
+51 -27
View File
@@ -1,5 +1,5 @@
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::{self, Cursor}; use std::io::{self, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
@@ -118,21 +118,39 @@ where
None None
}; };
let archive = if let Some(ref hash) = expected { let app_dir = dest
download_verified(&client, &asset.browser_download_url, hash, on_progress) .parent()
.await .and_then(|p| p.parent())
.with_context(|| format!("downloading {}", asset.browser_download_url))? .context("invalid dest path for temp archive")?;
let scratch_dir = app_dir.join("temp");
fs::create_dir_all(&scratch_dir).context("creating temp dir for archive")?;
let archive_path = scratch_dir.join(format!(
"ffmpeg-archive-{}.tmp",
source.name.to_lowercase()
));
if let Some(ref hash) = expected {
download_verified(
&client,
&asset.browser_download_url,
hash,
&archive_path,
on_progress,
)
.await
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
} else { } else {
download_plain(&client, &asset.browser_download_url, on_progress) download_plain(&client, &asset.browser_download_url, &archive_path, on_progress)
.await .await
.with_context(|| format!("downloading {}", asset.browser_download_url))? .with_context(|| format!("downloading {}", asset.browser_download_url))?;
}; };
match source.kind { let result = match source.kind {
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive, dest)?, ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest),
ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive, dest)?, ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest),
} };
Ok(()) let _ = fs::remove_file(&archive_path);
result
} }
/// Fetch and parse a SHA-256 checksums file from GyanD. /// Fetch and parse a SHA-256 checksums file from GyanD.
@@ -174,23 +192,25 @@ async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> {
async fn download_plain<F>( async fn download_plain<F>(
client: &reqwest::Client, client: &reqwest::Client,
url: &str, url: &str,
dest: &Path,
mut on_progress: F, mut on_progress: F,
) -> Result<Vec<u8>> ) -> Result<()>
where where
F: FnMut(u64, Option<u64>), F: FnMut(u64, Option<u64>),
{ {
let resp = client.get(url).send().await?.error_for_status()?; let resp = client.get(url).send().await?.error_for_status()?;
let total = resp.content_length(); let total = resp.content_length();
let mut buf: Vec<u8> = Vec::with_capacity(total.unwrap_or(0) as usize); let mut file = std::fs::File::create(dest).context("creating archive temp file")?;
let mut downloaded = 0u64; let mut downloaded = 0u64;
let mut stream = resp.bytes_stream(); let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await { while let Some(chunk) = stream.next().await {
let chunk = chunk?; let chunk = chunk?;
buf.extend_from_slice(&chunk); file.write_all(&chunk)?;
downloaded += chunk.len() as u64; downloaded += chunk.len() as u64;
on_progress(downloaded, total); on_progress(downloaded, total);
} }
Ok(buf) file.flush()?;
Ok(())
} }
async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(GithubAsset, String)> { async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(GithubAsset, String)> {
@@ -224,33 +244,36 @@ async fn download_verified<F>(
client: &reqwest::Client, client: &reqwest::Client,
url: &str, url: &str,
expected: &[u8; 32], expected: &[u8; 32],
dest: &Path,
on_progress: &mut F, on_progress: &mut F,
) -> Result<Vec<u8>> ) -> Result<()>
where where
F: FnMut(u64, Option<u64>), F: FnMut(u64, Option<u64>),
{ {
let resp = client.get(url).send().await?.error_for_status()?; let resp = client.get(url).send().await?.error_for_status()?;
let total = resp.content_length(); let total = resp.content_length();
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();
let mut buf: Vec<u8> = Vec::with_capacity(total.unwrap_or(0) as usize); let mut file = std::fs::File::create(dest).context("creating archive temp file")?;
let mut downloaded = 0u64; let mut downloaded = 0u64;
let mut stream = resp.bytes_stream(); let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await { while let Some(chunk) = stream.next().await {
let chunk = chunk?; let chunk = chunk?;
hasher.update(&chunk); hasher.update(&chunk);
buf.extend_from_slice(&chunk); file.write_all(&chunk)?;
downloaded += chunk.len() as u64; downloaded += chunk.len() as u64;
on_progress(downloaded, total); on_progress(downloaded, total);
} }
file.flush()?;
let got: [u8; 32] = hasher.finalize().into(); let got: [u8; 32] = hasher.finalize().into();
if &got != expected { if &got != expected {
let _ = std::fs::remove_file(dest);
bail!( bail!(
"sha256 mismatch: expected {} got {}", "sha256 mismatch: expected {} got {}",
hex::encode(expected), hex::encode(expected),
hex::encode(got) hex::encode(got)
); );
} }
Ok(buf) Ok(())
} }
fn is_ffmpeg_entry(name: &str) -> bool { fn is_ffmpeg_entry(name: &str) -> bool {
@@ -265,7 +288,7 @@ fn is_ffmpeg_entry(name: &str) -> bool {
.unwrap_or(false) .unwrap_or(false)
} }
fn extract_ffmpeg_from_7z(archive: &[u8], dest: &Path) -> Result<()> { fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> {
let app_dir = dest let app_dir = dest
.parent() .parent()
.and_then(|p| p.parent()) .and_then(|p| p.parent())
@@ -274,9 +297,10 @@ fn extract_ffmpeg_from_7z(archive: &[u8], dest: &Path) -> Result<()> {
let _ = fs::remove_dir_all(&scratch); let _ = fs::remove_dir_all(&scratch);
fs::create_dir_all(&scratch).context("create 7z scratch dir")?; fs::create_dir_all(&scratch).context("create 7z scratch dir")?;
let reader = Cursor::new(archive); let file = std::fs::File::open(archive_path).context("opening 7z archive")?;
let extract_result = sevenz_rust2::decompress_with_extract_fn(reader, &scratch, |_, _, _| Ok(true)) let extract_result =
.map_err(|e| anyhow!("7z extraction failed: {e}")); sevenz_rust2::decompress_with_extract_fn(file, &scratch, |_, _, _| Ok(true))
.map_err(|e| anyhow!("7z extraction failed: {e}"));
let found = find_ffmpeg_in(&scratch); let found = find_ffmpeg_in(&scratch);
let _ = fs::remove_dir_all(&scratch); let _ = fs::remove_dir_all(&scratch);
@@ -305,9 +329,9 @@ fn find_ffmpeg_in(dir: &Path) -> Option<PathBuf> {
None None
} }
fn extract_ffmpeg_from_zip(archive: &[u8], dest: &Path) -> Result<()> { fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> {
let reader = Cursor::new(archive); let file = std::fs::File::open(archive_path).context("opening zip archive")?;
let mut zip = zip::ZipArchive::new(reader).context("open zip archive")?; let mut zip = zip::ZipArchive::new(file).context("open zip archive")?;
for i in 0..zip.len() { for i in 0..zip.len() {
let mut entry = zip.by_index(i)?; let mut entry = zip.by_index(i)?;
if entry.is_dir() { if entry.is_dir() {
+9
View File
@@ -329,6 +329,10 @@ impl CaptureSession {
/// Re-encode the intermediate file with correct timestamps. /// Re-encode the intermediate file with correct timestamps.
/// The capture declares -framerate N and applies fps=M filter. /// The capture declares -framerate N and applies fps=M filter.
/// This scales PTS to match real-time duration. /// This scales PTS to match real-time duration.
///
/// Idempotent: if `input` has already been consumed (e.g. a previous
/// pause/resume cycle ran this to completion and removed it), and
/// `output` exists, returns Ok without re-running ffmpeg.
pub fn fix_intermediate_fps( pub fn fix_intermediate_fps(
ffmpeg: &std::path::Path, ffmpeg: &std::path::Path,
input: &std::path::Path, input: &std::path::Path,
@@ -339,6 +343,11 @@ pub fn fix_intermediate_fps(
) -> Result<()> { ) -> Result<()> {
use std::process::Command; use std::process::Command;
if !input.is_file() && output.is_file() {
tracing::debug!("capture fix: input already consumed, output exists, skipping");
return Ok(());
}
if frame_count == 0 || elapsed_secs <= 0.0 { if frame_count == 0 || elapsed_secs <= 0.0 {
tracing::warn!("capture fix: no frames counted, keeping original"); tracing::warn!("capture fix: no frames counted, keeping original");
let _ = std::fs::rename(input, output); let _ = std::fs::rename(input, output);
+23 -2
View File
@@ -148,8 +148,29 @@ impl Config {
match toml::from_str::<Self>(&raw) { match toml::from_str::<Self>(&raw) {
Ok(cfg) => Ok(cfg), Ok(cfg) => Ok(cfg),
Err(e) => { Err(e) => {
let backup = path.with_extension("toml.bak"); // Use a timestamped backup so successive corruptions don't
tracing::warn!("config.toml is corrupt ({}), backing up to {:?} and using defaults", e, backup); // clobber each other. Falls back to .toml.bak if the
// timestamped name collides for some reason.
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let stem = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("config");
let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("toml");
let backup = path.with_file_name(format!("{stem}-{ts}.{ext}.bak"));
let backup = if backup.exists() {
path.with_extension("toml.bak")
} else {
backup
};
tracing::warn!(
"config.toml is corrupt ({}), backing up to {:?} and using defaults",
e,
backup
);
let _ = std::fs::copy(path, &backup); let _ = std::fs::copy(path, &backup);
let cfg = Self::default(); let cfg = Self::default();
cfg.save(path)?; cfg.save(path)?;
+162 -58
View File
@@ -140,18 +140,14 @@ pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
match req.format { match req.format {
Format::Mp4 => { Format::Mp4 => {
let codec = pick_video_codec( let requested = mp4_video_codec(req.mp4_codec);
&encoders, let codec = require_video_codec(&encoders, requested, "MP4")?;
&[mp4_video_codec(req.mp4_codec), "libx264"],
)?;
let audio = pick_audio_codec(&encoders, &["aac", "libfdk_aac"])?; let audio = pick_audio_codec(&encoders, &["aac", "libfdk_aac"])?;
two_pass_video(ffmpeg, req, codec, audio, "mp4") two_pass_video(ffmpeg, req, codec, audio, "mp4")
} }
Format::Webm => { Format::Webm => {
let codec = pick_video_codec( let requested = webm_video_codec(req.webm_codec);
&encoders, let codec = require_video_codec(&encoders, requested, "WebM")?;
&[webm_video_codec(req.webm_codec), "libvpx-vp9", "libvpx"],
)?;
let audio = pick_audio_codec(&encoders, &["libopus", "libvorbis"])?; let audio = pick_audio_codec(&encoders, &["libopus", "libvorbis"])?;
two_pass_video(ffmpeg, req, codec, audio, "webm") two_pass_video(ffmpeg, req, codec, audio, "webm")
} }
@@ -159,6 +155,18 @@ pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
} }
} }
fn require_video_codec<'a>(
encoders: &HashSet<String>,
requested: &'a str,
container: &str,
) -> Result<&'a str> {
if encoders.contains(requested) {
Ok(requested)
} else {
bail!("{container} codec unavailable: ffmpeg does not include {requested}")
}
}
use std::sync::OnceLock; use std::sync::OnceLock;
static ENCODER_CACHE: OnceLock<HashSet<String>> = OnceLock::new(); static ENCODER_CACHE: OnceLock<HashSet<String>> = OnceLock::new();
@@ -191,21 +199,6 @@ fn list_encoders(ffmpeg: &Path) -> Result<&'static HashSet<String>> {
Ok(ENCODER_CACHE.get().unwrap()) Ok(ENCODER_CACHE.get().unwrap())
} }
fn pick_video_codec<'a>(
encoders: &HashSet<String>,
candidates: &[&'a str],
) -> Result<&'a str> {
for c in candidates {
if encoders.contains(*c) {
return Ok(c);
}
}
bail!(
"no video encoder available - tried {}",
candidates.join(", ")
)
}
fn pick_audio_codec<'a>( fn pick_audio_codec<'a>(
encoders: &HashSet<String>, encoders: &HashSet<String>,
candidates: &[&'a str], candidates: &[&'a str],
@@ -298,7 +291,21 @@ fn two_pass_video(
let dur = req.duration_secs; let dur = req.duration_secs;
let fps = req.fps; let fps = req.fps;
let cancel = req.cancel.clone(); let cancel = req.cancel.clone();
run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref(), cancel.as_ref())?; let pass_start = std::time::Instant::now();
run_with_progress(
&mut pass1,
"pass 1",
1,
2,
dur,
fps,
tx.as_ref(),
cancel.as_ref(),
)?;
tracing::info!(
elapsed_ms = pass_start.elapsed().as_millis(),
"ffmpeg pass 1 finished"
);
// Send 50% to signal pass 1 done, pass 2 starting. // Send 50% to signal pass 1 done, pass 2 starting.
if let Some(ref t) = tx { if let Some(ref t) = tx {
@@ -328,7 +335,21 @@ fn two_pass_video(
pass2.arg("-an"); pass2.arg("-an");
} }
pass2.arg(&req.output); pass2.arg(&req.output);
run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref(), cancel.as_ref())?; let pass_start = std::time::Instant::now();
run_with_progress(
&mut pass2,
"pass 2",
2,
2,
dur,
fps,
tx.as_ref(),
cancel.as_ref(),
)?;
tracing::info!(
elapsed_ms = pass_start.elapsed().as_millis(),
"ffmpeg pass 2 finished"
);
cleanup_pass_logs(&log_stem); cleanup_pass_logs(&log_stem);
Ok(()) Ok(())
@@ -365,18 +386,29 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
}; };
let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height); let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height);
let target = req.target_bytes; let target = req.target_bytes;
let max_retries = 6; // Retry budget scales with the input. A 5s clip rarely needs more than 3-4
// attempts; a 60s clip with tight target and high colors can take 8-10.
// Cap at 12 to avoid runaway loops on pathological inputs.
let max_retries = ((req.duration_secs / 5.0).ceil() as u32 + 4).clamp(5, 12);
let mut prev_actual: Option<u64> = None;
for attempt in 0..max_retries { for attempt in 0..max_retries {
if req.cancel.as_ref().map_or(false, |c| c.load(Ordering::Relaxed)) { if req.cancel.as_ref().map_or(false, |c| c.load(Ordering::Relaxed)) {
bail!("export cancelled"); bail!("export cancelled");
} }
// Last resort: use minimal settings to hit the target // Last resort: use minimal settings to hit the target
if attempt == 5 { if attempt == max_retries - 1 {
scale_width = (scale_width / 2).max(60); scale_width = (scale_width / 2).max(60);
effective_fps = 1; effective_fps = 1;
} }
let pass_start = std::time::Instant::now();
encode_gif_pass(ffmpeg, req, scale_width, effective_fps)?; encode_gif_pass(ffmpeg, req, scale_width, effective_fps)?;
tracing::info!(
attempt = attempt + 1,
elapsed_ms = pass_start.elapsed().as_millis(),
"gif pass finished"
);
let actual = std::fs::metadata(&req.output) let actual = std::fs::metadata(&req.output)
.map(|m| m.len()) .map(|m| m.len())
@@ -397,29 +429,69 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
return Ok(()); return Ok(());
} }
// Only adjust DOWN when file is too big - never exceed target // Compute a shrink factor. Clamp the multiplicative shrink between
// File is too big - scale down based on budget priority // 0.6 and 0.9 so a single bad estimate can't half the resolution in
// one step (which is the oscillation problem) and so we don't creep
// toward the target at a snail's pace.
let raw_factor = match req.gif_budget_mode {
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 (which the old `factor = ratio.sqrt()`
// would do after a large overshoot).
let half = 0.5_f64;
(ratio * (1.0 - half) + ratio.sqrt() * half).clamp(0.1, 1.0)
}
};
let mut factor = raw_factor.clamp(0.6, 0.9);
// Track trend across attempts. If shrinking settings did not shrink
// the file, or moved us farther from the target, force the strongest
// allowed shrink next time instead of creeping/oscillating.
if let Some(prev) = prev_actual {
let prev_dist = (target as f64 - prev as f64).abs();
let cur_dist = (target as f64 - actual as f64).abs();
if actual >= prev || cur_dist > prev_dist {
tracing::warn!(
"gif encode: retry trend worsened. prev={}B, now={}B. using stronger shrink.",
prev,
actual
);
factor = 0.6;
}
}
match req.gif_budget_mode { match req.gif_budget_mode {
GifBudgetMode::Resolution => { GifBudgetMode::Resolution => {
// Reduce fps (resolution is priority, keep it) effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
effective_fps = ((effective_fps as f64 * ratio).round() as u32).max(1);
} }
GifBudgetMode::Framerate => { GifBudgetMode::Framerate => {
// Reduce resolution (fps is priority, keep it) scale_width = ((scale_width as f64 * factor).round() as u32 / 2)
scale_width = ((scale_width as f64 * ratio.sqrt()).round() as u32 / 2).max(60).min(1280) * 2; .max(60)
.min(1280)
* 2;
} }
GifBudgetMode::Balanced => { GifBudgetMode::Balanced => {
// Reduce both scale_width = ((scale_width as f64 * factor).round() as u32 / 2)
let factor = ratio.sqrt(); .max(60)
scale_width = ((scale_width as f64 * factor).round() as u32 / 2).max(60).min(1280) * 2; .min(1280)
* 2;
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1); effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
} }
} }
tracing::info!( tracing::info!(
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps", "gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps (factor={:.2})",
attempt + 1, actual, target, scale_width, effective_fps attempt + 1,
actual,
target,
scale_width,
effective_fps,
factor
); );
prev_actual = Some(actual);
} }
// All retries exhausted - warn if still over target // All retries exhausted - warn if still over target
@@ -505,7 +577,7 @@ pub struct GifBudgetInput {
} }
pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> (u32, u32) { pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> (u32, u32) {
let aspect = if clip_height > 0 { clip_width as f64 / clip_height as f64 } else { 16.0 / 9.0 }; let aspect = aspect_ratio(clip_width, clip_height);
// GIF LZW compression on typical screen content averages ~0.2 bytes/pixel at 256 colors. // GIF LZW compression on typical screen content averages ~0.2 bytes/pixel at 256 colors.
// Real compression varies 3-5x depending on content (solid colors compress much better // Real compression varies 3-5x depending on content (solid colors compress much better
// than gradients/noise). The retry loop in encode_gif handles correction on mismatch. // than gradients/noise). The retry loop in encode_gif handles correction on mismatch.
@@ -555,6 +627,23 @@ pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) ->
} }
} }
pub fn aspect_ratio(width: u32, height: u32) -> f64 {
if height > 0 {
width as f64 / height as f64
} else {
16.0 / 9.0
}
}
pub fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32) -> u32 {
let aspect = aspect_ratio(clip_width, clip_height);
if width == 0 {
0
} else {
((width as f64 / aspect).round() as u32 / 2) * 2
}
}
pub fn render_preview( pub fn render_preview(
ffmpeg: &Path, ffmpeg: &Path,
input: &Path, input: &Path,
@@ -709,7 +798,7 @@ pub fn mux_with_audio(
} }
pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> { pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
use std::io::{Read, Write}; use std::io::Write;
if segments.is_empty() { if segments.is_empty() {
bail!("no audio segments to concatenate"); bail!("no audio segments to concatenate");
} }
@@ -719,15 +808,9 @@ pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
let mut out = std::fs::File::create(output).context("creating audio concat file")?; let mut out = std::fs::File::create(output).context("creating audio concat file")?;
for seg in segments { for seg in segments {
let mut f = std::fs::File::open(seg).with_context(|| format!("opening {seg:?}"))?; let mut f = std::fs::File::open(seg).with_context(|| format!("opening {seg:?}"))?;
let mut buf = vec![0u8; 64 * 1024]; std::io::copy(&mut f, &mut out).context("copying audio segment")?;
loop {
let n = f.read(&mut buf)?;
if n == 0 {
break;
}
out.write_all(&buf[..n])?;
}
} }
out.flush()?;
Ok(()) Ok(())
} }
@@ -777,9 +860,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
fn run(cmd: &mut Command, label: &str) -> Result<()> { fn run(cmd: &mut Command, label: &str) -> Result<()> {
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None)?; let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None)?;
if !output.status.success() { if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr); bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, head);
} }
Ok(()) Ok(())
} }
@@ -798,13 +879,36 @@ fn run_with_progress(
) -> Result<()> { ) -> Result<()> {
let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned(), cancel.cloned())?; let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned(), cancel.cloned())?;
if !output.status.success() { if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr); bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, head);
} }
Ok(()) Ok(())
} }
fn ffmpeg_failure_message(label: &str, status: std::process::ExitStatus, stderr: &[u8]) -> String {
let text = String::from_utf8_lossy(stderr);
let head: String = text.lines().take(12).collect::<Vec<_>>().join("\n");
let lower = text.to_ascii_lowercase();
let hint = if lower.contains("unknown encoder")
|| lower.contains("error while opening encoder")
{
Some("selected codec is not available in this ffmpeg build")
} else if lower.contains("permission denied") {
Some("output path is not writable")
} else if lower.contains("no such file or directory") {
Some("input or output path does not exist")
} else if lower.contains("invalid data found") {
Some("input clip could not be read")
} else if lower.contains("invalid argument") {
Some("ffmpeg rejected one of the encode settings")
} else {
None
};
match hint {
Some(h) => format!("ffmpeg {label} failed: {h}. Details: {head}"),
None => format!("ffmpeg {label} exited with {status}: {head}"),
}
}
fn run_impl( fn run_impl(
cmd: &mut Command, cmd: &mut Command,
label: &str, label: &str,
@@ -914,11 +1018,11 @@ fn parse_frame_from_stderr(line: &str) -> Option<f64> {
mod tests { mod tests {
use super::*; use super::*;
// Paths are empty - these tests only exercise bitrate math, not ffmpeg.
fn dummy_request() -> TranscodeRequest { fn dummy_request() -> TranscodeRequest {
let dir = std::env::temp_dir().join(format!("bytesize-encode-test-{}", std::process::id()));
TranscodeRequest { TranscodeRequest {
input: PathBuf::new(), input: dir.join("input.mp4"),
output: PathBuf::new(), output: dir.join("output.mp4"),
format: Format::Mp4, format: Format::Mp4,
target_bytes: 0, target_bytes: 0,
duration_secs: 10.0, duration_secs: 10.0,
@@ -927,7 +1031,7 @@ mod tests {
gif_dither: GifDither::FloydSteinberg, gif_dither: GifDither::FloydSteinberg,
webm_codec: WebmCodec::Vp9, webm_codec: WebmCodec::Vp9,
mp4_codec: Mp4Codec::H264, mp4_codec: Mp4Codec::H264,
scratch_dir: PathBuf::new(), scratch_dir: dir.join("scratch"),
crop: None, crop: None,
gif_budget_mode: GifBudgetMode::Balanced, gif_budget_mode: GifBudgetMode::Balanced,
gif_colors: 256, gif_colors: 256,
+42 -11
View File
@@ -182,12 +182,49 @@ struct SaveConfigResult {
hotkey_result: HotkeyRegistrationResult, hotkey_result: HotkeyRegistrationResult,
} }
fn validate_config(config: &Config) -> Result<(), String> {
let mut keys = Vec::new();
if let Some(k) = config
.hotkeys
.start
.as_deref()
.filter(|s| !s.trim().is_empty())
{
keys.push(("start", k));
}
if let Some(k) = config
.hotkeys
.stop
.as_deref()
.filter(|s| !s.trim().is_empty())
{
keys.push(("stop", k));
}
if let Some(k) = config
.hotkeys
.pause
.as_deref()
.filter(|s| !s.trim().is_empty())
{
keys.push(("pause", k));
}
for (i, (a, ka)) in keys.iter().enumerate() {
for (b, kb) in keys.iter().skip(i + 1) {
if ka.eq_ignore_ascii_case(kb) {
return Err(format!("duplicate hotkey: {a} and {b} both use {ka}"));
}
}
}
Ok(())
}
#[tauri::command] #[tauri::command]
fn save_config( fn save_config(
app: AppHandle, app: AppHandle,
state: State<'_, AppState>, state: State<'_, AppState>,
config: Config, config: Config,
) -> Result<SaveConfigResult, String> { ) -> Result<SaveConfigResult, String> {
validate_config(&config)?;
let path = config::config_path(&state.app_dir); let path = config::config_path(&state.app_dir);
config.save(&path).map_err(|e| format!("{e:#}"))?; config.save(&path).map_err(|e| format!("{e:#}"))?;
*lock(&state.config) = config.clone(); *lock(&state.config) = config.clone();
@@ -794,16 +831,7 @@ fn estimate_gif_params(request: PreviewRequest) -> GifEstimate {
gif_budget_mode: request.gif_budget_mode, gif_budget_mode: request.gif_budget_mode,
}; };
let (w, fps) = encode::gif_params(&budget, request.clip_width, request.clip_height); let (w, fps) = encode::gif_params(&budget, request.clip_width, request.clip_height);
let aspect = if request.clip_height > 0 { let height = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
request.clip_width as f64 / request.clip_height as f64
} else {
16.0 / 9.0
};
let height = if w == 0 {
0
} else {
((w as f64 / aspect).round() as u32 / 2) * 2
};
let dims_label = format!("{w}x{height} @ {fps}fps"); let dims_label = format!("{w}x{height} @ {fps}fps");
GifEstimate { width: w, fps, height, dims_label } GifEstimate { width: w, fps, height, dims_label }
} }
@@ -845,7 +873,7 @@ mod tests {
assert_eq!(est.fps, encode_fps); assert_eq!(est.fps, encode_fps);
// height should be a multiple of 2 and within aspect // height should be a multiple of 2 and within aspect
assert_eq!(est.height % 2, 0); assert_eq!(est.height % 2, 0);
let expected_height = ((encode_w as f64 / (1920.0 / 1080.0)).round() as u32 / 2) * 2; let expected_height = encode::gif_height_for_width(encode_w, 1920, 1080);
assert_eq!(est.height, expected_height); assert_eq!(est.height, expected_height);
// dims_label should be "{w}x{h} @ {fps}fps" // dims_label should be "{w}x{h} @ {fps}fps"
assert_eq!(est.dims_label, format!("{}x{} @ {}fps", encode_w, est.height, encode_fps)); assert_eq!(est.dims_label, format!("{}x{} @ {}fps", encode_w, est.height, encode_fps));
@@ -1571,7 +1599,10 @@ pub fn run() {
let registry = tracing_subscriber::registry().with(env_filter).with(file_layer); let registry = tracing_subscriber::registry().with(env_filter).with(file_layer);
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout)); let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout));
#[cfg(test)]
let _ = registry.try_init(); let _ = registry.try_init();
#[cfg(not(test))]
registry.init();
let webview_dir = app_dir.join("temp").join("webview"); let webview_dir = app_dir.join("temp").join("webview");
match std::fs::create_dir_all(&webview_dir) { match std::fs::create_dir_all(&webview_dir) {
+45 -10
View File
@@ -155,15 +155,40 @@ pub fn write_apply_script(app_dir: &Path) -> Result<PathBuf> {
Ok(bat_path) Ok(bat_path)
} }
#[derive(Debug, PartialEq, Eq)]
struct VersionParts {
nums: Vec<u32>,
pre: Option<String>,
}
fn parse_version(v: &str) -> VersionParts {
let trimmed = v.trim().trim_start_matches('v');
let (core, pre) = trimmed
.split_once('-')
.map(|(core, pre)| (core, Some(pre.to_ascii_lowercase())))
.unwrap_or((trimmed, None));
let nums = core
.split('.')
.map(|s| s.parse::<u32>().unwrap_or(0))
.collect();
VersionParts { nums, pre }
}
fn is_newer(latest: &str, current: &str) -> bool { fn is_newer(latest: &str, current: &str) -> bool {
// Note: pre-release suffixes (e.g., "-beta") are filtered out by parse().ok(), let mut l = parse_version(latest);
// so "1.0.0-beta" compares equal to "1.0.0". Acceptable for v1. let mut c = parse_version(current);
let mut l: Vec<u32> = latest.split('.').filter_map(|s| s.parse().ok()).collect(); let max = l.nums.len().max(c.nums.len());
let mut c: Vec<u32> = current.split('.').filter_map(|s| s.parse().ok()).collect(); l.nums.resize(max, 0);
let max = l.len().max(c.len()); c.nums.resize(max, 0);
l.resize(max, 0); if l.nums != c.nums {
c.resize(max, 0); return l.nums > c.nums;
l > c }
match (&l.pre, &c.pre) {
(None, Some(_)) => true,
(Some(_), None) => false,
(Some(a), Some(b)) => a > b,
(None, None) => false,
}
} }
#[cfg(test)] #[cfg(test)]
@@ -203,7 +228,17 @@ mod tests {
#[test] #[test]
fn version_ignores_extra_text() { fn version_ignores_extra_text() {
assert!(is_newer("1.0.0-beta", "0.9.0")); assert!(is_newer("1.0.0-beta", "0.9.0"));
// "beta" doesn't parse as u32, so it's filtered out. }
// 1.0.0 vs 0.9.0 -> newer
#[test]
fn stable_is_newer_than_matching_prerelease() {
assert!(is_newer("1.0.0", "1.0.0-beta"));
assert!(!is_newer("1.0.0-beta", "1.0.0"));
}
#[test]
fn prerelease_compares_when_core_matches() {
assert!(is_newer("1.0.0-rc", "1.0.0-beta"));
assert!(!is_newer("1.0.0-beta", "1.0.0-rc"));
} }
} }
+200
View File
@@ -0,0 +1,200 @@
<script lang="ts">
import GifControls from "./GifControls.svelte"
import type { Format, GifBudgetMode, GifDither } from "./api"
import { maxTargetMB, minTargetMB } from "./exportSizing"
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: { 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
} = $props()
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
})
</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>
</div>
<input
type="range"
class="styled-range"
min={minTargetMB(clip.duration_secs)}
max={maxTargetMB(clip.duration_secs)}
step="0.1"
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>
{#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>
{/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>
</div>
</div>
<div class="edit-actions">
<button class="btn-primary" onclick={onExport} disabled={cropInvalid}>Export</button>
<button class="btn-ghost" onclick={onDiscard}>Discard</button>
</div>
</div>
<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; }
</style>
+2
View File
@@ -107,6 +107,7 @@
.styled-range { .styled-range {
-webkit-appearance: none; -webkit-appearance: none;
appearance: none;
width: 100%; width: 100%;
height: 3px; height: 3px;
background: var(--bg-3); background: var(--bg-3);
@@ -116,6 +117,7 @@
} }
.styled-range::-webkit-slider-thumb { .styled-range::-webkit-slider-thumb {
-webkit-appearance: none; -webkit-appearance: none;
appearance: none;
width: 14px; height: 14px; width: 14px; height: 14px;
border-radius: 50%; border-radius: 50%;
background: var(--accent); background: var(--accent);
+45 -259
View File
@@ -4,9 +4,11 @@
import { save } from "@tauri-apps/plugin-dialog" import { save } from "@tauri-apps/plugin-dialog"
import { emit, listen } from "@tauri-apps/api/event" import { emit, listen } from "@tauri-apps/api/event"
import TrimPanel from "./TrimPanel.svelte" import TrimPanel from "./TrimPanel.svelte"
import GifControls from "./GifControls.svelte"
import Preview from "./Preview.svelte" import Preview from "./Preview.svelte"
import FramesStrip from "./FramesStrip.svelte" import FramesStrip from "./FramesStrip.svelte"
import ExportSidebar from "./ExportSidebar.svelte"
import { resetTrimPreview } from "./trimPreviewState.svelte"
import { minTargetMB } from "./exportSizing"
type Phase = "idle" | "recording" | "paused" | "editing" | "exporting" | "done" type Phase = "idle" | "recording" | "paused" | "editing" | "exporting" | "done"
@@ -209,7 +211,7 @@
cropH = c.height cropH = c.height
pathOverridden = false pathOverridden = false
outputPath = await api.defaultOutputPath(format) outputPath = await api.defaultOutputPath(format)
const sensible = Math.min(50, Math.max(minMB(c.duration_secs), Math.round(c.duration_secs * 0.5))) const sensible = Math.min(50, Math.max(minTargetMB(c.duration_secs), Math.round(c.duration_secs * 0.5)))
targetMB = sensible targetMB = sensible
} catch (e) { errMsg = String(e); phase = "idle"; clearTick() } } catch (e) { errMsg = String(e); phase = "idle"; clearTick() }
} }
@@ -314,7 +316,7 @@
clip = null; exportResult = null; errMsg = null; encodeProgress = null clip = null; exportResult = null; errMsg = null; encodeProgress = null
thumbnails = []; deletedFrames = new Set() thumbnails = []; deletedFrames = new Set()
thumbCache = new Map() thumbCache = new Map()
previewPath = null; trimPreviewPath = null previewPath = null; resetTrimPreview()
if (previewTimer !== null) { clearTimeout(previewTimer); previewTimer = null } if (previewTimer !== null) { clearTimeout(previewTimer); previewTimer = null }
elapsed = 0; phase = "idle" elapsed = 0; phase = "idle"
if (config) { if (config) {
@@ -347,25 +349,6 @@
function tick() { elapsedTimer = window.setInterval(() => { elapsed += 0.1 }, 100) } function tick() { elapsedTimer = window.setInterval(() => { elapsed += 0.1 }, 100) }
function clearTick() { if (elapsedTimer !== null) { clearInterval(elapsedTimer); elapsedTimer = null } } function clearTick() { if (elapsedTimer !== null) { clearInterval(elapsedTimer); elapsedTimer = null } }
// Minimum target file size (MB) for a clip of `s` seconds.
// Hard floor of 0.1 MB; otherwise scale ~50 KB/sec with a 50 KB absolute floor.
function minMB(s: number): number {
const perSecBytes = s * 50_000
const floorBytes = 50_000
return Math.max(0.1, Math.max(floorBytes, perSecBytes) / 1_048_576)
}
// Maximum target file size (MB) for a clip of `s` seconds.
// Capped at 200 MB; floor of 10 MB; otherwise scale 5 MB/sec.
function maxMB(s: number): number {
return Math.min(200, Math.max(10, s * 5))
}
// Trim state is lifted here so the Preview component can read it
// (to swap to the raw frame during drag) and the parent can debounce
// exports that depend on the values.
let dragging: 'start' | 'end' | null = $state(null)
let trimPreviewPath: string | null = $state(null)
let trimPreviewBust: number = $state(0)
// Reactivity // Reactivity
$effect(() => { $effect(() => {
@@ -563,9 +546,6 @@
{previewPath} {previewPath}
{previewLoading} {previewLoading}
{previewCacheBust} {previewCacheBust}
{trimPreviewPath}
{trimPreviewBust}
{dragging}
/> />
<!-- Trim timeline --> <!-- Trim timeline -->
@@ -573,9 +553,6 @@
{clip} {clip}
bind:trimStart bind:trimStart
bind:trimEnd bind:trimEnd
bind:dragging
bind:trimPreviewPath
bind:trimPreviewBust
onAfterChange={refreshPreview} onAfterChange={refreshPreview}
/> />
@@ -592,96 +569,29 @@
</div> </div>
<!-- Right: controls --> <!-- Right: controls -->
<div class="edit-right"> <ExportSidebar
<!-- Target size --> {clip}
<div class="control-group"> {format}
<div class="control-head"> bind:targetMB
<span class="section-title">Target size</span> bind:fps
<span class="mono size-readout">{targetMB.toFixed(1)} MB</span> bind:keepAudio
</div> bind:gifBudgetMode
<input bind:gifDither
type="range" bind:gifColors
class="styled-range" bind:cropEnabled
min={minMB(clip.duration_secs)} bind:cropX
max={maxMB(clip.duration_secs)} bind:cropY
step="0.1" bind:cropW
bind:value={targetMB} bind:cropH
onchange={refreshPreview} bind:outputPath
/> {previewDims}
<p class="estimate">{previewDims} &middot; {fps}fps &middot; {trimmedDuration.toFixed(1)}s</p> {trimmedDuration}
</div> onPreview={refreshPreview}
onPathInput={() => pathOverridden = true}
{#if format === "gif"} onBrowse={browseOutput}
<GifControls onExport={doExport}
bind:budgetMode={gifBudgetMode} onDiscard={confirmDiscard}
bind:dither={gifDither} />
bind:colors={gifColors}
onChange={refreshPreview}
/>
{/if}
<!-- FPS + Audio -->
<div class="control-row">
<label class="control">
<span class="control-label">FPS</span>
<select bind:value={fps} onchange={refreshPreview}>
{#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>
<!-- Crop -->
<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>
{#if cropEnabled}
<div class="crop-grid">
<label class="crop-field">
<span>X</span>
<input type="number" min="0" max={clip?.width ?? 9999} bind:value={cropX} />
</label>
<label class="crop-field">
<span>Y</span>
<input type="number" min="0" max={clip?.height ?? 9999} bind:value={cropY} />
</label>
<label class="crop-field">
<span>W</span>
<input type="number" min="1" max={clip?.width ?? 9999} bind:value={cropW} />
</label>
<label class="crop-field">
<span>H</span>
<input type="number" min="1" max={clip?.height ?? 9999} bind:value={cropH} />
</label>
</div>
{/if}
</div>
<!-- Output path -->
<div class="control-group">
<span class="section-title">Output</span>
<div class="path-row">
<input type="text" class="path-input" bind:value={outputPath} oninput={() => pathOverridden = true} aria-label="output file path" />
<button class="btn-ghost" onclick={browseOutput}>Browse</button>
</div>
</div>
<!-- Actions -->
<div class="edit-actions">
<button class="btn-primary" onclick={doExport}>Export</button>
<button class="btn-ghost" onclick={confirmDiscard}>Discard</button>
</div>
</div>
</div> </div>
<!-- EXPORTING --> <!-- EXPORTING -->
@@ -693,11 +603,18 @@
<span class="mono">{encodeProgress.pct.toFixed(0)}%</span> <span class="mono">{encodeProgress.pct.toFixed(0)}%</span>
</div> </div>
<div class="enc-track"> <div class="enc-track">
<div class="enc-fill" style="width:{encodeProgress.pct}%"></div> {#each Array(encodeProgress.total) as _, i}
<div class="enc-segment">
<div
class="enc-fill"
style="width:{i + 1 < encodeProgress.pass ? 100 : i + 1 === encodeProgress.pass ? encodeProgress.pct : 0}%"
></div>
</div>
{/each}
</div> </div>
{:else} {:else}
<div class="enc-meta"><span>Preparing</span></div> <div class="enc-meta"><span>Preparing</span></div>
<div class="enc-track"><div class="enc-fill" style="width:0%"></div></div> <div class="enc-track"><div class="enc-segment"><div class="enc-fill" style="width:0%"></div></div></div>
{/if} {/if}
<p class="enc-hint">ffmpeg is encoding your clip</p> <p class="enc-hint">ffmpeg is encoding your clip</p>
<button class="btn-ghost" onclick={cancelExport}>Cancel</button> <button class="btn-ghost" onclick={cancelExport}>Cancel</button>
@@ -1066,7 +983,7 @@
background: var(--border); background: var(--border);
min-height: 0; min-height: 0;
} }
.edit-left, .edit-right { .edit-left {
background: var(--bg); background: var(--bg);
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -1075,11 +992,9 @@
min-height: 0; min-height: 0;
} }
.edit-left { padding: 20px; gap: 20px; } .edit-left { padding: 20px; gap: 20px; }
.edit-right { padding: 20px; gap: 20px; border-left: 1px solid var(--border); }
@media (max-width: 720px) { @media (max-width: 720px) {
.edit { grid-template-columns: 1fr; } .edit { grid-template-columns: 1fr; }
.edit-right { border-left: none; border-top: 1px solid var(--border); }
} }
/* Format bar */ /* Format bar */
@@ -1108,135 +1023,6 @@
.fmt-chip:hover { color: var(--text-2); } .fmt-chip:hover { color: var(--text-2); }
.fmt-chip.active { background: var(--accent); border-color: var(--accent); color: var(--accent-text); } .fmt-chip.active { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
/* Preview (Trim, Frames, GifControls own their styles in their components) */
.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;
width: 100%;
height: 3px;
background: var(--bg-3);
border-radius: 2px;
outline: none;
cursor: pointer;
}
.styled-range::-webkit-slider-thumb {
-webkit-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 */
.crop-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
}
.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 */
.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 { .btn-primary {
padding: 10px 24px; padding: 10px 24px;
background: var(--accent); background: var(--accent);
@@ -1266,13 +1052,6 @@
} }
.btn-ghost:hover { border-color: var(--border-3); color: var(--text); } .btn-ghost:hover { border-color: var(--border-3); color: var(--text); }
.edit-actions {
display: flex;
gap: 10px;
margin-top: auto;
padding-top: 8px;
}
/* ---- Exporting ---- */ /* ---- Exporting ---- */
.exporting { .exporting {
flex: 1; flex: 1;
@@ -1299,7 +1078,10 @@
background: var(--bg-3); background: var(--bg-3);
border-radius: 2px; border-radius: 2px;
overflow: hidden; overflow: hidden;
display: flex;
gap: 2px;
} }
.enc-segment { flex: 1; background: var(--bg-3); overflow: hidden; }
.enc-fill { .enc-fill {
height: 100%; height: 100%;
background: var(--accent); background: var(--accent);
@@ -1398,6 +1180,7 @@
background: rgba(0,0,0,0.5); background: rgba(0,0,0,0.5);
display: grid; place-items: center; display: grid; place-items: center;
z-index: 50; z-index: 50;
animation: fadein 120ms ease-out;
} }
.confirm-card { .confirm-card {
background: var(--bg-2); background: var(--bg-2);
@@ -1406,7 +1189,10 @@
padding: 24px; padding: 24px;
min-width: 280px; min-width: 280px;
text-align: center; text-align: center;
animation: cardin 140ms ease-out;
} }
@keyframes fadein { from { opacity: 0; } to { opacity: 1; } }
@keyframes cardin { from { opacity: 0; transform: translateY(6px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
.confirm-card p { margin: 0 0 16px; font-size: 14px; color: var(--text); } .confirm-card p { margin: 0 0 16px; font-size: 14px; color: var(--text); }
.confirm-actions { display: flex; gap: 10px; justify-content: center; } .confirm-actions { display: flex; gap: 10px; justify-content: center; }
</style> </style>
+3 -8
View File
@@ -1,26 +1,21 @@
<script lang="ts"> <script lang="ts">
import { convertFileSrc } from "./api" import { convertFileSrc } from "./api"
import { trimPreviewState } from "./trimPreviewState.svelte"
let { let {
previewPath, previewPath,
previewLoading, previewLoading,
previewCacheBust, previewCacheBust,
trimPreviewPath,
trimPreviewBust,
dragging,
}: { }: {
previewPath: string | null previewPath: string | null
previewLoading: boolean previewLoading: boolean
previewCacheBust: number previewCacheBust: number
trimPreviewPath: string | null
trimPreviewBust: number
dragging: "start" | "end" | null
} = $props() } = $props()
</script> </script>
{#if dragging && trimPreviewPath} {#if trimPreviewState.dragging && trimPreviewState.path}
<div class="preview-box"> <div class="preview-box">
<img src={convertFileSrc(trimPreviewPath) + "?t=" + trimPreviewBust} alt="preview frame" class="preview-img"/> <img src={convertFileSrc(trimPreviewState.path) + "?t=" + trimPreviewState.bust} alt="preview frame" class="preview-img"/>
<div class="preview-loading">original</div> <div class="preview-loading">original</div>
</div> </div>
{:else if previewPath} {:else if previewPath}
+8 -13
View File
@@ -1,21 +1,16 @@
<script lang="ts"> <script lang="ts">
import { api } from "./api" import { api } from "./api"
import { trimPreviewState } from "./trimPreviewState.svelte"
let { let {
clip, clip,
trimStart = $bindable(), trimStart = $bindable(),
trimEnd = $bindable(), trimEnd = $bindable(),
trimPreviewPath = $bindable(),
trimPreviewBust = $bindable(),
dragging = $bindable(),
onAfterChange, onAfterChange,
}: { }: {
clip: { temp_path: string; duration_secs: number; width: number; height: number } clip: { temp_path: string; duration_secs: number; width: number; height: number }
trimStart: number trimStart: number
trimEnd: number trimEnd: number
trimPreviewPath: string | null
trimPreviewBust: number
dragging: "start" | "end" | null
onAfterChange: () => void onAfterChange: () => void
} = $props() } = $props()
@@ -35,24 +30,24 @@
if (now - lastTrimPreview < 100) return if (now - lastTrimPreview < 100) return
lastTrimPreview = now lastTrimPreview = now
try { try {
trimPreviewPath = await api.renderRawPreview(secs) trimPreviewState.path = await api.renderRawPreview(secs)
trimPreviewBust = Date.now() trimPreviewState.bust = Date.now()
} catch { } catch {
lastTrimPreview = 0 lastTrimPreview = 0
} }
} }
function startDrag(which: "start" | "end", e: PointerEvent) { function startDrag(which: "start" | "end", e: PointerEvent) {
dragging = which trimPreviewState.dragging = which
const el = e.currentTarget as HTMLElement const el = e.currentTarget as HTMLElement
el.setPointerCapture(e.pointerId) el.setPointerCapture(e.pointerId)
void updateTrimPreview(which === "start" ? trimStart : trimEnd) void updateTrimPreview(which === "start" ? trimStart : trimEnd)
} }
function onDrag(e: PointerEvent) { function onDrag(e: PointerEvent) {
if (!dragging) return if (!trimPreviewState.dragging) return
const secs = pointerToSecs(e) const secs = pointerToSecs(e)
if (dragging === "start") { if (trimPreviewState.dragging === "start") {
trimStart = Math.min(secs, trimEnd - 0.1) trimStart = Math.min(secs, trimEnd - 0.1)
} else { } else {
trimEnd = Math.max(secs, trimStart + 0.1) trimEnd = Math.max(secs, trimStart + 0.1)
@@ -63,8 +58,8 @@
function endDrag(e: PointerEvent) { function endDrag(e: PointerEvent) {
const el = e.currentTarget as HTMLElement const el = e.currentTarget as HTMLElement
el.releasePointerCapture(e.pointerId) el.releasePointerCapture(e.pointerId)
dragging = null trimPreviewState.dragging = null
trimPreviewPath = null trimPreviewState.path = null
onAfterChange() onAfterChange()
} }
+9
View File
@@ -0,0 +1,9 @@
export function minTargetMB(seconds: number): number {
const perSecBytes = seconds * 50_000
const floorBytes = 50_000
return Math.max(0.1, Math.max(floorBytes, perSecBytes) / 1_048_576)
}
export function maxTargetMB(seconds: number): number {
return Math.min(200, Math.max(10, seconds * 5))
}
+15
View File
@@ -0,0 +1,15 @@
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
}