current state before improvement pass
This commit is contained in:
+251
-15
@@ -2,6 +2,8 @@ use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::mpsc::Sender;
|
||||
use std::thread;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
|
||||
@@ -9,7 +11,19 @@ use crate::clicks::Click;
|
||||
use crate::config::{Format, GifDither, Mp4Codec, WebmCodec};
|
||||
use crate::CaptureRect;
|
||||
|
||||
const AUDIO_BITRATE_KBPS: u64 = 128;
|
||||
// Used both for bitrate budget calculation and final mux. Must be consistent.
|
||||
const AUDIO_BITRATE_KBPS: u64 = 192;
|
||||
|
||||
/// Progress update sent during encoding.
|
||||
/// pass: 1-based pass number (1 or 2 for two-pass video, 1 for GIF).
|
||||
/// total_passes: total number of passes.
|
||||
/// percent: 0.0 to 100.0.
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize)]
|
||||
pub struct EncodeProgress {
|
||||
pub pass: u8,
|
||||
pub total_passes: u8,
|
||||
pub percent: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TranscodeRequest {
|
||||
@@ -29,8 +43,13 @@ pub struct TranscodeRequest {
|
||||
pub trim_start_secs: Option<f64>,
|
||||
pub trim_end_secs: Option<f64>,
|
||||
pub clicks: Vec<Click>,
|
||||
/// Optional channel to report encoding progress.
|
||||
#[doc(hidden)]
|
||||
pub progress_tx: Option<Sender<EncodeProgress>>,
|
||||
}
|
||||
|
||||
const MAX_CLICK_HIGHLIGHTS: usize = 50;
|
||||
|
||||
fn click_filters(req: &TranscodeRequest) -> Option<String> {
|
||||
if req.clicks.is_empty() {
|
||||
return None;
|
||||
@@ -38,7 +57,15 @@ fn click_filters(req: &TranscodeRequest) -> Option<String> {
|
||||
let size = 24i32;
|
||||
let half = size / 2;
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
for click in &req.clicks {
|
||||
let clicks_to_render = req.clicks.len().min(MAX_CLICK_HIGHLIGHTS);
|
||||
if req.clicks.len() > MAX_CLICK_HIGHLIGHTS {
|
||||
tracing::warn!(
|
||||
"{} click events recorded, only first {} will be highlighted",
|
||||
req.clicks.len(),
|
||||
MAX_CLICK_HIGHLIGHTS
|
||||
);
|
||||
}
|
||||
for click in &req.clicks[..clicks_to_render] {
|
||||
let x = click.x - half;
|
||||
let y = click.y - half;
|
||||
let t1 = (click.time_secs - 0.05).max(0.0);
|
||||
@@ -206,9 +233,8 @@ fn two_pass_video(
|
||||
req: &TranscodeRequest,
|
||||
video_codec: &str,
|
||||
audio_codec: &str,
|
||||
container: &str,
|
||||
_container: &str,
|
||||
) -> Result<()> {
|
||||
let _ = container;
|
||||
let bitrate_kbps = video_bitrate_kbps(req)?;
|
||||
let bitrate = format!("{bitrate_kbps}k");
|
||||
|
||||
@@ -245,7 +271,16 @@ fn two_pass_video(
|
||||
.arg("-an")
|
||||
.args(["-f", "null"])
|
||||
.arg(null_target);
|
||||
run(&mut pass1, "pass 1")?;
|
||||
|
||||
let tx = req.progress_tx.clone();
|
||||
let dur = req.duration_secs;
|
||||
let fps = req.fps;
|
||||
run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref())?;
|
||||
|
||||
// Send 50% to signal pass 1 done, pass 2 starting.
|
||||
if let Some(ref t) = tx {
|
||||
let _ = t.send(EncodeProgress { pass: 1, total_passes: 2, percent: 100.0 });
|
||||
}
|
||||
|
||||
let mut pass2 = Command::new(ffmpeg);
|
||||
pass2
|
||||
@@ -270,7 +305,7 @@ fn two_pass_video(
|
||||
pass2.arg("-an");
|
||||
}
|
||||
pass2.arg(&req.output);
|
||||
run(&mut pass2, "pass 2")?;
|
||||
run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref())?;
|
||||
|
||||
cleanup_pass_logs(&log_stem);
|
||||
Ok(())
|
||||
@@ -356,7 +391,15 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
.args(["-lavfi", &use_filter])
|
||||
.args(["-loop", "0"])
|
||||
.arg(&req.output);
|
||||
run(&mut encode, "gif encode")?;
|
||||
run_with_progress(
|
||||
&mut encode,
|
||||
"gif encode",
|
||||
1,
|
||||
1,
|
||||
req.duration_secs,
|
||||
req.fps,
|
||||
req.progress_tx.as_ref(),
|
||||
)?;
|
||||
|
||||
let _ = std::fs::remove_file(&palette_path);
|
||||
Ok(())
|
||||
@@ -533,6 +576,44 @@ 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)?;
|
||||
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);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run an ffmpeg command with progress monitoring.
|
||||
/// progress_tx, if provided, receives (pass, total_passes, percent) updates.
|
||||
fn run_with_progress(
|
||||
cmd: &mut Command,
|
||||
label: &str,
|
||||
pass: u8,
|
||||
total_passes: u8,
|
||||
duration_secs: f64,
|
||||
fps: u32,
|
||||
progress_tx: Option<&Sender<EncodeProgress>>,
|
||||
) -> Result<()> {
|
||||
let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.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);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_impl(
|
||||
cmd: &mut Command,
|
||||
label: &str,
|
||||
progress_pass: u8,
|
||||
progress_total_passes: u8,
|
||||
progress_duration_secs: f64,
|
||||
progress_fps: u32,
|
||||
progress_tx: Option<Sender<EncodeProgress>>,
|
||||
) -> Result<std::process::Output> {
|
||||
use std::process::Stdio;
|
||||
|
||||
let mut printable = OsString::from(label);
|
||||
@@ -544,14 +625,169 @@ fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
||||
}
|
||||
tracing::debug!("{}", printable.to_string_lossy());
|
||||
|
||||
cmd.stdout(Stdio::null()).stderr(Stdio::piped());
|
||||
let output = cmd
|
||||
.output()
|
||||
let mut child = cmd
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.with_context(|| format!("spawning ffmpeg for {label}"))?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let tail: String = stderr.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n");
|
||||
bail!("ffmpeg {label} exited with {}: {}", output.status, tail);
|
||||
|
||||
// Spawn a thread to monitor stderr and emit progress.
|
||||
let stderr = child.stderr.take();
|
||||
let tx = progress_tx.clone();
|
||||
|
||||
let handle = stderr.map(move |serr| {
|
||||
// Clone the Sender if present.
|
||||
let tx = tx.as_ref().map(|t| t.clone());
|
||||
let encode_dur = progress_duration_secs;
|
||||
let fps = progress_fps;
|
||||
let pass = progress_pass;
|
||||
let total_passes = progress_total_passes;
|
||||
thread::spawn(move || {
|
||||
use std::io::{BufRead, BufReader};
|
||||
let reader = BufReader::new(serr);
|
||||
for line in reader.lines().map_while(Result::ok) {
|
||||
if let Some(frame) = parse_frame_from_stderr(&line) {
|
||||
let total = (encode_dur * fps as f64).max(1.0);
|
||||
let percent = (frame / total * 100.0).min(100.0);
|
||||
if let Some(ref sender) = tx {
|
||||
let _ = sender.send(EncodeProgress {
|
||||
pass,
|
||||
total_passes,
|
||||
percent,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
let output = child.wait_with_output().context("waiting for ffmpeg")?;
|
||||
if let Some(h) = handle {
|
||||
let _ = h.join();
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Parse a frame count from an ffmpeg stderr progress line.
|
||||
/// Lines look like: "frame= 123 fps= 30 q=-0.0 size= 1024kB time=00:00:04.10 ..."
|
||||
fn parse_frame_from_stderr(line: &str) -> Option<f64> {
|
||||
let trimmed = line.trim();
|
||||
if !trimmed.starts_with("frame=") {
|
||||
return None;
|
||||
}
|
||||
// Find the "frame= NNN" token and extract the number after it.
|
||||
let after = trimmed.strip_prefix("frame=")?.trim_start();
|
||||
let end = after
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(after.len());
|
||||
let frame_str = &after[..end];
|
||||
frame_str.parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn dummy_request() -> TranscodeRequest {
|
||||
TranscodeRequest {
|
||||
input: PathBuf::new(),
|
||||
output: PathBuf::new(),
|
||||
format: Format::Mp4,
|
||||
target_bytes: 0,
|
||||
duration_secs: 10.0,
|
||||
fps: 30,
|
||||
keep_audio: true,
|
||||
gif_dither: GifDither::FloydSteinberg,
|
||||
webm_codec: WebmCodec::Vp9,
|
||||
mp4_codec: Mp4Codec::H264,
|
||||
scratch_dir: PathBuf::new(),
|
||||
crop: None,
|
||||
deleted_frame_indices: vec![],
|
||||
trim_start_secs: None,
|
||||
trim_end_secs: None,
|
||||
clicks: vec![],
|
||||
progress_tx: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitrate_for_8mb_10s_with_audio() {
|
||||
let mut req = dummy_request();
|
||||
req.target_bytes = 8 * 1024 * 1024;
|
||||
req.duration_secs = 10.0;
|
||||
req.keep_audio = true;
|
||||
let kbps = video_bitrate_kbps(&req).unwrap();
|
||||
// 8 MB * 8 * 0.95 = 60.96 Mbits total
|
||||
// minus 192k * 10 = 1.92 Mbits audio
|
||||
// video = ~59 Mbits / 10s = ~5900 kbps
|
||||
assert!(kbps > 5800 && kbps < 6200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitrate_for_8mb_10s_no_audio() {
|
||||
let mut req = dummy_request();
|
||||
req.target_bytes = 8 * 1024 * 1024;
|
||||
req.duration_secs = 10.0;
|
||||
req.keep_audio = false;
|
||||
let kbps = video_bitrate_kbps(&req).unwrap();
|
||||
// 8 MB * 8 * 0.95 = 60.96 Mbits total, all video
|
||||
// 60.96 Mbits / 10s = ~6096 kbps
|
||||
assert!(kbps > 6000 && kbps < 6500);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitrate_rejects_too_small() {
|
||||
let mut req = dummy_request();
|
||||
req.target_bytes = 1000;
|
||||
req.duration_secs = 10.0;
|
||||
req.keep_audio = true;
|
||||
assert!(video_bitrate_kbps(&req).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitrate_floor_at_16_kbps() {
|
||||
let mut req = dummy_request();
|
||||
req.target_bytes = 1024 * 1024;
|
||||
req.duration_secs = 600.0;
|
||||
req.keep_audio = false;
|
||||
let kbps = video_bitrate_kbps(&req).unwrap();
|
||||
assert_eq!(kbps, 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ffmpeg_stderr_frame() {
|
||||
assert_eq!(
|
||||
parse_frame_from_stderr("frame= 123 fps= 30 q=-0.0 size= 1024kB"),
|
||||
Some(123.0)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_frame_from_stderr("frame=9999 fps=60.0"),
|
||||
Some(9999.0)
|
||||
);
|
||||
assert_eq!(parse_frame_from_stderr("size= 1024kB"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_filter_output() {
|
||||
let rect = CaptureRect { x: 10, y: 20, width: 100, height: 200 };
|
||||
assert_eq!(
|
||||
crop_filter(Some(rect)),
|
||||
Some("crop=100:200:10:20".to_string())
|
||||
);
|
||||
assert_eq!(crop_filter(None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn click_filters_capped_at_max() {
|
||||
let clicks: Vec<Click> = (0..100)
|
||||
.map(|i| Click { time_secs: i as f64, x: i, y: i })
|
||||
.collect();
|
||||
let req = TranscodeRequest {
|
||||
clicks,
|
||||
..dummy_request()
|
||||
};
|
||||
let filter = click_filters(&req).unwrap();
|
||||
let count = filter.matches("drawbox").count();
|
||||
assert_eq!(count, MAX_CLICK_HIGHLIGHTS);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user