geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! Stage 1: extract evenly-spaced frames from a drone video via ffmpeg.
//!
//! The extraction rate (`--fps`) controls how many frames per second of
//! footage are written. A slow orbit flight recorded at 4K benefits from a
//! low rate (1–2 fps) with high overlap; a faster flyover needs a higher
//! rate to keep frame-to-frame overlap above the photogrammetry floor.

use std::path::Path;
use std::process::{Command, Stdio};

/// Extract frames from `video` into `out_dir` at `fps` frames per second.
///
/// Frames are written as zero-padded JPEGs (`00001.jpg`, `00002.jpg`, …).
/// The directory is created if missing; existing frames are left untouched
/// (callers rely on [`super::Layout::stage_done`] for resume semantics).
///
/// # Errors
///
/// Returns an error if ffmpeg is missing or fails, or if the output
/// directory cannot be created.
pub fn extract_frames(
    video: &Path,
    out_dir: &Path,
    fps: f64,
    max_frames: Option<usize>,
) -> crate::error::Result<usize> {
    if !video.is_file() {
        return Err(crate::error::GeolithError::Ffmpeg(format!(
            "video not found: {}",
            video.display()
        )));
    }
    std::fs::create_dir_all(out_dir)?;

    let mut command = Command::new("ffmpeg");
    command
        .arg("-hide_banner")
        .arg("-loglevel")
        .arg("error")
        .arg("-i")
        .arg(video)
        .arg("-vf")
        .arg(format!("fps={fps}"))
        .arg("-q:v")
        .arg("2") // high JPEG quality for photogrammetry features
        .arg("-start_number")
        .arg("1")
        .arg("-y")
        .arg(out_dir.join("%05d.jpg"));

    let status = command
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .status();

    match status {
        Ok(status) if status.success() => {}
        Ok(status) => {
            return Err(crate::error::GeolithError::Ffmpeg(format!(
                "ffmpeg exited with {status:?} while extracting frames from {}",
                video.display()
            )));
        }
        Err(error) => {
            return Err(crate::error::GeolithError::Ffmpeg(format!(
                "failed to run ffmpeg: {error}"
            )));
        }
    }

    if let Some(max) = max_frames {
        let (kept, removed) = cap_frames(out_dir, max)?;
        tracing::info!(kept, removed, max, "capped extracted frames");
    }

    let count = std::fs::read_dir(out_dir)?
        .filter_map(std::result::Result::ok)
        .filter(|entry| {
            entry
                .path()
                .extension()
                .and_then(|ext| ext.to_str())
                .is_some_and(|ext| matches!(ext, "jpg" | "jpeg"))
        })
        .count();

    tracing::info!(
        frames = count,
        fps,
        source = %video.display(),
        out = %out_dir.display(),
        "frames extracted"
    );
    Ok(count)
}

/// Keep the first `max` extracted frames in name order and delete the rest.
///
/// Returns `(kept, removed)`.
///
/// The surviving set must not depend on directory order. `read_dir` returns
/// entries in filesystem order, which differs between macOS and Linux, so an
/// unsorted cap would delete a different tail on each machine and make the
/// reconstruction non-reproducible. Sorting by path makes the kept set a
/// function of the frame names alone.
///
/// # Errors
///
/// Returns an error if the directory cannot be read or a frame cannot be
/// deleted.
fn cap_frames(out_dir: &Path, max: usize) -> crate::error::Result<(usize, usize)> {
    let mut frames: Vec<std::path::PathBuf> = std::fs::read_dir(out_dir)?
        .filter_map(std::result::Result::ok)
        .map(|entry| entry.path())
        .filter(|path| {
            path.extension()
                .and_then(|ext| ext.to_str())
                .is_some_and(|ext| matches!(ext, "jpg" | "jpeg"))
        })
        .collect();
    frames.sort();

    let mut removed = 0;
    for path in frames.iter().skip(max) {
        std::fs::remove_file(path)?;
        removed += 1;
    }

    Ok((frames.len().min(max), removed))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Write `names` as empty files and return the directory holding them.
    fn frame_dir(names: &[&str]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        for name in names {
            std::fs::write(dir.path().join(name), b"").expect("write frame");
        }
        dir
    }

    /// Surviving file names, sorted so the assertion does not depend on
    /// directory order.
    fn surviving(dir: &std::path::Path) -> Vec<String> {
        let mut names: Vec<String> = std::fs::read_dir(dir)
            .expect("read dir")
            .filter_map(std::result::Result::ok)
            .map(|entry| entry.file_name().to_string_lossy().into_owned())
            .collect();
        names.sort();
        names
    }

    #[test]
    fn cap_keeps_the_lowest_numbered_frames() {
        let dir = frame_dir(&["00003.jpg", "00001.jpg", "00004.jpg", "00002.jpg"]);

        let (kept, removed) = cap_frames(dir.path(), 2).expect("cap");

        assert_eq!((kept, removed), (2, 2));
        assert_eq!(surviving(dir.path()), vec!["00001.jpg", "00002.jpg"]);
    }

    #[test]
    fn cap_is_a_no_op_when_below_the_limit() {
        let dir = frame_dir(&["00001.jpg", "00002.jpg"]);

        let (kept, removed) = cap_frames(dir.path(), 10).expect("cap");

        assert_eq!((kept, removed), (2, 0));
        assert_eq!(surviving(dir.path()), vec!["00001.jpg", "00002.jpg"]);
    }

    #[test]
    fn cap_ignores_files_that_are_not_frames() {
        let dir = frame_dir(&["00001.jpg", "00002.jpg", "notes.txt", "cameras.json"]);

        let (kept, removed) = cap_frames(dir.path(), 1).expect("cap");

        assert_eq!((kept, removed), (1, 1));
        assert_eq!(
            surviving(dir.path()),
            vec!["00001.jpg", "cameras.json", "notes.txt"],
            "only frames are capped; sidecar files must survive"
        );
    }

    #[test]
    fn missing_video_is_an_error() {
        let err = extract_frames(
            Path::new("/nonexistent/video.mp4"),
            Path::new("/tmp/x"),
            2.0,
            None,
        )
        .expect_err("missing video must fail");
        assert!(err.to_string().contains("video not found"));
    }
}