use serde::{Deserialize, Serialize};
use crate::error::{MediaError, Result};
use crate::ffmpeg::{Exec, Input, Job};
use crate::pcm::{Pcm, TRANSCRIBE_RATE, decode_wav, encode_wav, wav_bytes};
use crate::probe::looks_like_wav;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum AudioFormat {
Wav,
Mp3,
Opus,
Flac,
}
impl AudioFormat {
pub fn mime(self) -> &'static str {
match self {
AudioFormat::Wav => "audio/wav",
AudioFormat::Mp3 => "audio/mpeg",
AudioFormat::Opus => "audio/ogg",
AudioFormat::Flac => "audio/flac",
}
}
pub fn extension(self) -> &'static str {
match self {
AudioFormat::Wav => "wav",
AudioFormat::Mp3 => "mp3",
AudioFormat::Opus => "opus",
AudioFormat::Flac => "flac",
}
}
pub fn from_name(name: &str) -> Option<AudioFormat> {
match name.to_ascii_lowercase().as_str() {
"wav" | "wave" => Some(AudioFormat::Wav),
"mp3" | "mpeg" => Some(AudioFormat::Mp3),
"opus" | "ogg" => Some(AudioFormat::Opus),
"flac" => Some(AudioFormat::Flac),
_ => None,
}
}
}
fn secs(ms: u64) -> String {
format!("{}.{:03}", ms / 1000, ms % 1000)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Extract {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub start_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub len_ms: Option<u64>,
pub sample_rate: u32,
pub channels: u16,
pub max_len_ms: u64,
}
impl Extract {
pub fn transcribe(max_len_ms: u64) -> Self {
Extract { start_ms: None, len_ms: None, sample_rate: TRANSCRIBE_RATE, channels: 1, max_len_ms }
}
pub fn new(sample_rate: u32, channels: u16, max_len_ms: u64) -> Self {
Extract { start_ms: None, len_ms: None, sample_rate, channels, max_len_ms }
}
pub fn range(mut self, start_ms: u64, len_ms: u64) -> Self {
self.start_ms = Some(start_ms);
self.len_ms = Some(len_ms);
self
}
}
pub fn extract(exec: &dyn Exec, input: &Input, what: &Extract) -> Result<Vec<u8>> {
let mut job = Job::ffmpeg(input.clone());
if let Some(s) = what.start_ms.filter(|s| *s > 0) {
job = job.before_input(["-ss".to_string(), secs(s)]);
}
if let Some(l) = what.len_ms {
job = job.before_input(["-t".to_string(), secs(l)]);
}
let bound = what.len_ms.unwrap_or(what.max_len_ms).min(what.max_len_ms);
let job = job
.args(["-vn", "-sn", "-dn", "-map", "0:a:0", "-map_metadata", "-1", "-c:a", "pcm_s16le"])
.args(["-ac".to_string(), what.channels.max(1).to_string(), "-ar".to_string(), what.sample_rate.to_string()])
.args(["-f", "wav", "pipe:1"])
.max_output(wav_bytes(what.sample_rate, what.channels.max(1), bound) + 4096);
exec.exec(&job)
}
pub fn normalize_pcm(exec: &dyn Exec, input: &Input, max_len_ms: u64) -> Result<Pcm> {
if looks_like_wav(&input.head(12)?) {
let bytes = input.read_all(wav_bytes(192_000, 8, max_len_ms).saturating_mul(4))?;
let pcm = decode_wav(&bytes)?;
if pcm.duration_ms() > max_len_ms {
return Err(MediaError::limit(format!("the audio is {} ms, over the {max_len_ms} ms limit", pcm.duration_ms())));
}
return Ok(pcm.to_transcribe());
}
let wav = extract(exec, input, &Extract::transcribe(max_len_ms))?;
decode_wav(&wav)
}
pub fn normalize(exec: &dyn Exec, input: &Input, max_len_ms: u64) -> Result<Vec<u8>> {
Ok(encode_wav(&normalize_pcm(exec, input, max_len_ms)?))
}
pub fn encode(exec: &dyn Exec, pcm: &Pcm, format: AudioFormat, max_bytes: u64) -> Result<Vec<u8>> {
let wav = encode_wav(pcm);
let (codec, muxer): (&[&str], &str) = match format {
AudioFormat::Wav => {
if wav.len() as u64 > max_bytes {
return Err(MediaError::limit(format!("the WAV is {} bytes, over the {max_bytes}-byte bound", wav.len())));
}
return Ok(wav);
}
AudioFormat::Mp3 => (&["-c:a", "libmp3lame", "-q:a", "4"], "mp3"),
AudioFormat::Opus => (&["-c:a", "libopus", "-b:a", "48k"], "ogg"),
AudioFormat::Flac => (&["-c:a", "flac"], "flac"),
};
let job = Job::ffmpeg(Input::bytes(wav))
.before_input(["-f", "wav"])
.args(["-vn", "-map_metadata", "-1"])
.args(codec.iter().copied())
.args(["-f", muxer, "pipe:1"])
.max_output(max_bytes);
exec.exec(&job)
}