pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! # ミキサー(mixer・cpal 機能)
//!
//! pikopiko の曲と効果音を、実際のオーディオデバイスで鳴らす。ゲームの BGM(MML の曲)と
//! 効果音(作っておいた音)を、1 つのミキサー・1 本の出力で混ぜるための部品。
//!
//! ```no_run
//! # #[cfg(feature = "cpal")]
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use std::sync::Arc;
//! use std::time::Duration;
//! use pikopiko::player::mixer::{BusId, Clip, ClipOptions, Output, PlayOptions};
//!
//! const MUSIC: BusId = BusId(1);
//! const SFX: BusId = BusId(2);
//!
//! let mut out = Output::open_default()?;
//! let bgm = Arc::new(pikopiko::compile("A t150 o5 l8 * cdefgab>c").expect("MMLの誤り"));
//! let mut player = pikopiko::synth::player(bgm, out.sample_rate());
//! player.handle(pikopiko::Command::SetLooping(true));
//! // BGM は先読みして鳴らす(重い音源でも途切れにくい。操作は先読みの分だけ遅れて効く)
//! let id = out.play_with(player, PlayOptions {
//!     bus: MUSIC,
//!     lookahead: Duration::from_millis(200),
//!     ..Default::default()
//! })?;
//! // 効果音は作っておいた音(クリップ)を、遅れなく混ぜる
//! let coin = Clip::render(&pikopiko::compile("A t240 o6 l32 b>e4").unwrap(), out.sample_rate());
//! out.play_clip(&coin, ClipOptions { bus: SFX, rate: 1.2, pan: -0.5, ..Default::default() })?;
//! // ダッキング:BGM のバスだけを下げる
//! out.set_bus_volume(MUSIC, 0.5, Duration::from_millis(300))?;
//! out.send(id, pikopiko::Command::SetTempoScale(1.2))?;
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "cpal"))]
//! # fn main() {}
//! ```
//!
//! ## 鳴らすもの
//!
//! - **曲**([`MixerHandle::play_with`] など):`Player` をその場で動かして音を作る。テンポ・シーク・
//!   ミュート・マーカーへの移動などの操作(`Command`)が使える。同時に [`MAX_SOUNDS`] 曲まで。
//! - **クリップ**([`MixerHandle::play_clip`]):作っておいたステレオの音([`Clip`])を、音量・再生速度
//!   (音程も変わる)・定位を付けて鳴らす。音を作る処理がなく読んで足すだけなので軽く、効果音向き。
//!   同時に [`MAX_CLIPS`] 本まで。満杯なら、同じバスのいちばん古いクリップを短く消して入れ替える。
//!
//! ## バス
//!
//! 曲もクリップも、鳴らすときにバス([`BusId`]、[`MAX_BUSES`] 本)を 1 本選ぶ。バスごとに音量・一時停止・
//! 停止をフェード付きで操作できる(BGM のダッキング、ポーズでの一時停止など)。バスに名前はなく、
//! 使う側が番号に意味を付ける。既定は [`BusId::MAIN`]。
//!
//! ## 先読み
//!
//! 曲は、オーディオスレッドで音を作る(既定)か、別のスレッド(先読みのスレッド)で少し先まで作って
//! 溜めておくかを、鳴らし始めるときに選べる([`PlayOptions::lookahead`])。先読みすると重い瞬間を
//! 溜めた分で吸収でき、音が途切れにくい。その代わり、曲への操作(`send` で送る `Command`)は溜めた分だけ
//! 遅れて聞こえる。いま溜まっている量(=遅れ)は [`MixerHandle::lookahead`] で読める。音量・フェード・
//! バスの操作は混ぜるときにかけるので遅れない。再生位置([`MixerHandle::position`])と通知は、
//! 先読みしていてもいま聞こえている音に合わせる。クリップは先読みしない。
//!
//! ## 曲の切り替え
//!
//! [`MixerHandle::switch`] で、鳴っている曲から次の曲へクロスフェードで切り替える。今すぐか、
//! 鳴っている曲の次の小節の頭([`SwitchAt::NextBar`])かを選べる。小節の頭の判定はオーディオスレッドで
//! 行うので、呼び出し側のフレームの遅れに左右されない。
//!
//! ## スレッドの約束
//!
//! - `Player`・クリップの音・先読みの溜め場所はこちら(呼び出し側のスレッド)で作り、ロックフリーの
//!   リングバッファでオーディオスレッドへ**移す**。オーディオスレッドではメモリの確保も解放もしない。
//! - 鳴り終わったものは、別のリングバッファでこちらへ戻し、こちらで解放する
//!   ([`MixerHandle::collect_garbage`]。ほかのメソッドも内部で呼ぶ)。先読みする曲の `Player` は
//!   先読みのスレッドが持ち、そこで解放する。
//!
//! オーディオデバイスを使わない部分([`mixer`]、[`Mixer`]、[`MixerHandle`])は、
//! `cpal` 機能を入れなくても(`mixer` 機能だけで)使える。独自のオーディオ出力につなぐときはこちらを使う。
//! `cpal` の出力([`Output`])は、既定の出力デバイスが変わると開き直して鳴らし続ける。
//!
//! ## 出力の EQ
//!
//! 全部の音を混ぜた後に、出力の EQ(`pikopiko::runtime::output`)をかけられる
//! ([`MixerHandle::set_output_eq`])。曲は変えずに、鳴らす機器に合わせて帯域を整える
//! (スマートフォンのスピーカーでは鳴らない低音を削る、実機の出力回路を模すなど)。
//! 既定は何もしない。順番は「曲とクリップをバスごとに混ぜる → バスの音量 → EQ → 全体の音量 → ±1 に収める」。
//!
//! ## 出力のメーターと波形
//!
//! 最後に出した音のピーク([`MixerHandle::take_peak`])と最新の波形([`MixerHandle::scope`])を、
//! ロックなしで読める(エディタのメーター・オシロスコープ用。画面側のスレッドが、曲ごとではなく
//! 実際に出した音を見るための口)。

