use crate::{
cli::BatchArgs,
commands::batch::{run_batch, BatchFuture, BatchTask, FileOutcome},
ffmpeg::{args, Ffmpeg, ProcessRunner},
util::files,
workflow::{Workflow, WorkflowOptions},
};
use anyhow::Result;
use clap::Args;
use std::{
fs,
path::{Path, PathBuf},
};
use tokio_util::sync::CancellationToken;
const DEFAULT_BITRATE: u32 = 320;
const TEMP_COVER_PREFIX: &str = "toolkitrs-cover-";
const TEMP_COVER_SUFFIX: &str = ".jpg";
#[derive(Debug, Args)]
#[command(after_help = "Examples:
toolkitrs mp32mp4 Scan and process all .mp3 files in the current directory
toolkitrs mp32mp4 song.mp3 Process one file; prompt if sibling .mp3 files exist
toolkitrs mp32mp4 --batch --input-dir /dir Process all .mp3 files in /dir
toolkitrs mp32mp4 --batch --on-error skip Continue past errors and report at the end
toolkitrs mp32mp4 --no-cover-fallback Skip files without embedded cover art")]
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>,
}
#[derive(Debug, Clone, Copy)]
struct Mp3ToMp4Task {
bitrate: u32,
force: bool,
no_cover_fallback: bool,
}
impl Mp3ToMp4Task {
fn workflow_options(self) -> WorkflowOptions {
WorkflowOptions {
force: self.force,
bitrate: self.bitrate,
no_cover_fallback: self.no_cover_fallback,
..WorkflowOptions::default()
}
}
}
impl BatchTask for Mp3ToMp4Task {
fn input_extension(&self) -> &str {
Workflow::Mp32Mp4.input_extension()
}
fn output_extension(&self) -> &str {
Workflow::Mp32Mp4.output_extension()
}
fn file_type_name(&self) -> &str {
Workflow::Mp32Mp4.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 = match ffmpeg.run(args::extract_embedded_cover(input, &cover)) {
Ok(_) => has_file_content(&cover),
Err(error) => {
eprintln!(
"WARNING: Failed to extract cover art from {}: {}",
input.display(),
error
);
cleanup_temp_file(&cover);
false
}
};
if !has_cover && self.no_cover_fallback {
cleanup_temp_file(&cover);
return Ok(FileOutcome::Skipped(format!(
"no cover art in {}",
input.display()
)));
}
let result = ffmpeg.run(args::encode_mp4(
has_cover.then_some(cover.as_path()),
input,
output,
self.bitrate,
self.force,
));
cleanup_temp_file(&cover);
result?;
Ok(FileOutcome::Success)
}
fn process_file_async(
&self,
input: PathBuf,
output: PathBuf,
ffmpeg_binary: PathBuf,
cancel: CancellationToken,
) -> BatchFuture {
let options = self.workflow_options();
Box::pin(async move {
Workflow::Mp32Mp4
.run_async(input, output, &options, &ffmpeg_binary, cancel, None)
.await
})
}
}
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.batch, args_cli.files, ffmpeg)
}
fn has_file_content(path: &Path) -> bool {
path.metadata().map(|meta| meta.len() > 0).unwrap_or(false)
}
fn cleanup_temp_file(path: &Path) {
let _ = fs::remove_file(path);
}