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},
};
const MP3_EXT: &str = "mp3";
const MP4_EXT: &str = "mp4";
const FILE_TYPE_NAME: &str = "MP3";
const DEFAULT_BITRATE: u32 = 320;
const TEMP_COVER_PREFIX: &str = "toolkit-cover-";
const TEMP_COVER_SUFFIX: &str = ".jpg";
#[derive(Debug, Args)]
pub struct Mp32mp4Args {
#[command(flatten)]
pub batch: BatchArgs,
#[arg(long, default_value_t = DEFAULT_BITRATE)]
pub bitrate: u32,
#[arg(long)]
pub no_cover_fallback: bool,
#[arg(value_name = "FILE")]
pub files: Vec<PathBuf>,
}
struct Mp3ToMp4Task {
bitrate: u32,
force: bool,
no_cover_fallback: bool,
}
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,
)
}
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)
}
}