Skip to main content

pikopiko_cli/
audio_file.rs

1//! 試聴の音を書き出すファイルの形式(WAV・MP3)。
2//!
3//! **何のためか**:音色を測る `tone`(`-o`)と MCP の `measure_tone` は、測るために鳴らした音を
4//! 人が聴いて確かめる用のファイルにする。WAV は外部のクレートなしで書けるが、スマホの再生アプリ
5//! などで読めないことがあり、MP3 にすると聴ける。そこで MP3 も選べるようにする。
6//!
7//! 約束:
8//!
9//! - WAV は本体の `pikopiko::export::wav::encode_pcm16`(16bit PCM ステレオ)と同じバイト列。
10//! - MP3 は `mp3` 機能(既定で入る)の `audio2mp3-core`(Rust だけで書かれたエンコーダ。C の
11//!   ライブラリを組み立てない)で、ステレオの固定ビットレート [`MP3_KBPS`]。先頭に長さと
12//!   エンコーダの遅れを書いた Info フレーム(Xing と LAME の拡張)を置き、対応する再生側では
13//!   前後の無音を足さずに鳴る。サンプルレートは MPEG-1 の 32000・44100・48000 Hz だけ
14//!   (試聴は 44100 Hz で鳴らす)。
15//! - 曲の書き出し(`render`・`render_mml`)は WAV のまま。ここは聴いて確かめる用の短い音だけの口。
16//! - 誤りの文は使う側(CLI・MCP)の文言で出す(外のライブラリの文はそのまま出さない)。
17
18/// MP3 のビットレート(kbps)。試聴の数秒の音なので、聴き比べで差が出にくい高めの値にする。
19pub const MP3_KBPS: u16 = 192;
20
21/// 書き出す音のファイルの形式。
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum AudioFormat {
24    /// 16bit PCM ステレオの WAV。
25    Wav,
26    /// ステレオ・固定ビットレートの MP3(`mp3` 機能)。
27    Mp3,
28}
29
30/// 音をファイルの形にできなかった理由。
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum EncodeError {
33    /// `mp3` 機能を外して組み立てたので MP3 を書けない。
34    Mp3Unavailable,
35    /// MP3 のエンコーダが受け付けなかった(MPEG-1 にないサンプルレートなど)。
36    Mp3Failed,
37}
38
39impl AudioFormat {
40    /// 名前(`wav`・`mp3`。大文字小文字は区別しない)から形式を決める。知らない名前は `None`。
41    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    /// 書き出す先の名前の拡張子から形式を決める(`.mp3` なら MP3、ほかは WAV)。
50    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    /// ファイル名の拡張子(`wav`・`mp3`)。
63    pub fn extension(self) -> &'static str {
64        match self {
65            Self::Wav => "wav",
66            Self::Mp3 => "mp3",
67        }
68    }
69
70    /// MIME の型(MCP の音の中身を埋めるとき用)。
71    pub fn mime(self) -> &'static str {
72        match self {
73            Self::Wav => "audio/wav",
74            Self::Mp3 => "audio/mpeg",
75        }
76    }
77}
78
79/// ステレオのサンプル(-1.0〜1.0)を形式 `format` のファイルのバイト列にする。
80pub 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    // WAV と同じ丸め方で 16bit にする(左右を交互に並べる)
104    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    // 先頭の仮の Info フレームを、長さと遅れの決まった本物に書き換える
113    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        // MPEG-1 Layer III のフレームの同期(11 ビットの 1)と、Info フレームの印
159        assert_eq!(b[0], 0xFF);
160        assert_eq!(b[1] & 0xE0, 0xE0);
161        assert!(b.windows(4).any(|w| w == b"Info"), "Info フレームがない");
162        // 192kbps で 1 秒ほど(フレームの区切りと遅れの分だけ長い)
163        assert!((24_000..30_000).contains(&b.len()), "{}", b.len());
164        // MPEG-1 にないサンプルレートは誤り
165        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}