pikopiko_cli/
audio_file.rs1pub const MP3_KBPS: u16 = 192;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum AudioFormat {
24 Wav,
26 Mp3,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum EncodeError {
33 Mp3Unavailable,
35 Mp3Failed,
37}
38
39impl AudioFormat {
40 pub fn from_name(name: &str) -> Option<Self> {
42 match name.to_ascii_lowercase().as_str() {
43 "wav" => Some(Self::Wav),
44 "mp3" => Some(Self::Mp3),
45 _ => None,
46 }
47 }
48
49 pub fn from_path(path: &str) -> Self {
51 let ext = std::path::Path::new(path)
52 .extension()
53 .and_then(|e| e.to_str())
54 .unwrap_or("");
55 if ext.eq_ignore_ascii_case("mp3") {
56 Self::Mp3
57 } else {
58 Self::Wav
59 }
60 }
61
62 pub fn extension(self) -> &'static str {
64 match self {
65 Self::Wav => "wav",
66 Self::Mp3 => "mp3",
67 }
68 }
69
70 pub fn mime(self) -> &'static str {
72 match self {
73 Self::Wav => "audio/wav",
74 Self::Mp3 => "audio/mpeg",
75 }
76 }
77}
78
79pub fn encode(
81 samples: &[[f32; 2]],
82 sample_rate: u32,
83 format: AudioFormat,
84) -> Result<Vec<u8>, EncodeError> {
85 match format {
86 AudioFormat::Wav => Ok(pikopiko::export::wav::encode_pcm16(samples, sample_rate)),
87 AudioFormat::Mp3 => encode_mp3(samples, sample_rate),
88 }
89}
90
91#[cfg(feature = "mp3")]
92fn encode_mp3(samples: &[[f32; 2]], sample_rate: u32) -> Result<Vec<u8>, EncodeError> {
93 use audio2mp3_core::{Bitrate, EncoderConfig, Mp3Encoder};
94 let fail = |_| EncodeError::Mp3Failed;
95 let bitrate = Bitrate::from_kbps(MP3_KBPS).map_err(fail)?;
96 let mut enc = Mp3Encoder::new(EncoderConfig {
97 sample_rate,
98 channels: 2,
99 bitrate,
100 })
101 .map_err(fail)?;
102 enc.enable_info_frame().map_err(fail)?;
103 let pcm: Vec<i16> = samples
105 .iter()
106 .flatten()
107 .map(|&s| (s.clamp(-1.0, 1.0) * i16::MAX as f32).round() as i16)
108 .collect();
109 let mut out = Vec::new();
110 enc.encode(&pcm, &mut out).map_err(fail)?;
111 enc.flush(&mut out).map_err(fail)?;
112 let n = enc.info_frame_size();
114 if n > 0 && out.len() >= n {
115 enc.info_frame_into(&mut out[..n]).map_err(fail)?;
116 }
117 Ok(out)
118}
119
120#[cfg(not(feature = "mp3"))]
121fn encode_mp3(_: &[[f32; 2]], _: u32) -> Result<Vec<u8>, EncodeError> {
122 Err(EncodeError::Mp3Unavailable)
123}
124
125#[cfg(test)]
126mod tests {
127 use super::*;
128
129 #[test]
130 fn formats_from_names_and_paths() {
131 assert_eq!(AudioFormat::from_name("MP3"), Some(AudioFormat::Mp3));
132 assert_eq!(AudioFormat::from_name("wav"), Some(AudioFormat::Wav));
133 assert_eq!(AudioFormat::from_name("ogg"), None);
134 assert_eq!(AudioFormat::from_path("a/b.Mp3"), AudioFormat::Mp3);
135 assert_eq!(AudioFormat::from_path("a.wav"), AudioFormat::Wav);
136 assert_eq!(AudioFormat::from_path("noext"), AudioFormat::Wav);
137 }
138
139 #[test]
140 fn wav_is_the_same_as_the_core() {
141 let s = [[0.5, -0.5]; 100];
142 assert_eq!(
143 encode(&s, 44_100, AudioFormat::Wav).unwrap(),
144 pikopiko::export::wav::encode_pcm16(&s, 44_100)
145 );
146 }
147
148 #[cfg(feature = "mp3")]
149 #[test]
150 fn mp3_has_frames_and_an_info_frame() {
151 let s: Vec<[f32; 2]> = (0..44_100)
152 .map(|i| {
153 let v = (i as f32 * 440.0 / 44_100.0 * std::f32::consts::TAU).sin() * 0.5;
154 [v, v]
155 })
156 .collect();
157 let b = encode(&s, 44_100, AudioFormat::Mp3).unwrap();
158 assert_eq!(b[0], 0xFF);
160 assert_eq!(b[1] & 0xE0, 0xE0);
161 assert!(b.windows(4).any(|w| w == b"Info"), "Info フレームがない");
162 assert!((24_000..30_000).contains(&b.len()), "{}", b.len());
164 assert_eq!(
166 encode(&s, 22_050, AudioFormat::Mp3),
167 Err(EncodeError::Mp3Failed)
168 );
169 }
170
171 #[cfg(not(feature = "mp3"))]
172 #[test]
173 fn mp3_needs_the_feature() {
174 assert_eq!(
175 encode(&[[0.0; 2]], 44_100, AudioFormat::Mp3),
176 Err(EncodeError::Mp3Unavailable)
177 );
178 }
179}