sreepathi-ravikumar's picture
Update rust_highlight/src/lib.rs
fbb769b verified
raw
history blame
2.81 kB
use std::process::Command;
use std::path::Path;
pub fn render_video(
id: usize,
image_path: &str,
audio_path: &str,
duration: f64,
words: Vec<(String, (u32, u32, u32, u32))>,
output_dir: &str,
) -> Result<String, String> {
// Validate paths
if !Path::new(image_path).exists() {
return Err(format!("Image not found: {}", image_path));
}
if !Path::new(audio_path).exists() {
return Err(format!("Audio not found: {}", audio_path));
}
let output_path = format!("{}/clip{}.mp4", output_dir, id);
let duration_str = duration.to_string();
let n_words = words.len() as f64;
let highlight_duration = duration / n_words;
// Build complex filter graph
let mut filter_complex = String::new();
let mut last_output = "0:v".to_string();
for (i, (_, (x, y, w, h))) in words.iter().enumerate() {
let start = i as f64 * highlight_duration;
let end = start + highlight_duration;
// Create highlight box
filter_complex.push_str(&format!(
"[{last_out}]drawbox=x={x}:y={y}:w={w}:h={h}:color=yellow@0.5:t=fill:enable='between(t,{start:.3},{end:.3})'[v{i}];",
last_out = last_output,
x = x,
y = y,
w = w,
h = h,
start = start,
end = end,
i = i
));
last_output = format!("[v{i}]");
}
// Remove trailing semicolon
filter_complex.pop();
// FFmpeg command with optimized settings
let status = Command::new("ffmpeg")
.args(&[
"-y", // Overwrite output
"-hwaccel", "auto", // Enable hardware acceleration
"-loop", "1",
"-i", image_path,
"-i", audio_path,
"-filter_complex", &filter_complex,
"-map", &last_output,
"-map", "1:a",
"-c:v", "libx264",
"-preset", "fast", // Balance between speed and compression
"-crf", "18", // High quality (lower = better quality)
"-pix_fmt", "yuv420p",
"-movflags", "+faststart", // For web streaming
"-c:a", "aac",
"-b:a", "192k", // Higher audio bitrate
"-r", "60", // Higher framerate for smoother animation
"-t", &duration_str,
"-vsync", "2", // Frame rate conversion method
&output_path,
])
.status();
match status {
Ok(exit_status) if exit_status.success() => Ok(output_path),
Ok(_) => Err("FFmpeg command failed".to_string()),
Err(e) => Err(format!("Failed to execute FFmpeg: {}", e)),
}
}
#[pymodule]
fn rust_highlight(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(render_video, m)?)?;
Ok(())
}