/// このモジュールの文の表(`locales/` の機能の部分。音源の説明・エラーの文)。機能を入れたときだけ入る。
#[allow(dead_code)]
pub(crate) mod text_table {
    use crate::text::{Catalog, Seg};
    include!(concat!(env!("OUT_DIR"), "/text-mixer.rs"));
}

use std::sync::atomic::{AtomicU32, AtomicU64};
use std::sync::Arc;
use std::time::Duration;

use crate::player::TrackActivity;
use crate::Song;

mod clip;
mod engine;
mod gain;
mod handle;
mod lookahead;
mod tap;

pub use engine::Mixer;
pub use handle::MixerHandle;
use tap::Tap;
pub use tap::{TapRead, SCOPE_LEN, STREAM_LEN};

#[cfg(feature = "cpal")]
mod output;
#[cfg(feature = "cpal")]
pub use output::{buffer_size, Output, OutputError, OutputOptions};

/// 同時に鳴らせる曲の数。
pub const MAX_SOUNDS: usize = 32;
/// 同時に鳴らせるクリップの数。満杯で鳴らすと、同じバスのいちばん古いクリップを短く消して入れ替える。
pub const MAX_CLIPS: usize = 64;
/// バスの数([`BusId`] の 0〜7)。
pub const MAX_BUSES: usize = 8;
/// 先読みの長さの上限。これより長い値は切り詰める。
pub const MAX_LOOKAHEAD: Duration = Duration::from_secs(2);
/// 先読みの長さの最短。これと「出力の遅れの 2 倍」の長いほうより短い値は、そこまで引き上げる。
///
/// 先読みのスレッドは溜まり具合を数 ms ごとに見て補うので、出力が 1 回に持っていく量(出力のバッファ)
/// より十分長く溜めておかないと間に合わず、尽きて曲が遅れる。実機で 10 ms の先読みが尽き続けたことから、
/// 出力のバッファの 2 倍と 50 ms の長いほうを最短にした。
pub const MIN_LOOKAHEAD: Duration = Duration::from_millis(50);
/// 通知のキューの長さ。あふれた通知は捨てる。
pub const NOTICE_QUEUE: usize = 256;

