summaryrefslogtreecommitdiff
path: root/morphology-img/src/render.rs
diff options
context:
space:
mode:
Diffstat (limited to 'morphology-img/src/render.rs')
-rw-r--r--morphology-img/src/render.rs224
1 files changed, 57 insertions, 167 deletions
diff --git a/morphology-img/src/render.rs b/morphology-img/src/render.rs
index a437a21..842f796 100644
--- a/morphology-img/src/render.rs
+++ b/morphology-img/src/render.rs
@@ -53,55 +53,69 @@ pub fn check_lilypond_available() -> Result<String, RenderError> {
}
}
-/// Renders a single .ly file to SVG using LilyPond.
+/// Renders multiple .ly files to SVGs by calling LilyPond once with all files.
///
-/// This function invokes the LilyPond CLI to convert a LilyPond source file
-/// into an SVG image. The SVG file will be created in the specified output directory.
+/// This function invokes LilyPond with all .ly files as arguments in a single command,
+/// which is significantly more efficient than calling LilyPond separately for each file.
+/// It eliminates process startup overhead and allows the OS to handle scheduling optimally.
///
/// # Arguments
-/// - `ly_file`: Path to the .ly file to render
-/// - `output_dir`: Directory where the SVG should be created
+/// - `ly_files`: Paths to the .ly files to render
+/// - `output_dir`: Directory where SVGs should be created
/// - `lilypond_binary`: Path to the LilyPond binary (typically "lilypond")
///
/// # Returns
-/// Path to the generated SVG file
+/// Vector of paths to generated SVG files, in the same order as input
///
/// # Errors
/// - `RenderError::FileIO` if the output directory cannot be created
/// - `RenderError::LilyPondExecution` if LilyPond fails to execute or produce output
-/// - `RenderError::Template` if the .ly filename is invalid
+/// - `RenderError::Template` if any .ly filename is invalid
///
/// # Examples
/// ```no_run
-/// use morphology_img::render::render_ly_to_svg;
-/// use std::path::Path;
+/// use morphology_img::render::render_all_ly_files_batch;
+/// use std::path::{Path, PathBuf};
///
-/// let ly_file = Path::new("/tmp/sequence-0.ly");
+/// let ly_files = vec![
+/// PathBuf::from("/tmp/sequence-0.ly"),
+/// PathBuf::from("/tmp/sequence-1.ly"),
+/// ];
/// let output_dir = Path::new("output");
/// let lilypond = Path::new("lilypond");
///
-/// let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond).unwrap();
-/// println!("Generated SVG: {}", svg_path.display());
+/// let svg_paths = render_all_ly_files_batch(&ly_files, output_dir, lilypond).unwrap();
+/// println!("Generated {} SVG files", svg_paths.len());
/// ```
///
-/// # Notes
-/// - LilyPond creates `filename.svg` from `filename.ly` in the output directory
-/// - The function verifies that the expected SVG file was actually created
-/// - LilyPond must be installed and the binary must be accessible
-pub fn render_ly_to_svg(
- ly_file: &Path,
+/// # Performance Notes
+/// - All files are processed in a single LilyPond invocation
+/// - Much faster than sequential individual file processing
+/// - Optimal for batches of any size
+pub fn render_all_ly_files_batch(
+ ly_files: &[PathBuf],
output_dir: &Path,
lilypond_binary: &Path,
-) -> Result<PathBuf, RenderError> {
+) -> Result<Vec<PathBuf>, RenderError> {
+ // Handle empty input
+ if ly_files.is_empty() {
+ return Ok(Vec::new());
+ }
+
// Ensure output directory exists
fs::create_dir_all(output_dir)?;
- // Build the command: lilypond --svg -o output_dir ly_file
+ // Get the directory containing the .ly files (should all be in same temp dir)
+ let ly_dir = ly_files[0]
+ .parent()
+ .ok_or_else(|| RenderError::Template("Invalid .ly file path".to_string()))?;
+
+ // Build command: lilypond --svg file1.ly file2.ly file3.ly ...
+ // WITHOUT -o flag, so SVGs are created next to .ly files with correct names
let output = Command::new(lilypond_binary)
.arg("--svg")
- .arg("-o")
- .arg(output_dir)
- .arg(ly_file)
+ .args(ly_files)
+ .current_dir(ly_dir) // Run in the temp directory
.output()?;
if !output.status.success() {
@@ -109,156 +123,32 @@ pub fn render_ly_to_svg(
return Err(RenderError::LilyPondExecution(stderr.to_string()));
}
- // Determine the output SVG path
- // LilyPond creates filename.svg from filename.ly
- let svg_filename = ly_file
- .file_stem()
- .ok_or_else(|| RenderError::Template("Invalid .ly filename".to_string()))?
- .to_string_lossy()
- .to_string() + ".svg";
+ // Copy SVG files from temp directory to output directory
+ let mut svg_paths = Vec::with_capacity(ly_files.len());
- let svg_path = output_dir.join(svg_filename);
+ for ly_file in ly_files.iter() {
+ let svg_filename = ly_file
+ .file_stem()
+ .ok_or_else(|| RenderError::Template("Invalid .ly filename".to_string()))?
+ .to_string_lossy()
+ .to_string() + ".svg";
- // Verify the SVG was created
- if !svg_path.exists() {
- return Err(RenderError::LilyPondExecution(
- format!("Expected SVG not created: {}", svg_path.display())
- ));
- }
+ // SVG was created next to the .ly file in temp directory
+ let temp_svg_path = ly_dir.join(&svg_filename);
- Ok(svg_path)
-}
-
-/// Renders multiple .ly files to SVGs using LilyPond.
-///
-/// This function processes multiple LilyPond source files sequentially,
-/// converting each to an SVG image in the specified output directory.
-///
-/// # Arguments
-/// - `ly_files`: Paths to the .ly files to render
-/// - `output_dir`: Directory where SVGs should be created
-/// - `lilypond_binary`: Path to the LilyPond binary
-/// - `progress_callback`: Optional callback for progress reporting
-///
-/// # Returns
-/// Vector of paths to generated SVG files, in the same order as input
-///
-/// # Errors
-/// Returns an error if any file fails to render. Processing stops at the first error.
-///
-/// # Examples
-/// ```no_run
-/// use morphology_img::render::render_ly_files_to_svg;
-/// use std::path::{Path, PathBuf};
-///
-/// let ly_files = vec![
-/// PathBuf::from("/tmp/sequence-0.ly"),
-/// PathBuf::from("/tmp/sequence-1.ly"),
-/// ];
-/// let output_dir = Path::new("output");
-/// let lilypond = Path::new("lilypond");
-///
-/// let svg_paths = render_ly_files_to_svg(&ly_files, output_dir, lilypond, None).unwrap();
-/// println!("Generated {} SVG files", svg_paths.len());
-/// ```
-///
-/// # Notes
-/// - Files are processed sequentially (not in parallel)
-/// - All SVGs are created in the same output directory
-/// - If any file fails, an error is returned immediately
-/// - Progress callback is called after each file is rendered (if provided)
-pub fn render_ly_files_to_svg(
- ly_files: &[PathBuf],
- output_dir: &Path,
- lilypond_binary: &Path,
- progress_callback: Option<&crate::ProgressCallback>,
-) -> Result<Vec<PathBuf>, RenderError> {
- let total_count = ly_files.len();
- let mut svg_paths = Vec::with_capacity(total_count);
+ // Verify the SVG was created
+ if !temp_svg_path.exists() {
+ return Err(RenderError::LilyPondExecution(
+ format!("Expected SVG not created: {}", temp_svg_path.display())
+ ));
+ }
- for (index, ly_file) in ly_files.iter().enumerate() {
- let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond_binary)?;
- svg_paths.push(svg_path);
+ // Copy to output directory (can't use rename - may be different filesystem)
+ let final_svg_path = output_dir.join(&svg_filename);
+ fs::copy(&temp_svg_path, &final_svg_path)?;
- // Call progress callback if provided
- if let Some(callback) = progress_callback {
- callback(index + 1, total_count);
- }
+ svg_paths.push(final_svg_path);
}
Ok(svg_paths)
}
-
-/// Renders multiple .ly files to SVGs using LilyPond in parallel.
-///
-/// This function processes multiple LilyPond source files concurrently using rayon,
-/// converting each to an SVG image in the specified output directory. This can
-/// significantly improve performance for large batches on multi-core systems.
-///
-/// # Arguments
-/// - `ly_files`: Paths to the .ly files to render
-/// - `output_dir`: Directory where SVGs should be created
-/// - `lilypond_binary`: Path to the LilyPond binary
-/// - `progress_callback`: Optional callback for progress reporting
-///
-/// # Returns
-/// Vector of paths to generated SVG files, in the same order as input
-///
-/// # Errors
-/// Returns an error if any file fails to render. Processing stops at the first error.
-///
-/// # Performance Notes
-/// - Files are processed in parallel using rayon
-/// - Progress callbacks may be invoked out of order (but still track correct indices)
-/// - Best for batches of 10+ files on multi-core systems
-/// - May be slower than sequential for very small batches due to overhead
-///
-/// # Examples
-/// ```no_run
-/// use morphology_img::render::render_ly_files_to_svg_parallel;
-/// use std::path::{Path, PathBuf};
-///
-/// let ly_files = vec![
-/// PathBuf::from("/tmp/sequence-0.ly"),
-/// PathBuf::from("/tmp/sequence-1.ly"),
-/// ];
-/// let output_dir = Path::new("output");
-/// let lilypond = Path::new("lilypond");
-///
-/// let svg_paths = render_ly_files_to_svg_parallel(&ly_files, output_dir, lilypond, None).unwrap();
-/// println!("Generated {} SVG files", svg_paths.len());
-/// ```
-pub fn render_ly_files_to_svg_parallel(
- ly_files: &[PathBuf],
- output_dir: &Path,
- lilypond_binary: &Path,
- progress_callback: Option<&crate::ProgressCallback>,
-) -> Result<Vec<PathBuf>, RenderError> {
- use rayon::prelude::*;
- use std::sync::atomic::{AtomicUsize, Ordering};
- use std::sync::Arc;
-
- let total_count = ly_files.len();
-
- // Use atomic counter for progress tracking
- let completed = Arc::new(AtomicUsize::new(0));
-
- // Process files in parallel
- let results: Vec<Result<PathBuf, RenderError>> = ly_files
- .par_iter()
- .map(|ly_file| {
- let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond_binary)?;
-
- // Update progress if callback is provided
- if let Some(callback) = progress_callback {
- let current = completed.fetch_add(1, Ordering::SeqCst) + 1;
- callback(current, total_count);
- }
-
- Ok(svg_path)
- })
- .collect();
-
- // Collect results, returning early on first error
- results.into_iter().collect()
-}