toolkitrs 0.1.2

A unified FFmpeg workflow CLI for batch media conversion, remuxing, and thumbnail embedding
//! module mp32mp4 - Convert MP3 files to MP4 videos with optional cover art.
//! Converts MP3 files to MP4 videos with optional cover art using the batch pipeline.

use crate::{
    cli::BatchArgs,
    commands::batch::{run_batch, BatchTask, FileOutcome},
    ffmpeg::{args, Ffmpeg, ProcessRunner},
    util::files,
};
use anyhow::Result;
use clap::Args;
use std::{
    fs,
    path::{Path, PathBuf},
};

// --------------------------------- Types, Constants & Variables ------------------------------- //

/// Extension for MP3 audio files.
const MP3_EXT: &str = "mp3";

/// Extension for MP4 video files.
const MP4_EXT: &str = "mp4";

/// Human readable name for MP3 files.
const FILE_TYPE_NAME: &str = "MP3";

/// Default audio bitrate for MP3 encoding (kbps).
const DEFAULT_BITRATE: u32 = 320;

/// Prefix for temporary cover image files.
const TEMP_COVER_PREFIX: &str = "toolkit-cover-";

/// Suffix for temporary cover image files.
const TEMP_COVER_SUFFIX: &str = ".jpg";

/// Arguments for the `mp32mp4` subcommand.
#[derive(Debug, Args)]
pub struct Mp32mp4Args {
    /// Common batch options like output directory and force overwrite.
    #[command(flatten)]
    pub batch: BatchArgs,

    /// Audio bitrate in kbps for the MP4's audio stream.
    #[arg(long, default_value_t = DEFAULT_BITRATE)]
    pub bitrate: u32,

    /// Skip files without embedded cover art instead of using a black video.
    #[arg(long)]
    pub no_cover_fallback: bool,

    /// MP3 files; scans the current directory when omitted.
    #[arg(value_name = "FILE")]
    pub files: Vec<PathBuf>,
}

/// Task definition for MP3 to MP4 conversion.
struct Mp3ToMp4Task {
    /// Audio bitrate in kbps.
    bitrate: u32,

    /// Whether to force overwrite existing files.
    force: bool,

    /// Whether to skip files without embedded cover art.
    no_cover_fallback: bool,
}

// ----------------------------------------- Public API ----------------------------------------- //

/// Runs the MP3 to MP4 conversion using the generic batch pipeline.
pub fn run<R: ProcessRunner>(args_cli: Mp32mp4Args, ffmpeg: &Ffmpeg<R>) -> Result<()> {
    let task = Mp3ToMp4Task {
        bitrate: args_cli.bitrate,
        force: args_cli.batch.force,
        no_cover_fallback: args_cli.no_cover_fallback,
    };
    run_batch(
        &task,
        args_cli.files,
        &args_cli.batch.output_dir,
        args_cli.batch.force,
        ffmpeg,
    )
}

// -------------------------------------- Internal Helpers -------------------------------------- //

impl BatchTask for Mp3ToMp4Task {
    fn input_extension(&self) -> &str {
        MP3_EXT
    }

    fn output_extension(&self) -> &str {
        MP4_EXT
    }

    fn file_type_name(&self) -> &str {
        FILE_TYPE_NAME
    }

    fn process_file<R: ProcessRunner>(
        &self,
        input: &Path,
        output: &Path,
        ffmpeg: &Ffmpeg<R>,
    ) -> Result<FileOutcome> {
        let cover = files::temp_path(TEMP_COVER_PREFIX, TEMP_COVER_SUFFIX)?;
        let has_cover = ffmpeg
            .run(args::extract_embedded_cover(input, &cover))
            .is_ok()
            && cover.metadata().map(|m| m.len() > 0).unwrap_or(false);

        if !has_cover && self.no_cover_fallback {
            let _ = fs::remove_file(&cover);
            return Ok(FileOutcome::Skipped(format!(
                "no cover art in {}",
                input.display()
            )));
        }

        ffmpeg.run(args::encode_mp4(
            has_cover.then_some(cover.as_path()),
            input,
            output,
            self.bitrate,
            self.force,
        ))?;

        let _ = fs::remove_file(&cover);
        Ok(FileOutcome::Success)
    }
}