/// コマンドのキューの長さ。
const QUEUE: usize = 256;
/// 先読みのスレッドが 1 回に作るフレーム数。先読みの長さの最小でもある。
const LOOKAHEAD_BLOCK: usize = 512;
/// 入れ替えで消しているクリップを置いておく枠の数。
const FADING_CLIPS: usize = 16;
/// 入れ替えで古いクリップを消す長さ(秒)。プチッという音を防ぐための短いフェード。
const STEAL_FADE_SECS: f64 = 0.002;

/// 鳴らしている曲の番号。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SoundId(u64);

/// 鳴らしているクリップの番号。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ClipId(u64);

/// バスの番号(0〜[`MAX_BUSES`] − 1)。曲とクリップをまとめて音量・一時停止・停止をかける単位。
///
/// 名前は持たず、使う側が番号に意味を付ける(ゲームなら `const MUSIC: BusId = BusId(1);` など)。
/// 範囲外の番号は、鳴らすとき・操作するときに [`MixerError::NoSuchBus`] になる。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BusId(pub u8);

impl BusId {
    /// 既定のバス(0)。バスを選ばずに鳴らしたものはここに入る。
    pub const MAIN: BusId = BusId(0);

    fn index(self) -> Result<usize, MixerError> {
        let i = self.0 as usize;
        if i < MAX_BUSES {
            Ok(i)
        } else {
            Err(MixerError::NoSuchBus)
        }
    }
}

impl Default for BusId {
    fn default() -> Self {
        BusId::MAIN
    }
}

/// 曲を鳴らすときの設定([`MixerHandle::play_with`])。作るときは `..Default::default()` で残りを埋める
/// (フィールドは増えることがある)。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PlayOptions {
    /// 鳴らすバス。既定は [`BusId::MAIN`]。
    pub bus: BusId,
    /// 無音から等倍まで上げる長さ。既定は 0(すぐ等倍)。
    pub fade_in: Duration,
    /// 先読みの長さ。0(既定)ならオーディオスレッドで音を作る。0 より長ければ先読みのスレッドで
    /// 作って溜め、操作はその分だけ遅れて聞こえる。最短は [`MIN_LOOKAHEAD`] と出力の遅れ
    /// ([`MixerHandle::output_latency_frames`])の 2 倍の長いほうで、それより短い値は最短に、
    /// [`MAX_LOOKAHEAD`] より長い値は上限に揃える。先読みするかどうかは鳴らし始めに決まり、
    /// 途中で変えられるのは長さだけ([`MixerHandle::set_lookahead`])。
    pub lookahead: Duration,
}

impl Default for PlayOptions {
    fn default() -> Self {
        PlayOptions {
            bus: BusId::MAIN,
            fade_in: Duration::ZERO,
            lookahead: Duration::ZERO,
        }
    }
}

/// クリップを鳴らすときの設定([`MixerHandle::play_clip`])。作るときは `..Default::default()` で
/// 残りを埋める(フィールドは増えることがある)。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClipOptions {
    /// 音量(1.0 が等倍、0 以上)。
    pub volume: f32,
    /// 再生速度(1.0 が等倍)。音程も一緒に変わる(2.0 で 1 オクターブ上・半分の長さ)。
    /// 0 以下や有限でない値は 1.0 として扱う。
    pub rate: f32,
    /// 定位(-1.0 = 左、0 = 中央、1.0 = 右)。曲の `%pan` と同じバランス方式で、中央は左右とも等倍、
    /// 片側に寄せるともう片側だけが下がる。範囲外は -1〜1 に収める。
    pub pan: f32,
    /// 鳴らすバス。既定は [`BusId::MAIN`]。
    pub bus: BusId,
    /// 終わりまで来たら頭から繰り返すか(止めるまで鳴る)。
    pub looping: bool,
}

impl Default for ClipOptions {
    fn default() -> Self {
        ClipOptions {
            volume: 1.0,
            rate: 1.0,
            pan: 0.0,
            bus: BusId::MAIN,
            looping: false,
        }
    }
}

