shrivel 0.2.1

Cross-platform FFmpeg orchestrator that transcodes videos to HEVC or AV1
//! Command-line interface definition.

use std::path::PathBuf;

use clap::{Parser, ValueEnum};

/// Output video codec.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
pub enum Codec {
    #[default]
    Hevc,
    Av1,
}

impl std::fmt::Display for Codec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Hevc => "hevc",
            Self::Av1 => "av1",
        })
    }
}

/// Which encoder backend to use.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum EncoderChoice {
    /// Probe the available encoders and pick the first one that works.
    Auto,
    /// NVIDIA NVENC (`hevc_nvenc` or `av1_nvenc`).
    Nvenc,
    /// Intel Quick Sync Video (`hevc_qsv` or `av1_qsv`).
    Qsv,
    /// AMD AMF (`hevc_amf` or `av1_amf`).
    Amf,
    /// Apple VideoToolbox (`hevc_videotoolbox`, HEVC only).
    Videotoolbox,
    /// CPU encoding with x265 (`libx265`) or SVT-AV1 (`libsvtav1`).
    Software,
}

/// Batch re-encode videos by orchestrating FFmpeg.
#[derive(Debug, Parser)]
#[command(name = "shrivel", version, about, long_about = None)]
pub struct Cli {
    /// Output video codec.
    #[arg(long, value_enum, default_value_t = Codec::default())]
    pub codec: Codec,
    /// Video file or directory containing source videos.
    #[arg(short, long, value_name = "DIR", default_value = "input")]
    pub input: PathBuf,

    /// Directory where converted videos are written (created if missing).
    #[arg(short, long, value_name = "DIR", default_value = "output")]
    pub output: PathBuf,

    /// Normalized compression value (0-51). Lower generally means better
    /// quality; shrivel maps it to the selected encoder's native scale.
    #[arg(
        long,
        value_name = "N",
        default_value_t = 26,
        value_parser = clap::value_parser!(u8).range(0..=51)
    )]
    pub cq: u8,

    /// Target frame rate. Omit to keep the source frame rate.
    #[arg(long, value_name = "FPS", value_parser = parse_fps)]
    pub fps: Option<f64>,

    /// Skip files whose video stream already uses the selected codec.
    #[arg(long, alias = "skip-hevc")]
    pub skip_same_codec: bool,

    /// Apply a light spatial/temporal denoise filter (hqdn3d).
    #[arg(long)]
    pub denoise: bool,

    /// Encoder backend.
    #[arg(short, long, value_enum, default_value_t = EncoderChoice::Auto)]
    pub encoder: EncoderChoice,

    /// Comma-separated list of input file extensions to process.
    #[arg(
        long,
        value_name = "EXT,...",
        value_delimiter = ',',
        default_value = "mp4"
    )]
    pub ext: Vec<String>,

    /// Do not overwrite output files that already exist (skip them instead).
    #[arg(long)]
    pub skip_existing: bool,

    /// Target width for scaling. Height is calculated automatically.
    #[arg(long, value_name = "WIDTH", value_parser = clap::value_parser!(u32).range(1..))]
    pub scale: Option<u32>,

    /// Print the FFmpeg commands that would run without executing them.
    #[arg(long)]
    pub dry_run: bool,
}

fn parse_fps(s: &str) -> Result<f64, String> {
    let value: f64 = s
        .parse()
        .map_err(|_| format!("`{s}` is not a valid number"))?;
    if value.is_finite() && value > 0.0 {
        Ok(value)
    } else {
        Err("frame rate must be greater than zero".to_string())
    }
}

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

    #[test]
    fn fps_parser_accepts_positive_numbers() {
        assert_eq!(parse_fps("29.97"), Ok(29.97));
        assert_eq!(parse_fps("30"), Ok(30.0));
    }

    #[test]
    fn fps_parser_rejects_invalid_values() {
        assert!(parse_fps("0").is_err());
        assert!(parse_fps("-5").is_err());
        assert!(parse_fps("abc").is_err());
        assert!(parse_fps("inf").is_err());
    }
}