aether_renderer_core/
lib.rs

1pub mod config;
2pub mod ffmpeg;
3pub mod input;
4pub mod utils;
5
6pub use config::RenderConfig;
7
8use indicatif::{ProgressBar, ProgressStyle};
9use std::process::Command;
10use std::time::Duration;
11
12/// Load configuration from file then render
13pub fn render_from_config(config_path: &str) -> Result<String, String> {
14    let args = RenderConfig::from_file(config_path)?;
15    render(args)
16}
17
18/// Orchestrate rendering from a parsed configuration
19pub fn render(args: RenderConfig) -> Result<String, String> {
20    // Check for ffmpeg availability upfront
21    match {
22        let mut cmd = Command::new("ffmpeg");
23        cmd.arg("-version");
24
25        if !args.verbose_ffmpeg {
26            cmd.stdout(std::process::Stdio::null());
27            cmd.stderr(std::process::Stdio::null());
28        }
29
30        cmd.status()
31    } {
32        Ok(s) if s.success() => {}
33        Ok(_) => {
34            return Err("❌ ffmpeg failed to run correctly.".into());
35        }
36        Err(e) => {
37            if e.kind() == std::io::ErrorKind::NotFound {
38                return Err(
39                    "❌ ffmpeg not found. Please install ffmpeg and ensure it is in your PATH."
40                        .into(),
41                );
42            } else {
43                return Err(format!("❌ Failed to execute ffmpeg: {}", e));
44            }
45        }
46    }
47
48    if !args.input.exists() {
49        return Err(format!(
50            "❌ Input path '{}' does not exist.",
51            args.input.display()
52        ));
53    }
54
55    let input_path = &args.input;
56    let (working_input_path, _temp_guard) = if input_path
57        .extension()
58        .map(|ext| ext == "zip")
59        .unwrap_or(false)
60    {
61        let (path, guard) = utils::unzip_frames(input_path).map_err(|e| e.to_string())?;
62        (path, Some(guard))
63    } else {
64        (input_path.clone(), None)
65    };
66
67    let pattern = args
68        .file_pattern
69        .clone()
70        .unwrap_or_else(|| "*.png".to_string());
71    let frames = input::collect_input_frames(&working_input_path, Some(pattern.clone()))
72        .map_err(|e| format!("❌ Failed to read frames: {}", e))?;
73    let frame_count = frames.len() as u32;
74
75    // Use the provided file pattern when building the ffmpeg input string
76    let input_pattern = working_input_path.join(&pattern);
77    let input_str = input_pattern.to_str().unwrap();
78
79    if frame_count == 0 {
80        return Err(format!(
81            "❌ No input files found in '{}' matching pattern '{}'.",
82            working_input_path.display(),
83            pattern
84        ));
85    }
86
87    let duration = frame_count as f32 / args.fps as f32;
88
89    let mut fade_filter = String::new();
90    if args.fade_in > 0.0 {
91        fade_filter.push_str(&format!("fade=t=in:st=0:d={}", args.fade_in));
92    }
93    if args.fade_out > 0.0 {
94        if !fade_filter.is_empty() {
95            fade_filter.push(',');
96        }
97        let start = (duration - args.fade_out).max(0.0);
98        fade_filter.push_str(&format!("fade=t=out:st={}:d={}", start, args.fade_out));
99    }
100
101    println!(
102        "🌿 Rendering {} → {} at {} FPS...",
103        input_str, args.output, args.fps
104    );
105
106    let maybe_spinner = if args.verbose {
107        let pb = ProgressBar::new_spinner();
108        pb.set_style(
109            ProgressStyle::with_template(
110                "{spinner:.green} 🌿 Rendering with FFmpeg... {elapsed_precise}",
111            )
112            .unwrap()
113            .tick_chars("⠁⠃⠇⠧⠷⠿⠻⠟⠯⠷⠾⠽⠻⠛⠋"),
114        );
115        pb.enable_steady_tick(Duration::from_millis(120));
116        Some(pb)
117    } else {
118        None
119    };
120
121    if args.format == "gif" {
122        ffmpeg::gif::render_gif(
123            input_str,
124            &args.output,
125            args.fps,
126            Some(&fade_filter),
127            args.verbose_ffmpeg,
128        )?;
129    } else {
130        ffmpeg::video::render_video(
131            input_str,
132            &args.output,
133            args.fps,
134            &args.format,
135            args.bitrate.as_deref(),
136            args.crf,
137            Some(&fade_filter),
138            args.verbose_ffmpeg,
139        )?;
140    }
141
142    if let Some(pb) = &maybe_spinner {
143        pb.finish_with_message("✅ FFmpeg rendering complete!");
144    }
145
146    if args.preview {
147        if let Err(e) = utils::open_output(&args.output) {
148            eprintln!("⚠️ Failed to open video preview: {}", e);
149        }
150    }
151    Ok(args.output.clone())
152}