/// 曲の切り替えで、次の曲を鳴らし始める時点([`SwitchOptions::at`])。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SwitchAt {
    /// すぐ。
    #[default]
    Now,
    /// 鳴っている曲の、次の小節の頭(曲の拍子 `#meter` で数える。曲の頭から同じ拍子として数える)。
    /// その前に鳴っている曲が終わったら、その時点で始める。
    NextBar,
}

/// 曲の切り替えの設定([`MixerHandle::switch`])。作るときは `..Default::default()` で残りを埋める。
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct SwitchOptions {
    /// クロスフェードの長さ(次の曲を上げ、前の曲を下げる長さ)。0 ならすぐ入れ替わる。
    pub fade: Duration,
    /// 次の曲を鳴らし始める時点。
    pub at: SwitchAt,
    /// 次の曲の先読みの長さ([`PlayOptions::lookahead`] と同じ)。先読みするなら、待っている間に溜めておく。
    pub lookahead: Duration,
}

/// 作っておいたステレオの音(効果音など)。[`MixerHandle::play_clip`] で鳴らす。
///
/// 中身は `Arc` で持つので、複製(`clone`)しても音のデータは写さない。同じ音を何度鳴らしても、
/// 鳴らすたびに確保するのは小さな管理用の値だけ。サンプルレートがミキサーと違っても、鳴らすときに
/// 合わせる(線形補間)。
#[derive(Debug, Clone)]
pub struct Clip {
    frames: Arc<[[f32; 2]]>,
    sample_rate: u32,
}

impl Clip {
    /// ステレオの [左, 右] フレームと、そのサンプルレートから作る。
    pub fn new(frames: impl Into<Arc<[[f32; 2]]>>, sample_rate: u32) -> Self {
        Clip {
            frames: frames.into(),
            sample_rate: sample_rate.max(1),
        }
    }

    /// 曲を、曲が選んだ音源(`synth::ALL` から探す)で `sample_rate` で最後まで鳴らした音から作る
    /// (ループ点へは戻らない。曲の終わりの余韻まで含む)。効果音を MML で書いて、起動時に作っておく使い方。
    pub fn render(song: &Song, sample_rate: u32) -> Self {
        Clip::new(crate::synth::render(song, sample_rate, 0), sample_rate)
    }

    /// フレーム数。
    pub fn len(&self) -> usize {
        self.frames.len()
    }

    /// 音がないか。
    pub fn is_empty(&self) -> bool {
        self.frames.is_empty()
    }

    /// サンプルレート。
    pub fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    /// 等倍で鳴らしたときの長さ。
    pub fn duration(&self) -> Duration {
        Duration::from_secs_f64(self.frames.len() as f64 / self.sample_rate as f64)
    }

    /// 音のフレーム。
    pub fn frames(&self) -> &[[f32; 2]] {
        &self.frames
    }
}

/// ミキサーへの操作が失敗した理由。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MixerError {
    /// コマンドのキューがいっぱい(オーディオスレッドが止まっている可能性がある)。
    QueueFull,
    /// 同時に鳴らせる曲の数([`MAX_SOUNDS`])を超えた。
    TooManySounds,
    /// その番号の曲はもう鳴っていない。
    NotPlaying,
    /// 出力の EQ の設定を、ミキサーと違うサンプルレートで作った(係数がずれて別の帯域にかかる)。
    SampleRateMismatch,
    /// バスの番号が範囲外([`MAX_BUSES`] 以上)。
    NoSuchBus,
    /// 先読みせずに鳴らしている曲の先読みの長さを変えようとした(先読みするかは鳴らし始めに決まる)。
    NotLookahead,
}

impl crate::text::Localized for MixerError {
    fn text_key(&self) -> &'static str {
        match self {
            MixerError::QueueFull => "err-mixer-queue-full",
            MixerError::TooManySounds => "err-mixer-too-many-sounds",
            MixerError::NotPlaying => "err-mixer-not-playing",
            MixerError::SampleRateMismatch => "err-mixer-sample-rate-mismatch",
            MixerError::NoSuchBus => "err-mixer-no-such-bus",
            MixerError::NotLookahead => "err-mixer-not-lookahead",
        }
    }

    fn catalogs(&self) -> &'static [crate::text::Catalog] {
        crate::player::mixer::text_table::CATALOGS
    }
}

