pub const MP3_KBPS: u16 = 192;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AudioFormat {
Wav,
Mp3,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EncodeError {
Mp3Unavailable,
Mp3Failed,
}
impl AudioFormat {
pub fn from_name(name: &str) -> Option<Self> {
match name.to_ascii_lowercase().as_str() {
"wav" => Some(Self::Wav),
"mp3" => Some(Self::Mp3),
_ => None,
}
}
pub fn from_path(path: &str) -> Self {
let ext = std::path::Path::new(path)
.extension()
.and_then(|e| e.to_str())
.unwrap_or("");
if ext.eq_ignore_ascii_case("mp3") {
Self::Mp3
} else {
Self::Wav
}
}
pub fn extension(self) -> &'static str {
match self {
Self::Wav => "wav",
Self::Mp3 => "mp3",
}
}
pub fn mime(self) -> &'static str {
match self {
Self::Wav => "audio/wav",
Self::Mp3 => "audio/mpeg",
}
}
}
pub fn encode(
samples: &[[f32; 2]],
sample_rate: u32,
format: AudioFormat,
) -> Result<Vec<u8>, EncodeError> {
match format {
AudioFormat::Wav => Ok(pikopiko::export::wav::encode_pcm16(samples, sample_rate)),
AudioFormat::Mp3 => encode_mp3(samples, sample_rate),
}
}
#[cfg(feature = "mp3")]
fn encode_mp3(samples: &[[f32; 2]], sample_rate: u32) -> Result<Vec<u8>, EncodeError> {
use audio2mp3_core::{Bitrate, EncoderConfig, Mp3Encoder};
let fail = |_| EncodeError::Mp3Failed;
let bitrate = Bitrate::from_kbps(MP3_KBPS).map_err(fail)?;
let mut enc = Mp3Encoder::new(EncoderConfig {
sample_rate,
channels: 2,
bitrate,
})
.map_err(fail)?;
enc.enable_info_frame().map_err(fail)?;
let pcm: Vec<i16> = samples
.iter()
.flatten()
.map(|&s| (s.clamp(-1.0, 1.0) * i16::MAX as f32).round() as i16)
.collect();
let mut out = Vec::new();
enc.encode(&pcm, &mut out).map_err(fail)?;
enc.flush(&mut out).map_err(fail)?;
let n = enc.info_frame_size();
if n > 0 && out.len() >= n {
enc.info_frame_into(&mut out[..n]).map_err(fail)?;
}
Ok(out)
}
#[cfg(not(feature = "mp3"))]
fn encode_mp3(_: &[[f32; 2]], _: u32) -> Result<Vec<u8>, EncodeError> {
Err(EncodeError::Mp3Unavailable)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_from_names_and_paths() {
assert_eq!(AudioFormat::from_name("MP3"), Some(AudioFormat::Mp3));
assert_eq!(AudioFormat::from_name("wav"), Some(AudioFormat::Wav));
assert_eq!(AudioFormat::from_name("ogg"), None);
assert_eq!(AudioFormat::from_path("a/b.Mp3"), AudioFormat::Mp3);
assert_eq!(AudioFormat::from_path("a.wav"), AudioFormat::Wav);
assert_eq!(AudioFormat::from_path("noext"), AudioFormat::Wav);
}
#[test]
fn wav_is_the_same_as_the_core() {
let s = [[0.5, -0.5]; 100];
assert_eq!(
encode(&s, 44_100, AudioFormat::Wav).unwrap(),
pikopiko::export::wav::encode_pcm16(&s, 44_100)
);
}
#[cfg(feature = "mp3")]
#[test]
fn mp3_has_frames_and_an_info_frame() {
let s: Vec<[f32; 2]> = (0..44_100)
.map(|i| {
let v = (i as f32 * 440.0 / 44_100.0 * std::f32::consts::TAU).sin() * 0.5;
[v, v]
})
.collect();
let b = encode(&s, 44_100, AudioFormat::Mp3).unwrap();
assert_eq!(b[0], 0xFF);
assert_eq!(b[1] & 0xE0, 0xE0);
assert!(b.windows(4).any(|w| w == b"Info"), "Info フレームがない");
assert!((24_000..30_000).contains(&b.len()), "{}", b.len());
assert_eq!(
encode(&s, 22_050, AudioFormat::Mp3),
Err(EncodeError::Mp3Failed)
);
}
#[cfg(not(feature = "mp3"))]
#[test]
fn mp3_needs_the_feature() {
assert_eq!(
encode(&[[0.0; 2]], 44_100, AudioFormat::Mp3),
Err(EncodeError::Mp3Unavailable)
);
}
}