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 {
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")?;
result
@@ -198,74 +209,7 @@ fn capture_loop(
};
while packet_length > 0 {
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")?;
}
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")?;
}
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 {
@@ -279,3 +223,113 @@ fn capture_loop(
}
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::io::{self, Cursor};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, Context, Result};
@@ -118,21 +118,39 @@ where
None
};
let archive = if let Some(ref hash) = expected {
download_verified(&client, &asset.browser_download_url, hash, on_progress)
.await
.with_context(|| format!("downloading {}", asset.browser_download_url))?
let app_dir = dest
.parent()
.and_then(|p| p.parent())
.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 {
download_plain(&client, &asset.browser_download_url, on_progress)
download_plain(&client, &asset.browser_download_url, &archive_path, on_progress)
.await
.with_context(|| format!("downloading {}", asset.browser_download_url))?
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
};
match source.kind {
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive, dest)?,
ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive, dest)?,
}
Ok(())
let result = match source.kind {
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest),
ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest),
};
let _ = fs::remove_file(&archive_path);
result
}
/// 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>(
client: &reqwest::Client,
url: &str,
dest: &Path,
mut on_progress: F,
) -> Result<Vec<u8>>
) -> Result<()>
where
F: FnMut(u64, Option<u64>),
{
let resp = client.get(url).send().await?.error_for_status()?;
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 stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
buf.extend_from_slice(&chunk);
file.write_all(&chunk)?;
downloaded += chunk.len() as u64;
on_progress(downloaded, total);
}
Ok(buf)
file.flush()?;
Ok(())
}
async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(GithubAsset, String)> {
@@ -224,33 +244,36 @@ async fn download_verified<F>(
client: &reqwest::Client,
url: &str,
expected: &[u8; 32],
dest: &Path,
on_progress: &mut F,
) -> Result<Vec<u8>>
) -> Result<()>
where
F: FnMut(u64, Option<u64>),
{
let resp = client.get(url).send().await?.error_for_status()?;
let total = resp.content_length();
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 stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
hasher.update(&chunk);
buf.extend_from_slice(&chunk);
file.write_all(&chunk)?;
downloaded += chunk.len() as u64;
on_progress(downloaded, total);
}
file.flush()?;
let got: [u8; 32] = hasher.finalize().into();
if &got != expected {
let _ = std::fs::remove_file(dest);
bail!(
"sha256 mismatch: expected {} got {}",
hex::encode(expected),
hex::encode(got)
);
}
Ok(buf)
Ok(())
}
fn is_ffmpeg_entry(name: &str) -> bool {
@@ -265,7 +288,7 @@ fn is_ffmpeg_entry(name: &str) -> bool {
.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
.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);
fs::create_dir_all(&scratch).context("create 7z scratch dir")?;
let reader = Cursor::new(archive);
let extract_result = sevenz_rust2::decompress_with_extract_fn(reader, &scratch, |_, _, _| Ok(true))
.map_err(|e| anyhow!("7z extraction failed: {e}"));
let file = std::fs::File::open(archive_path).context("opening 7z archive")?;
let extract_result =
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 _ = fs::remove_dir_all(&scratch);
@@ -305,9 +329,9 @@ fn find_ffmpeg_in(dir: &Path) -> Option<PathBuf> {
None
}
fn extract_ffmpeg_from_zip(archive: &[u8], dest: &Path) -> Result<()> {
let reader = Cursor::new(archive);
let mut zip = zip::ZipArchive::new(reader).context("open zip archive")?;
fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> {
let file = std::fs::File::open(archive_path).context("opening zip archive")?;
let mut zip = zip::ZipArchive::new(file).context("open zip archive")?;
for i in 0..zip.len() {
let mut entry = zip.by_index(i)?;
if entry.is_dir() {
+9
View File
@@ -329,6 +329,10 @@ impl CaptureSession {
/// Re-encode the intermediate file with correct timestamps.
/// The capture declares -framerate N and applies fps=M filter.
/// 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(
ffmpeg: &std::path::Path,
input: &std::path::Path,
@@ -339,6 +343,11 @@ pub fn fix_intermediate_fps(
) -> Result<()> {
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 {
tracing::warn!("capture fix: no frames counted, keeping original");
let _ = std::fs::rename(input, output);
+23 -2
View File
@@ -148,8 +148,29 @@ impl Config {
match toml::from_str::<Self>(&raw) {
Ok(cfg) => Ok(cfg),
Err(e) => {
let backup = path.with_extension("toml.bak");
tracing::warn!("config.toml is corrupt ({}), backing up to {:?} and using defaults", e, backup);
// Use a timestamped backup so successive corruptions don't
// 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 cfg = Self::default();
cfg.save(path)?;
+162 -58
View File
@@ -140,18 +140,14 @@ pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
match req.format {
Format::Mp4 => {
let codec = pick_video_codec(
&encoders,
&[mp4_video_codec(req.mp4_codec), "libx264"],
)?;
let requested = mp4_video_codec(req.mp4_codec);
let codec = require_video_codec(&encoders, requested, "MP4")?;
let audio = pick_audio_codec(&encoders, &["aac", "libfdk_aac"])?;
two_pass_video(ffmpeg, req, codec, audio, "mp4")
}
Format::Webm => {
let codec = pick_video_codec(
&encoders,
&[webm_video_codec(req.webm_codec), "libvpx-vp9", "libvpx"],
)?;
let requested = webm_video_codec(req.webm_codec);
let codec = require_video_codec(&encoders, requested, "WebM")?;
let audio = pick_audio_codec(&encoders, &["libopus", "libvorbis"])?;
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;
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())
}
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>(
encoders: &HashSet<String>,
candidates: &[&'a str],
@@ -298,7 +291,21 @@ fn two_pass_video(
let dur = req.duration_secs;
let fps = req.fps;
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.
if let Some(ref t) = tx {
@@ -328,7 +335,21 @@ fn two_pass_video(
pass2.arg("-an");
}
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);
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 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 {
if req.cancel.as_ref().map_or(false, |c| c.load(Ordering::Relaxed)) {
bail!("export cancelled");
}
// Last resort: use minimal settings to hit the target
if attempt == 5 {
if attempt == max_retries - 1 {
scale_width = (scale_width / 2).max(60);
effective_fps = 1;
}
let pass_start = std::time::Instant::now();
encode_gif_pass(ffmpeg, 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)
.map(|m| m.len())
@@ -397,29 +429,69 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
return Ok(());
}
// Only adjust DOWN when file is too big - never exceed target
// File is too big - scale down based on budget priority
// Compute a shrink factor. Clamp the multiplicative shrink between
// 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 {
GifBudgetMode::Resolution => {
// Reduce fps (resolution is priority, keep it)
effective_fps = ((effective_fps as f64 * ratio).round() as u32).max(1);
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
}
GifBudgetMode::Framerate => {
// Reduce resolution (fps is priority, keep it)
scale_width = ((scale_width as f64 * ratio.sqrt()).round() as u32 / 2).max(60).min(1280) * 2;
scale_width = ((scale_width as f64 * factor).round() as u32 / 2)
.max(60)
.min(1280)
* 2;
}
GifBudgetMode::Balanced => {
// Reduce both
let factor = ratio.sqrt();
scale_width = ((scale_width as f64 * factor).round() as u32 / 2).max(60).min(1280) * 2;
scale_width = ((scale_width as f64 * factor).round() as u32 / 2)
.max(60)
.min(1280)
* 2;
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1);
}
}
tracing::info!(
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps",
attempt + 1, actual, target, scale_width, effective_fps
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps (factor={:.2})",
attempt + 1,
actual,
target,
scale_width,
effective_fps,
factor
);
prev_actual = Some(actual);
}
// 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) {
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.
// 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.
@@ -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(
ffmpeg: &Path,
input: &Path,
@@ -709,7 +798,7 @@ pub fn mux_with_audio(
}
pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
use std::io::{Read, Write};
use std::io::Write;
if segments.is_empty() {
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")?;
for seg in segments {
let mut f = std::fs::File::open(seg).with_context(|| format!("opening {seg:?}"))?;
let mut buf = vec![0u8; 64 * 1024];
loop {
let n = f.read(&mut buf)?;
if n == 0 {
break;
}
out.write_all(&buf[..n])?;
}
std::io::copy(&mut f, &mut out).context("copying audio segment")?;
}
out.flush()?;
Ok(())
}
@@ -777,9 +860,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
fn run(cmd: &mut Command, label: &str) -> Result<()> {
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None)?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, head);
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
}
Ok(())
}
@@ -798,13 +879,36 @@ fn run_with_progress(
) -> Result<()> {
let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned(), cancel.cloned())?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, head);
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
}
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(
cmd: &mut Command,
label: &str,
@@ -914,11 +1018,11 @@ fn parse_frame_from_stderr(line: &str) -> Option<f64> {
mod tests {
use super::*;
// Paths are empty - these tests only exercise bitrate math, not ffmpeg.
fn dummy_request() -> TranscodeRequest {
let dir = std::env::temp_dir().join(format!("bytesize-encode-test-{}", std::process::id()));
TranscodeRequest {
input: PathBuf::new(),
output: PathBuf::new(),
input: dir.join("input.mp4"),
output: dir.join("output.mp4"),
format: Format::Mp4,
target_bytes: 0,
duration_secs: 10.0,
@@ -927,7 +1031,7 @@ mod tests {
gif_dither: GifDither::FloydSteinberg,
webm_codec: WebmCodec::Vp9,
mp4_codec: Mp4Codec::H264,
scratch_dir: PathBuf::new(),
scratch_dir: dir.join("scratch"),
crop: None,
gif_budget_mode: GifBudgetMode::Balanced,
gif_colors: 256,
+42 -11
View File
@@ -182,12 +182,49 @@ struct SaveConfigResult {
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]
fn save_config(
app: AppHandle,
state: State<'_, AppState>,
config: Config,
) -> Result<SaveConfigResult, String> {
validate_config(&config)?;
let path = config::config_path(&state.app_dir);
config.save(&path).map_err(|e| format!("{e:#}"))?;
*lock(&state.config) = config.clone();
@@ -794,16 +831,7 @@ fn estimate_gif_params(request: PreviewRequest) -> GifEstimate {
gif_budget_mode: request.gif_budget_mode,
};
let (w, fps) = encode::gif_params(&budget, request.clip_width, request.clip_height);
let aspect = if request.clip_height > 0 {
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 height = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
let dims_label = format!("{w}x{height} @ {fps}fps");
GifEstimate { width: w, fps, height, dims_label }
}
@@ -845,7 +873,7 @@ mod tests {
assert_eq!(est.fps, encode_fps);
// height should be a multiple of 2 and within aspect
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);
// dims_label should be "{w}x{h} @ {fps}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);
#[cfg(debug_assertions)]
let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout));
#[cfg(test)]
let _ = registry.try_init();
#[cfg(not(test))]
registry.init();
let webview_dir = app_dir.join("temp").join("webview");
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)
}
#[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 {
// Note: pre-release suffixes (e.g., "-beta") are filtered out by parse().ok(),
// so "1.0.0-beta" compares equal to "1.0.0". Acceptable for v1.
let mut l: Vec<u32> = latest.split('.').filter_map(|s| s.parse().ok()).collect();
let mut c: Vec<u32> = current.split('.').filter_map(|s| s.parse().ok()).collect();
let max = l.len().max(c.len());
l.resize(max, 0);
c.resize(max, 0);
l > c
let mut l = parse_version(latest);
let mut c = parse_version(current);
let max = l.nums.len().max(c.nums.len());
l.nums.resize(max, 0);
c.nums.resize(max, 0);
if l.nums != c.nums {
return l.nums > c.nums;
}
match (&l.pre, &c.pre) {
(None, Some(_)) => true,
(Some(_), None) => false,
(Some(a), Some(b)) => a > b,
(None, None) => false,
}
}
#[cfg(test)]
@@ -203,7 +228,17 @@ mod tests {
#[test]
fn version_ignores_extra_text() {
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"));
}
}