separate trim from review and save
This commit is contained in:
+215
-311
@@ -102,7 +102,6 @@ pub(crate) struct TranscodeRequest {
|
||||
pub crop: Option<CaptureRect>,
|
||||
pub gif_budget_mode: GifBudgetMode,
|
||||
pub gif_colors: u16,
|
||||
pub deleted_frame_indices: Vec<u32>,
|
||||
pub trim_start_secs: Option<f64>,
|
||||
pub trim_end_secs: Option<f64>,
|
||||
pub clicks: Vec<Click>,
|
||||
@@ -139,15 +138,11 @@ fn click_box(clip_x: i32, clip_y: i32, clip_w: u32, clip_h: u32) -> Option<(i32,
|
||||
Some((x, y))
|
||||
}
|
||||
|
||||
/// The time `apply_trim` cuts off the head of the clip. A seek rebases the
|
||||
/// filter graph's timestamps to zero, so anything recorded against clip time -
|
||||
/// the click highlights - has to be shifted by the same amount or it lands late
|
||||
/// by the length of the trim.
|
||||
fn trim_offset(req: &TranscodeRequest) -> f64 {
|
||||
req.trim_start_secs.filter(|s| *s > 0.001).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32, time_offset: f64) -> Option<String> {
|
||||
fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32) -> Option<String> {
|
||||
if clicks.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -169,10 +164,7 @@ fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32, time_offset: f64) -
|
||||
let Some((x, y)) = click_box(click.x, click.y, clip_w, clip_h) else {
|
||||
continue;
|
||||
};
|
||||
let t = click.time_secs - time_offset;
|
||||
if t + 0.25 < 0.0 {
|
||||
continue;
|
||||
}
|
||||
let t = click.time_secs;
|
||||
let t1 = (t - 0.05).max(0.0);
|
||||
let t2 = t + 0.25;
|
||||
let color = match click.button {
|
||||
@@ -202,19 +194,26 @@ fn apply_trim(cmd: &mut Command, req: &TranscodeRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
fn select_filter_for_deleted(deleted: &[u32]) -> Option<String> {
|
||||
if deleted.is_empty() {
|
||||
return None;
|
||||
fn gif_timeline_filter(req: &TranscodeRequest, effective_fps: u32) -> String {
|
||||
let mut trim = Vec::new();
|
||||
if let Some(start) = req.trim_start_secs {
|
||||
trim.push(format!("start={start}"));
|
||||
}
|
||||
if let Some(end) = req.trim_end_secs {
|
||||
trim.push(format!("end={end}"));
|
||||
}
|
||||
let fps = format!("fps={effective_fps}");
|
||||
if trim.is_empty() {
|
||||
fps
|
||||
} else {
|
||||
format!("trim={},setpts=PTS-STARTPTS,{fps}", trim.join(":"))
|
||||
}
|
||||
let parts: Vec<String> = deleted.iter().map(|n| format!("eq(n\\,{n})")).collect();
|
||||
let expr = parts.join("+");
|
||||
Some(format!("select='not({expr})',setpts=N/FRAME_RATE/TB"))
|
||||
}
|
||||
|
||||
fn crop_filter(crop: Option<CaptureRect>) -> Option<String> {
|
||||
crop.map(|c| {
|
||||
format!(
|
||||
"crop={w}:{h}:{x}:{y}",
|
||||
"crop={w}:{h}:{x}:{y}:exact=1",
|
||||
w = c.width,
|
||||
h = c.height,
|
||||
x = c.x.max(0),
|
||||
@@ -227,6 +226,9 @@ pub(crate) fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
if req.duration_secs <= 0.01 {
|
||||
bail!("clip duration is essentially zero - nothing to encode");
|
||||
}
|
||||
if req.fps == 0 {
|
||||
bail!("export frame rate must be greater than zero");
|
||||
}
|
||||
std::fs::create_dir_all(&req.scratch_dir).context("creating scratch dir")?;
|
||||
if let Some(parent) = req.output.parent() {
|
||||
std::fs::create_dir_all(parent).context("creating output dir")?;
|
||||
@@ -407,15 +409,14 @@ fn video_bitrate_kbps(req: &TranscodeRequest) -> Result<u64> {
|
||||
Ok(kbps.max(16))
|
||||
}
|
||||
|
||||
/// Chain the crop and the click highlights into the single `-vf` argument the
|
||||
/// two video passes share.
|
||||
fn combined_video_filter(crop: Option<&String>, clicks: Option<&String>) -> Option<String> {
|
||||
match (crop, clicks) {
|
||||
(Some(c), Some(k)) => Some(format!("{c},{k}")),
|
||||
(Some(c), None) => Some(c.clone()),
|
||||
(None, Some(k)) => Some(k.clone()),
|
||||
(None, None) => None,
|
||||
}
|
||||
fn video_filters(req: &TranscodeRequest) -> String {
|
||||
let crop = crop_filter(req.crop);
|
||||
let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height);
|
||||
[clicks, crop, Some(format!("fps={}", req.fps))]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
|
||||
fn two_pass_video(
|
||||
@@ -423,7 +424,7 @@ fn two_pass_video(
|
||||
req: &TranscodeRequest,
|
||||
video_codec: &str,
|
||||
audio_codec: &str,
|
||||
_container: &str,
|
||||
container: &str,
|
||||
) -> Result<()> {
|
||||
let bitrate_kbps = video_bitrate_kbps(req)?;
|
||||
let bitrate = format!("{bitrate_kbps}k");
|
||||
@@ -434,14 +435,7 @@ fn two_pass_video(
|
||||
.ok_or_else(|| anyhow!("scratch dir contains non-UTF8"))?;
|
||||
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
|
||||
|
||||
let crop = crop_filter(req.crop);
|
||||
let clicks = click_filters(
|
||||
&req.clicks,
|
||||
req.clip_width,
|
||||
req.clip_height,
|
||||
trim_offset(req),
|
||||
);
|
||||
let combined_vf = combined_video_filter(crop.as_ref(), clicks.as_ref());
|
||||
let combined_vf = video_filters(req);
|
||||
|
||||
let mut pass1 = Command::new(ffmpeg);
|
||||
pass1
|
||||
@@ -450,10 +444,8 @@ fn two_pass_video(
|
||||
.arg("-i")
|
||||
.arg(&req.input);
|
||||
apply_trim(&mut pass1, req);
|
||||
if let Some(c) = &combined_vf {
|
||||
pass1.args(["-vf", c]);
|
||||
}
|
||||
pass1
|
||||
.args(["-vf", &combined_vf])
|
||||
.args(["-c:v", video_codec])
|
||||
.args(["-b:v", &bitrate])
|
||||
.args(["-pass", "1"])
|
||||
@@ -464,7 +456,6 @@ fn two_pass_video(
|
||||
|
||||
let tx = req.progress_tx.clone();
|
||||
let dur = req.duration_secs;
|
||||
let fps = req.fps;
|
||||
let cancel = req.cancel.clone();
|
||||
let pass_start = std::time::Instant::now();
|
||||
run_with_progress(
|
||||
@@ -473,7 +464,6 @@ fn two_pass_video(
|
||||
1,
|
||||
2,
|
||||
dur,
|
||||
fps,
|
||||
tx.as_ref(),
|
||||
cancel.as_ref(),
|
||||
)?;
|
||||
@@ -501,10 +491,8 @@ fn two_pass_video(
|
||||
.arg("-i")
|
||||
.arg(&req.input);
|
||||
apply_trim(&mut pass2, req);
|
||||
if let Some(c) = &combined_vf {
|
||||
pass2.args(["-vf", c]);
|
||||
}
|
||||
pass2
|
||||
.args(["-vf", &combined_vf])
|
||||
.args(["-c:v", video_codec])
|
||||
.args(["-b:v", &bitrate])
|
||||
.args(["-pass", "2"])
|
||||
@@ -516,7 +504,7 @@ fn two_pass_video(
|
||||
} else {
|
||||
pass2.arg("-an");
|
||||
}
|
||||
pass2.arg(&req.output);
|
||||
pass2.args(["-abort_on", "empty_output_stream", "-f", container]).arg(&req.output);
|
||||
let pass_start = std::time::Instant::now();
|
||||
run_with_progress(
|
||||
&mut pass2,
|
||||
@@ -524,7 +512,6 @@ fn two_pass_video(
|
||||
2,
|
||||
2,
|
||||
dur,
|
||||
fps,
|
||||
tx.as_ref(),
|
||||
cancel.as_ref(),
|
||||
)?;
|
||||
@@ -567,7 +554,7 @@ fn calibrate_via_sample(
|
||||
) -> Option<(u32, u32)> {
|
||||
let sample_path = req.scratch_dir.join("gif-calib-sample.gif");
|
||||
let sample_dur = 2.0_f64.min(req.duration_secs);
|
||||
let sample_start = (req.duration_secs / 2.0 - sample_dur / 2.0).max(0.0);
|
||||
let sample_start = trim_offset(req) + ((req.duration_secs - sample_dur) / 2.0).max(0.0);
|
||||
|
||||
// Defer cleanup until we've measured the sample: the guard owns a copy of
|
||||
// the path, which lets the original move into the request below. Earlier
|
||||
@@ -582,7 +569,6 @@ fn calibrate_via_sample(
|
||||
sample_req.output = sample_path;
|
||||
sample_req.trim_start_secs = Some(sample_start);
|
||||
sample_req.trim_end_secs = Some(sample_start + sample_dur);
|
||||
sample_req.deleted_frame_indices.clear();
|
||||
sample_req.clicks.clear();
|
||||
sample_req.progress_tx = None;
|
||||
|
||||
@@ -598,7 +584,8 @@ fn calibrate_via_sample(
|
||||
// Back-compute the effective bytes/pixel from the sample. LZW on a short
|
||||
// clip overstates per-frame cost slightly (less inter-frame reuse) so we
|
||||
// apply a small correction factor toward the conservative side.
|
||||
let aspect = aspect_ratio(req.clip_width, req.clip_height);
|
||||
let (clip_width, clip_height) = req.crop.map_or((req.clip_width, req.clip_height), |r| (r.width, r.height));
|
||||
let aspect = aspect_ratio(clip_width, clip_height);
|
||||
let sample_h = round_u32(f64::from(est_width) / aspect);
|
||||
let frames = (f64::from(est_fps) * sample_dur).max(1.0);
|
||||
let measured_bpp =
|
||||
@@ -611,17 +598,20 @@ fn calibrate_via_sample(
|
||||
let ratio = assumed_bpp / blended_bpp;
|
||||
// Only recalibrate if the gap is meaningful (>15%). Small gaps aren't
|
||||
// worth the risk of overshooting on a noisy 2s sample.
|
||||
if (ratio - 1.0).abs() < 0.15 {
|
||||
if ratio >= 0.85 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Recompute target params with the corrected constant. Scale resolution
|
||||
// by the sqrt of the ratio so file size scales roughly linearly.
|
||||
let new_width = (round_u32(f64::from(est_width) * ratio.sqrt()) / 2).max(60) * 2;
|
||||
let new_fps = round_u32(f64::from(est_fps) * ratio.sqrt())
|
||||
.max(1)
|
||||
.min(est_fps);
|
||||
Some((new_width.min(1280), new_fps))
|
||||
let (mut width, mut fps) = (est_width, est_fps);
|
||||
shrink_gif_params(
|
||||
req.gif_budget_mode,
|
||||
gif_shrink_factor(req.gif_budget_mode, ratio.min(1.0)),
|
||||
&mut width,
|
||||
&mut fps,
|
||||
);
|
||||
Some((width, fps))
|
||||
}
|
||||
|
||||
/// Per-mode raw shrink factor (before clamping to 0.6..0.9) given the
|
||||
@@ -630,8 +620,8 @@ fn calibrate_via_sample(
|
||||
/// match the dimension it is applied to.
|
||||
fn gif_shrink_factor(mode: GifBudgetMode, ratio: f64) -> f64 {
|
||||
match mode {
|
||||
GifBudgetMode::Resolution => ratio.sqrt(),
|
||||
GifBudgetMode::Framerate => ratio,
|
||||
GifBudgetMode::Resolution => ratio,
|
||||
GifBudgetMode::Framerate => ratio.sqrt(),
|
||||
GifBudgetMode::Balanced => {
|
||||
// Split the required reduction between resolution and fps so we
|
||||
// reduce both proportionally rather than halving resolution alone.
|
||||
@@ -644,15 +634,17 @@ fn gif_shrink_factor(mode: GifBudgetMode, ratio: f64) -> f64 {
|
||||
/// keeping the width even (the `*2` after the halving clamp).
|
||||
fn shrink_gif_params(mode: GifBudgetMode, factor: f64, width: &mut u32, fps: &mut u32) {
|
||||
match mode {
|
||||
GifBudgetMode::Resolution => {
|
||||
GifBudgetMode::Framerate => {
|
||||
*width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2;
|
||||
}
|
||||
GifBudgetMode::Framerate => {
|
||||
*fps = round_u32(f64::from(*fps) * factor).max(1);
|
||||
GifBudgetMode::Resolution => {
|
||||
*fps = round_u32(f64::from(*fps) * factor)
|
||||
.clamp(1, fps.saturating_sub(1).max(1));
|
||||
}
|
||||
GifBudgetMode::Balanced => {
|
||||
*width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2;
|
||||
*fps = round_u32(f64::from(*fps) * factor).max(1);
|
||||
*fps = round_u32(f64::from(*fps) * factor)
|
||||
.clamp(1, fps.saturating_sub(1).max(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -676,7 +668,7 @@ fn gif_calibration(
|
||||
Some((w, f))
|
||||
}
|
||||
|
||||
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
fn gif_starting_params(req: &TranscodeRequest) -> (u32, u32) {
|
||||
let budget_input = GifBudgetInput {
|
||||
gif_colors: req.gif_colors,
|
||||
target_bytes: req.target_bytes,
|
||||
@@ -684,8 +676,12 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
duration_secs: req.duration_secs,
|
||||
gif_budget_mode: req.gif_budget_mode,
|
||||
};
|
||||
let (mut scale_width, mut effective_fps) =
|
||||
gif_params(&budget_input, req.clip_width, req.clip_height);
|
||||
let (width, height) = req.crop.map_or((req.clip_width, req.clip_height), |r| (r.width, r.height));
|
||||
gif_params(&budget_input, width, height)
|
||||
}
|
||||
|
||||
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
let (mut scale_width, mut effective_fps) = gif_starting_params(req);
|
||||
|
||||
// Calibrate the bytes/pixel constant by encoding a short sample first.
|
||||
// The default 0.2 bytes/pixel assumption varies 3-5x by content; measuring
|
||||
@@ -715,11 +711,6 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
{
|
||||
bail!("export cancelled");
|
||||
}
|
||||
// Last resort: use minimal settings to hit the target
|
||||
if attempt == max_retries - 1 {
|
||||
scale_width = (scale_width / 2).max(60);
|
||||
effective_fps = 1;
|
||||
}
|
||||
let pass_start = std::time::Instant::now();
|
||||
encode_gif_pass(
|
||||
ffmpeg,
|
||||
@@ -781,12 +772,25 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
let previous = (scale_width, effective_fps);
|
||||
shrink_gif_params(
|
||||
req.gif_budget_mode,
|
||||
factor,
|
||||
&mut scale_width,
|
||||
&mut effective_fps,
|
||||
);
|
||||
if (scale_width, effective_fps) == previous {
|
||||
// Try the other setting when the preferred one hits its floor.
|
||||
let fallback = match req.gif_budget_mode {
|
||||
GifBudgetMode::Resolution => GifBudgetMode::Framerate,
|
||||
GifBudgetMode::Framerate | GifBudgetMode::Balanced => GifBudgetMode::Resolution,
|
||||
};
|
||||
shrink_gif_params(fallback, gif_shrink_factor(fallback, ratio).clamp(0.6, 0.9),
|
||||
&mut scale_width, &mut effective_fps);
|
||||
if (scale_width, effective_fps) == previous {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps (factor={:.2})",
|
||||
@@ -811,28 +815,15 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn encode_gif_pass(
|
||||
ffmpeg: &Path,
|
||||
req: &TranscodeRequest,
|
||||
scale_width: u32,
|
||||
effective_fps: u32,
|
||||
attempt: u8,
|
||||
max_attempts: u8,
|
||||
) -> Result<()> {
|
||||
fn gif_filters(req: &TranscodeRequest, scale_width: u32, effective_fps: u32) -> String {
|
||||
let crop_prefix = crop_filter(req.crop)
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let click_prefix = click_filters(
|
||||
&req.clicks,
|
||||
req.clip_width,
|
||||
req.clip_height,
|
||||
trim_offset(req),
|
||||
)
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices)
|
||||
.map(|s| format!("{s},"))
|
||||
let click_prefix = click_filters(&req.clicks, req.clip_width, req.clip_height)
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let timeline = gif_timeline_filter(req, effective_fps);
|
||||
let stats = "diff";
|
||||
|
||||
let dither = match req.gif_dither {
|
||||
GifDither::FloydSteinberg => "floyd_steinberg",
|
||||
@@ -843,16 +834,26 @@ fn encode_gif_pass(
|
||||
// Single-pass approach: split the stream, generate palette from one copy,
|
||||
// apply palette to the other. The fps filter handles frame rate conversion.
|
||||
let scale = gif_rgb_scale_filter(scale_width);
|
||||
let filter_complex = format!(
|
||||
"{cprefix}{kprefix}fps={fps},{sprefix}{scale},split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors={colors}[p];[s1][p]paletteuse=dither={d}",
|
||||
let colors = req.gif_colors;
|
||||
let reserve = u8::from(colors > 2);
|
||||
format!(
|
||||
"{kprefix}{cprefix}{timeline},{scale},split[s0][s1];[s0]palettegen=stats_mode={stats}:max_colors={colors}:reserve_transparent={reserve}[p];[s1][p]paletteuse=dither={d}",
|
||||
cprefix = crop_prefix,
|
||||
kprefix = click_prefix,
|
||||
sprefix = select_prefix,
|
||||
fps = effective_fps,
|
||||
scale = scale,
|
||||
colors = req.gif_colors,
|
||||
d = dither,
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
fn encode_gif_pass(
|
||||
ffmpeg: &Path,
|
||||
req: &TranscodeRequest,
|
||||
scale_width: u32,
|
||||
effective_fps: u32,
|
||||
attempt: u8,
|
||||
max_attempts: u8,
|
||||
) -> Result<()> {
|
||||
let filter_complex = gif_filters(req, scale_width, effective_fps);
|
||||
|
||||
tracing::info!(
|
||||
"gif encode: fps={effective_fps} scale={scale_width} colors={} filter={filter_complex}",
|
||||
@@ -865,10 +866,10 @@ fn encode_gif_pass(
|
||||
.arg("-hide_banner")
|
||||
.arg("-i")
|
||||
.arg(&req.input);
|
||||
apply_trim(&mut encode, req);
|
||||
encode
|
||||
.args(["-filter_complex", &filter_complex])
|
||||
.args(["-loop", "0"])
|
||||
.args(["-abort_on", "empty_output", "-f", "gif"])
|
||||
.arg(&req.output);
|
||||
run_with_progress(
|
||||
&mut encode,
|
||||
@@ -876,7 +877,6 @@ fn encode_gif_pass(
|
||||
attempt,
|
||||
max_attempts,
|
||||
req.duration_secs,
|
||||
effective_fps,
|
||||
req.progress_tx.as_ref(),
|
||||
req.cancel.as_ref(),
|
||||
)?;
|
||||
@@ -886,7 +886,7 @@ fn encode_gif_pass(
|
||||
|
||||
fn gif_rgb_scale_filter(width: u32) -> String {
|
||||
format!(
|
||||
"scale={width}:-1:flags=lanczos:in_color_matrix=bt709:in_range=tv:in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb:out_range=pc,format=rgb24"
|
||||
"scale={width}:-1:flags=lanczos:in_color_matrix=bt709:in_range=tv:out_range=pc:in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb,format=rgb24"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -970,181 +970,69 @@ pub(crate) fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn render_preview(
|
||||
ffmpeg: &Path,
|
||||
input: &Path,
|
||||
out_path: &Path,
|
||||
midpoint_secs: f64,
|
||||
target_width: u32,
|
||||
) -> Result<()> {
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent).context("creating preview parent")?;
|
||||
}
|
||||
let scale_filter = format!("scale={target_width}:-2");
|
||||
let mut cmd = Command::new(ffmpeg);
|
||||
cmd.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.args(["-ss", &format!("{midpoint_secs}")])
|
||||
.arg("-i")
|
||||
.arg(input)
|
||||
.args(["-vf", &scale_filter])
|
||||
.args(["-frames:v", "1"])
|
||||
.arg(out_path);
|
||||
run(&mut cmd, "preview render")
|
||||
#[derive(Clone, Copy, Debug, serde::Serialize)]
|
||||
pub(crate) struct OutputProperties {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: f64,
|
||||
pub duration_secs: f64,
|
||||
}
|
||||
|
||||
/// Render a GIF preview with actual palette and dithering applied.
|
||||
/// Generates a palette from the full clip, then applies it to a single frame.
|
||||
// Every argument is a distinct knob the caller already has in hand; bundling
|
||||
// them into a struct would only move the same list one level up.
|
||||
#[allow(
|
||||
clippy::too_many_arguments,
|
||||
reason = "flat parameter list mirrors the preview request fields the caller owns"
|
||||
)]
|
||||
pub(crate) fn render_gif_preview(
|
||||
ffmpeg: &Path,
|
||||
input: &Path,
|
||||
out_path: &Path,
|
||||
midpoint_secs: f64,
|
||||
target_width: u32,
|
||||
gif_colors: u16,
|
||||
gif_dither: &str,
|
||||
duration_secs: f64,
|
||||
) -> Result<()> {
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent).context("creating preview parent")?;
|
||||
}
|
||||
// The palette depends only on gif_colors and the sampled frame range, not
|
||||
// on target_bytes or dither. Cache it keyed on those inputs so slider
|
||||
// drags (which change target_bytes) skip the expensive palettegen pass.
|
||||
let sample_start = (midpoint_secs - 1.0).max(0.0);
|
||||
let sample_dur = duration_secs.min(2.0);
|
||||
let palette_key = palette_cache_key(gif_colors, target_width, sample_start, sample_dur);
|
||||
// The preview and its input both live in the scratch dir, so the preview's
|
||||
// parent is the normal case. Fall back to the input's parent rather than
|
||||
// panicking on a bare filename.
|
||||
let palette_dir = out_path
|
||||
.parent()
|
||||
.filter(|p| !p.as_os_str().is_empty())
|
||||
.or_else(|| input.parent().filter(|p| !p.as_os_str().is_empty()))
|
||||
.context("preview palette has no parent directory")?;
|
||||
let palette_path = palette_dir.join(format!("preview-palette-{palette_key}.png"));
|
||||
|
||||
let need_regen = !palette_path.is_file();
|
||||
if need_regen {
|
||||
// Drop any stale palettes from previous inputs so temp doesn't grow.
|
||||
clean_stale_palettes(palette_path.parent().unwrap_or(Path::new(".")));
|
||||
let palette_filter = format!(
|
||||
"{},palettegen=stats_mode=diff:max_colors={}",
|
||||
gif_rgb_scale_filter(target_width),
|
||||
gif_colors
|
||||
);
|
||||
let mut gen = Command::new(ffmpeg);
|
||||
gen.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.args(["-ss", &format!("{sample_start}")])
|
||||
.args(["-t", &format!("{sample_dur}")])
|
||||
.arg("-i")
|
||||
.arg(input)
|
||||
.args(["-vf", &palette_filter])
|
||||
.arg(&palette_path);
|
||||
run(&mut gen, "gif preview palette")?;
|
||||
}
|
||||
|
||||
// Apply palette to the target frame
|
||||
let use_filter = format!(
|
||||
"{}[x];[x][1:v]paletteuse=dither={}",
|
||||
gif_rgb_scale_filter(target_width),
|
||||
gif_dither
|
||||
);
|
||||
let mut encode = Command::new(ffmpeg);
|
||||
encode
|
||||
.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.args(["-ss", &format!("{midpoint_secs}")])
|
||||
.arg("-i")
|
||||
.arg(input)
|
||||
.arg("-i")
|
||||
.arg(&palette_path)
|
||||
.args(["-lavfi", &use_filter])
|
||||
.args(["-frames:v", "1"])
|
||||
.arg(out_path);
|
||||
// The palette is deliberately left in place: the cache key above exists so a
|
||||
// render with the same inputs can skip palettegen entirely, and deleting it
|
||||
// here meant every render regenerated it. clear_temp_segments sweeps
|
||||
// preview-palette-*.png between recordings, and clean_stale_palettes drops
|
||||
// the keys that no longer apply.
|
||||
run(&mut encode, "gif preview encode")
|
||||
}
|
||||
|
||||
/// Build a stable cache key for a GIF preview palette from the inputs that
|
||||
/// actually affect palettegen output. Same inputs -> same palette.
|
||||
fn palette_cache_key(
|
||||
gif_colors: u16,
|
||||
target_width: u32,
|
||||
sample_start: f64,
|
||||
sample_dur: f64,
|
||||
) -> String {
|
||||
format!("c{gif_colors}-w{target_width}-s{sample_start:.3}-d{sample_dur:.3}")
|
||||
}
|
||||
|
||||
/// Remove old `preview-palette-*.png` files so only the current key remains.
|
||||
fn clean_stale_palettes(dir: &Path) {
|
||||
if let Ok(entries) = std::fs::read_dir(dir) {
|
||||
for entry in entries.flatten() {
|
||||
if let Some(name) = entry.file_name().to_str() {
|
||||
// Case-insensitive for the same reason as the temp sweep: these
|
||||
// are the app's own files, but Windows keeps the case it was given.
|
||||
let is_png = Path::new(name)
|
||||
.extension()
|
||||
.is_some_and(|e| e.eq_ignore_ascii_case("png"));
|
||||
if name.starts_with("preview-palette-") && is_png {
|
||||
drop(std::fs::remove_file(entry.path()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn extract_thumbnails(
|
||||
ffmpeg: &Path,
|
||||
input: &Path,
|
||||
out_dir: &Path,
|
||||
fps: u32,
|
||||
crop: Option<CaptureRect>,
|
||||
) -> Result<Vec<PathBuf>> {
|
||||
std::fs::create_dir_all(out_dir).context("creating thumbnails dir")?;
|
||||
for entry in std::fs::read_dir(out_dir).into_iter().flatten().flatten() {
|
||||
drop(std::fs::remove_file(entry.path()));
|
||||
}
|
||||
|
||||
let crop_prefix = crop_filter(crop)
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let filter = format!("{crop_prefix}fps={fps},scale=120:-1:flags=lanczos");
|
||||
let pattern = out_dir.join("thumb-%05d.png");
|
||||
/// Inspect packet timing without decoding the video.
|
||||
pub(crate) fn inspect_output(ffmpeg: &Path, path: &Path) -> Result<OutputProperties> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
|
||||
|
||||
let mut cmd = Command::new(ffmpeg);
|
||||
cmd.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.arg("-i")
|
||||
.arg(input)
|
||||
.args(["-vf", &filter])
|
||||
.arg(&pattern);
|
||||
run(&mut cmd, "thumbnail extraction")?;
|
||||
let output = cmd
|
||||
.creation_flags(CREATE_NO_WINDOW.0)
|
||||
.args(["-v", "error", "-nostdin", "-i"])
|
||||
.arg(path)
|
||||
.args(["-map", "0:v:0", "-c:v", "copy", "-f", "framecrc", "pipe:1"])
|
||||
.output()
|
||||
.context("reading rendered output details")?;
|
||||
if !output.status.success() {
|
||||
bail!(ffmpeg_failure_message("reading output details", output.status, &output.stderr));
|
||||
}
|
||||
parse_output_properties(&String::from_utf8_lossy(&output.stdout))
|
||||
.ok_or_else(|| anyhow!("could not read the output dimensions or frame timing"))
|
||||
}
|
||||
|
||||
let mut paths: Vec<PathBuf> = std::fs::read_dir(out_dir)?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
p.extension().and_then(|s| s.to_str()) == Some("png")
|
||||
&& p.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.is_some_and(|s| s.starts_with("thumb-"))
|
||||
})
|
||||
.collect();
|
||||
paths.sort();
|
||||
Ok(paths)
|
||||
fn parse_output_properties(report: &str) -> Option<OutputProperties> {
|
||||
let (width, height) = report.lines()
|
||||
.find_map(|line| line.strip_prefix("#dimensions 0: "))?.trim().split_once('x')?;
|
||||
let (tick, timescale) = report.lines()
|
||||
.find_map(|line| line.strip_prefix("#tb 0: "))?.trim().split_once('/')?;
|
||||
let mut first = f64::INFINITY;
|
||||
let mut end = f64::NEG_INFINITY;
|
||||
let mut frames = 0u32;
|
||||
for line in report.lines().filter(|line| line.starts_with('0')) {
|
||||
let mut columns = line.split(',').skip(2);
|
||||
let pts = columns.next()?.trim().parse::<f64>().ok()?;
|
||||
let duration = columns.next()?.trim().parse::<f64>().ok()?;
|
||||
first = first.min(pts);
|
||||
end = end.max(pts + duration);
|
||||
frames += 1;
|
||||
}
|
||||
let duration_secs = (end - first) * tick.parse::<f64>().ok()? / timescale.parse::<f64>().ok()?;
|
||||
if !duration_secs.is_finite() || duration_secs <= 0.0 { return None; }
|
||||
Some(OutputProperties {
|
||||
width: width.parse().ok()?, height: height.parse().ok()?,
|
||||
fps: f64::from(frames) / duration_secs, duration_secs,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn timeline_thumbnails(ffmpeg: &Path, input: &Path, out_dir: &Path, seconds: f64) -> Result<Vec<PathBuf>> {
|
||||
if !seconds.is_finite() || seconds <= 0.0 {
|
||||
bail!("invalid clip duration for the timeline");
|
||||
}
|
||||
std::fs::create_dir_all(out_dir).context("creating timeline thumbnail folder")?;
|
||||
let filter = format!("fps={:.6},scale=160:-2", (8.0 / seconds).min(120.0));
|
||||
let mut cmd = Command::new(ffmpeg);
|
||||
cmd.args(["-y", "-hide_banner", "-i"]).arg(input)
|
||||
.args(["-vf", &filter, "-frames:v", "8"]).arg(out_dir.join("frame-%02d.jpg"));
|
||||
run(&mut cmd, "timeline thumbnails")?;
|
||||
Ok((1..=8).map(|i| out_dir.join(format!("frame-{i:02}.jpg"))).filter(|path| path.is_file()).collect())
|
||||
}
|
||||
|
||||
pub(crate) fn display_preview(ffmpeg: &Path, x: i32, y: i32, width: u32, height: u32) -> Result<Vec<u8>> {
|
||||
@@ -1351,7 +1239,7 @@ pub(crate) fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path
|
||||
}
|
||||
|
||||
fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
||||
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None, false)?;
|
||||
let output = run_impl(cmd, label, 0, 0, 0.0, None, None, false)?;
|
||||
if !output.status.success() {
|
||||
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
|
||||
}
|
||||
@@ -1362,19 +1250,12 @@ fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
||||
/// `progress_tx`, if provided, receives (pass, `total_passes`, percent) updates
|
||||
/// driven by ffmpeg's stable key=value output (`out_time_us`) rather than
|
||||
/// fragile stderr line parsing.
|
||||
// Thin forwarder to run_impl, which needs the same list; a params struct here
|
||||
// would just be reconstructed at each of the four call sites.
|
||||
#[allow(
|
||||
clippy::too_many_arguments,
|
||||
reason = "thin forwarder for the ffmpeg invocation; callers already hold these as locals"
|
||||
)]
|
||||
fn run_with_progress(
|
||||
cmd: &mut Command,
|
||||
label: &str,
|
||||
pass: u8,
|
||||
total_passes: u8,
|
||||
duration_secs: f64,
|
||||
fps: u32,
|
||||
progress_tx: Option<&Sender<EncodeProgress>>,
|
||||
cancel: Option<&Arc<AtomicBool>>,
|
||||
) -> Result<()> {
|
||||
@@ -1387,7 +1268,6 @@ fn run_with_progress(
|
||||
pass,
|
||||
total_passes,
|
||||
duration_secs,
|
||||
fps,
|
||||
progress_tx.cloned(),
|
||||
cancel.cloned(),
|
||||
true,
|
||||
@@ -1452,7 +1332,6 @@ fn run_impl(
|
||||
progress_pass: u8,
|
||||
progress_total_passes: u8,
|
||||
progress_duration_secs: f64,
|
||||
_progress_fps: u32,
|
||||
progress_tx: Option<Sender<EncodeProgress>>,
|
||||
cancel: Option<Arc<AtomicBool>>,
|
||||
read_stdout: bool,
|
||||
@@ -1588,6 +1467,17 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn review_properties_use_muxed_frame_timing() {
|
||||
let properties = parse_output_properties(concat!(
|
||||
"#tb 0: 1/100\n#dimensions 0: 128x96\n",
|
||||
"0, 0, 4, 3, 42, 0x00\n0, 3, 0, 4, 42, 0x00\n0, 6, 7, 3, 42, 0x00\n",
|
||||
)).unwrap();
|
||||
assert_eq!((properties.width, properties.height), (128, 96));
|
||||
assert!((properties.duration_secs - 0.1).abs() < 0.000_001);
|
||||
assert!((properties.fps - 30.0).abs() < 0.000_001);
|
||||
}
|
||||
|
||||
fn dummy_request() -> TranscodeRequest {
|
||||
let dir = std::env::temp_dir().join(format!("bytesize-encode-test-{}", std::process::id()));
|
||||
TranscodeRequest {
|
||||
@@ -1605,7 +1495,6 @@ mod tests {
|
||||
crop: None,
|
||||
gif_budget_mode: GifBudgetMode::Balanced,
|
||||
gif_colors: 256,
|
||||
deleted_frame_indices: vec![],
|
||||
trim_start_secs: None,
|
||||
trim_end_secs: None,
|
||||
clicks: vec![],
|
||||
@@ -1701,6 +1590,36 @@ mod tests {
|
||||
assert!(filter.contains("format=rgb24"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_alignment_pads_whole_sample_frames_and_preserves_retry_gaps() {
|
||||
let dir = std::env::temp_dir();
|
||||
let id = std::process::id();
|
||||
let first = TempFileGuard(dir.join(format!("bytesize-align-{id}-first.pcm")));
|
||||
let retry = TempFileGuard(dir.join(format!("bytesize-align-{id}-retry.pcm")));
|
||||
let out = TempFileGuard(dir.join(format!("bytesize-align-{id}-output.pcm")));
|
||||
let pcm = |samples: &[f32]| {
|
||||
samples.iter().copied().flat_map(f32::to_le_bytes).collect::<Vec<_>>()
|
||||
};
|
||||
std::fs::write(&first.0, pcm(&[0.1, 0.2, 0.3, 0.4])).unwrap();
|
||||
std::fs::write(&retry.0, pcm(&[0.5, 0.6, 0.7, 0.8])).unwrap();
|
||||
let segments = [
|
||||
AudioSegment {
|
||||
path: first.0.clone(), sample_rate: 10, channels: 2, start_secs: 0.12, end_secs: 0.3,
|
||||
},
|
||||
AudioSegment {
|
||||
path: retry.0.clone(), sample_rate: 10, channels: 2, start_secs: 0.48, end_secs: 0.6,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
assemble_pcm(Path::new("ffmpeg"), &segments, &out.0, 0.7).unwrap(),
|
||||
Some((10, 2)),
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(&out.0).unwrap(),
|
||||
pcm(&[0., 0., 0.1, 0.2, 0.3, 0.4, 0., 0., 0., 0., 0.5, 0.6, 0., 0.]),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_filter_output() {
|
||||
let rect = CaptureRect {
|
||||
@@ -1711,7 +1630,7 @@ mod tests {
|
||||
};
|
||||
assert_eq!(
|
||||
crop_filter(Some(rect)),
|
||||
Some("crop=100:200:10:20".to_string())
|
||||
Some("crop=100:200:10:20:exact=1".to_string())
|
||||
);
|
||||
assert_eq!(crop_filter(None), None);
|
||||
}
|
||||
@@ -1726,7 +1645,7 @@ mod tests {
|
||||
button: crate::clicks::MouseButton::Left,
|
||||
})
|
||||
.collect();
|
||||
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||
let filter = click_filters(&clicks, 1920, 1080).unwrap();
|
||||
let count = filter.matches("drawbox").count();
|
||||
assert_eq!(count, MAX_CLICK_HIGHLIGHTS);
|
||||
}
|
||||
@@ -1771,7 +1690,7 @@ mod tests {
|
||||
button: crate::clicks::MouseButton::Left,
|
||||
},
|
||||
];
|
||||
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||
let filter = click_filters(&clicks, 1920, 1080).unwrap();
|
||||
assert_eq!(filter.matches("drawbox").count(), 1);
|
||||
assert!(filter.contains("x=488:y=388"));
|
||||
// Every emitted box must be non-negative, or drawbox throws it away.
|
||||
@@ -1779,48 +1698,33 @@ mod tests {
|
||||
assert!(!filter.contains("y=-"));
|
||||
}
|
||||
|
||||
/// A trim seeks past the head of the clip, which rebases the filter timeline
|
||||
/// to zero, so a click recorded against clip time has to move back by the
|
||||
/// same amount or it fires late by the length of the trim.
|
||||
#[test]
|
||||
fn click_times_are_rebased_by_the_trim() {
|
||||
let clicks = vec![Click {
|
||||
fn click_geometry_and_time_use_the_source_before_crop_and_trim() {
|
||||
let mut req = dummy_request();
|
||||
req.crop = Some(CaptureRect { x: 400, y: 300, width: 520, height: 380 });
|
||||
req.trim_start_secs = Some(5.0);
|
||||
req.clicks = vec![Click {
|
||||
time_secs: 6.0,
|
||||
x: 500,
|
||||
y: 400,
|
||||
button: crate::clicks::MouseButton::Left,
|
||||
}];
|
||||
let untrimmed = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||
assert!(untrimmed.contains("between(t,5.950,6.250)"));
|
||||
let trimmed = click_filters(&clicks, 1920, 1080, 5.0).unwrap();
|
||||
assert!(trimmed.contains("between(t,0.950,1.250)"));
|
||||
assert!(!trimmed.contains("6.250"));
|
||||
}
|
||||
|
||||
/// A click that happened before the trimmed window has nothing left to draw.
|
||||
#[test]
|
||||
fn clicks_before_the_trim_are_dropped() {
|
||||
let clicks = vec![Click {
|
||||
time_secs: 1.0,
|
||||
x: 500,
|
||||
y: 400,
|
||||
button: crate::clicks::MouseButton::Left,
|
||||
}];
|
||||
assert!(click_filters(&clicks, 1920, 1080, 5.0).is_none());
|
||||
let filters = video_filters(&req);
|
||||
assert!(filters.starts_with("drawbox=x=488:y=388:"));
|
||||
assert!(filters.contains("between(t,5.950,6.250)"));
|
||||
assert!(filters.ends_with(",crop=520:380:400:300:exact=1,fps=30"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_shrink_factor_resolution_uses_sqrt() {
|
||||
// ratio 0.25 -> halving the *width* (which quarters pixels) needs sqrt(0.25)=0.5
|
||||
let f = gif_shrink_factor(GifBudgetMode::Resolution, 0.25);
|
||||
assert!((f - 0.5).abs() < 1e-9);
|
||||
}
|
||||
fn gif_budget_retries_preserve_the_selected_priority() {
|
||||
let (mut width, mut fps) = (800, 20);
|
||||
let mode = GifBudgetMode::Resolution;
|
||||
shrink_gif_params(mode, gif_shrink_factor(mode, 0.5), &mut width, &mut fps);
|
||||
assert_eq!((width, fps), (800, 10));
|
||||
|
||||
#[test]
|
||||
fn gif_shrink_factor_framerate_is_linear() {
|
||||
// ratio 0.5 -> halving fps needs factor 0.5
|
||||
let f = gif_shrink_factor(GifBudgetMode::Framerate, 0.5);
|
||||
assert!((f - 0.5).abs() < 1e-9);
|
||||
let mode = GifBudgetMode::Framerate;
|
||||
shrink_gif_params(mode, gif_shrink_factor(mode, 0.25), &mut width, &mut fps);
|
||||
assert_eq!((width, fps), (400, 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user