impl core::fmt::Display for MixerError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        crate::text::write_localized(f, self, crate::text::DEFAULT_LANG)
    }
}

impl std::error::Error for MixerError {}

/// オーディオスレッドが公開する再生位置(エディタの再生カーソルなどに使う)。
/// 枠ごとに「曲の番号」と「いまの tick」を持つ。読み書きは待たず、確保もしない。
struct Playheads {
    ids: Vec<AtomicU64>,
    ticks: Vec<AtomicU64>,
    /// 枠ごとのトラックの数。
    track_counts: Vec<AtomicU32>,
    /// 枠ごと・トラックごとの発音の状態([`pack_activity`] で 1 つの数に詰めたもの)。
    tracks: Vec<AtomicU64>,
    /// 枠ごと・トラックごとの発音の状態の続き([`pack_activity_ext`])。
    tracks_ext: Vec<AtomicU64>,
    /// 出力デバイスが音を出すまでの遅れ(フレーム数)。出力の側が知らせる([`Mixer::report_output_latency`])。
    latency: AtomicU32,
}

/// 曲 1 つあたりの、発音の状態を公開するトラックの数の上限(ミュートの印と同じ 32)。
pub const MAX_TRACK_ACTIVITY: usize = 32;

/// 発音の状態を 1 つの数に詰める(下位 32 ビットが回数、続いて音の高さ 8・音量 4・鳴っている 1)。
fn pack_activity(a: TrackActivity) -> u64 {
    a.note_ons as u64
        | (a.key as u64) << 32
        | ((a.volume & 0x0f) as u64) << 40
        | (a.sounding as u64) << 44
}

/// 発音の状態の続きを詰める(下位 32 ビットが音を離した回数、続いて和音の構成音の集合 16・和音の音の数 8)。
fn pack_activity_ext(a: TrackActivity) -> u64 {
    a.note_offs as u64 | (a.chord_pcs as u64) << 32 | (a.chord_len as u64) << 48
}

fn unpack_activity(v: u64, ext: u64) -> TrackActivity {
    TrackActivity {
        sounding: v >> 44 & 1 == 1,
        key: (v >> 32) as u8,
        volume: (v >> 40) as u8 & 0x0f,
        note_ons: v as u32,
        chord_len: (ext >> 48) as u8,
        chord_pcs: (ext >> 32) as u16,
        note_offs: ext as u32,
    }
}

/// ミキサーを作る。`sample_rate` は出力のサンプルレート。
/// [`Mixer`] をオーディオスレッドへ渡し、[`MixerHandle`] をこちらで持つ。
pub fn mixer(sample_rate: u32) -> (MixerHandle, Mixer) {
    let (tx, rx) = rtrb::RingBuffer::new(QUEUE);
    let (gtx, grx) = rtrb::RingBuffer::new(engine::GARBAGE_QUEUE);
    let (ntx, nrx) = rtrb::RingBuffer::new(NOTICE_QUEUE);
    let heads = Arc::new(Playheads {
        ids: (0..MAX_SOUNDS).map(|_| AtomicU64::new(0)).collect(),
        ticks: (0..MAX_SOUNDS).map(|_| AtomicU64::new(0)).collect(),
        track_counts: (0..MAX_SOUNDS).map(|_| AtomicU32::new(0)).collect(),
        tracks: (0..MAX_SOUNDS * MAX_TRACK_ACTIVITY)
            .map(|_| AtomicU64::new(0))
            .collect(),
        tracks_ext: (0..MAX_SOUNDS * MAX_TRACK_ACTIVITY)
            .map(|_| AtomicU64::new(0))
            .collect(),
        latency: AtomicU32::new(0),
    });
    let tap = Arc::new(Tap::new());
    let handle = MixerHandle::new(tx, grx, nrx, heads.clone(), tap.clone(), sample_rate);
    let mixer = Mixer::new(rx, gtx, ntx, heads, tap, sample_rate);
    (handle, mixer)
}