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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! 音を作る処理:`Player::render`(オーディオスレッドから呼ぶ入口)、イベントを時刻どおりに音源へ送る
//! `process_events`、フレームごとの音量エンベロープと音程エフェクトの更新、効果音とショットの混ぜ合わせ。
//!
//! ここはメモリの確保・ロック・入出力・パニックをしない(`tests/realtime.rs` が見張る)。曲全体を
//! まとめて書き出す `render_to_vec` などは `mod.rs` にあり、内側で `render_inner` を使う。

use super::*;

pub(super) fn vibrato_of(song: &Song, idx: Option<u8>) -> Option<pikopiko_runtime::pitch::Vibrato> {
    idx.and_then(|i| song.vibratos.get(i as usize))
        .map(|v| v.view())
}

pub(super) fn detune_of(
    song: &Song,
    idx: Option<u8>,
) -> Option<pikopiko_runtime::pitch::Detune<'_>> {
    idx.and_then(|i| song.detunes.get(i as usize))
        .map(|d| d.view())
}

pub(super) fn envelope_of(
    song: &Song,
    idx: Option<u8>,
) -> Option<pikopiko_runtime::envelope::Envelope<'_>> {
    idx.and_then(|i| song.envelopes.get(i as usize))
        .map(|e| e.view())
}

/// 音色のエンベロープ(`@duty`)。形は音量エンベロープと同じで、値は音色の番号。
pub(super) fn duty_of(
    song: &Song,
    idx: Option<u8>,
) -> Option<pikopiko_runtime::envelope::Envelope<'_>> {
    idx.and_then(|i| song.duties.get(i as usize))
        .map(|e| e.view())
}

/// アルペジオ(段はセント = 半音 × 100 で、デチューンと同じ形)。
pub(super) fn arp_of(song: &Song, idx: Option<u8>) -> Option<pikopiko_runtime::pitch::Detune<'_>> {
    idx.and_then(|i| song.arps.get(i as usize))
        .map(|d| d.view())
}

/// 選んでいる表の番号(ビブラート, デチューン, アルペジオ)から、音程エフェクトの組を引く。
pub(super) fn pitch_fx_of(
    song: &Song,
    vib: Option<u8>,
    detune: Option<u8>,
    arp: Option<u8>,
) -> pikopiko_runtime::pitch::PitchFx<'_> {
    pikopiko_runtime::pitch::PitchFx {
        vib: vibrato_of(song, vib),
        detune: detune_of(song, detune),
        arp: arp_of(song, arp),
    }
}

pub(super) fn render_inner(
    song: &Song,
    sample_rate: u32,
    synth: Box<dyn Synth>,
    loops: u32,
) -> Vec<[f32; 2]> {
    let mut p = Player::with_synth(Arc::new(song.clone()), sample_rate, synth);
    if loops > 0 {
        p.handle(Command::SetLooping(true));
        p.handle(Command::SetLoopLimit(Some(loops)));
    }
    let mut out = Vec::new();
    let mut buf = [[0.0f32; 2]; 1024];
    while !p.is_finished() {
        let n = p.render_counted(&mut buf);
        out.extend_from_slice(&buf[..n]);
    }
    out
}

impl Player {
    /// `out` を埋める。リアルタイム安全(メモリ確保、ロック、I/O、パニックをしない)。
    pub fn render(&mut self, out: &mut [[f32; 2]]) {
        self.render_counted(out);
    }

    /// `out` を埋め、曲(と余韻・効果音)が終わる前に書いたフレーム数を返す。残りは無音で埋まる。
    /// 事前レンダリングで、曲の終わりのちょうどの長さを知りたいときに使う。リアルタイム安全。
    pub fn render_counted(&mut self, out: &mut [[f32; 2]]) -> usize {
        if self.sfx.is_empty() {
            let mut none: [Option<(usize, SfxSeq<'_>)>; MAX_SFX] = [None, None, None, None];
            return self.render_frames(out, &mut none);
        }
        // 効果音のシーケンサーに、このブロックの間だけ曲データを付ける(確保しない)
        let sfx = std::mem::take(&mut self.sfx);
        let mut seqs = std::mem::take(&mut self.sfx_seqs);
        let mut bound: [Option<(usize, SfxSeq<'_>)>; MAX_SFX] = [None, None, None, None];
        for (slot, playing) in self.sfx_playing.iter().enumerate() {
            if let Some(e) = *playing {
                let e = e as usize;
                bound[slot] = seqs[e]
                    .take()
                    .and_then(|s| s.bind(&sfx[e].data))
                    .map(|s| (e, s));
            }
        }
        let produced = self.render_frames(out, &mut bound);
        for (e, seq) in bound.into_iter().flatten() {
            seqs[e] = Some(seq.unbind());
        }
        self.sfx = sfx;
        self.sfx_seqs = seqs;
        produced
    }

    /// `out` を埋める。最初の描画の前に、音源の遅れ(`Synth::latency_frames`)の分だけ先に進めて
    /// 出力を捨てる。音源が作った音は遅れて出てくるので、その分を捨てると、音は曲の時刻どおりに
    /// 聞こえる(遅れた分は曲の終わりの余韻に回る)。先に進めるのは曲を始めたときの 1 回だけで、
    /// 途中の巻き戻し・移動のあとには、音源をリセットした分の短い無音が残る(捨てる音がないため)。
    pub(super) fn render_frames(
        &mut self,
        out: &mut [[f32; 2]],
        sfx: &mut [Option<(usize, SfxSeq<'_>)>; MAX_SFX],
    ) -> usize {
        if self.preroll > 0 && matches!(self.state, State::Playing) {
            let mut scratch = [[0.0f32; 2]; 256];
            while self.preroll > 0 {
                let n = (self.preroll as usize).min(scratch.len());
                self.render_frames_inner(&mut scratch[..n], sfx);
                self.preroll -= n as u32;
            }
        }
        self.render_frames_inner(out, sfx)
    }

    fn render_frames_inner(
        &mut self,
        out: &mut [[f32; 2]],
        sfx: &mut [Option<(usize, SfxSeq<'_>)>; MAX_SFX],
    ) -> usize {
        let mut produced = 0;
        // テンポは 1/1000 BPM なので、分母も 1000 倍する(整数の比のまま、誤差なし)
        let denom = 60 * self.sample_rate as u64 * SCALE_ONE * 1000;
        for frame in out.iter_mut() {
            match self.state {
                State::Paused => {
                    *frame = [0.0, 0.0];
                    continue;
                }
                State::Finished => {
                    // BGM は終わっても、効果音とショットは鳴らす
                    if self.sfx_active() || self.shots_active() {
                        self.step_sfx(sfx);
                        *frame = self.mix();
                        produced += 1;
                    } else {
                        *frame = [0.0, 0.0];
                    }
                    continue;
                }
                State::Tail => {
                    self.step_sfx(sfx);
                    *frame = self.mix();
                    produced += 1;
                    self.tail_left = self.tail_left.saturating_sub(1);
                    if self.tail_left == 0 {
                        self.state = State::Finished;
                    }
                    continue;
                }
                State::Playing => {}
            }
            if let Some((m, JumpAt::Beat | JumpAt::Bar, due)) = self.pending_jump {
                if self.tick >= due {
                    self.jump(m);
                }
            }
            self.process_events();
            self.pass_points();
            if self.tick >= self.end_tick() {
                let may_loop = self.looping && self.loop_limit.is_none_or(|n| self.loops_done < n);
                if let Some((m, _, _)) = self.pending_jump {
                    // 待っている移動は、曲の終わりで(ループや終わりの代わりに)
                    self.jump(m);
                    self.state = State::Playing;
                    self.process_events();
                    self.pass_points();
                } else if may_loop {
                    self.loops_done = self.loops_done.saturating_add(1);
                    let to = self.song.loop_tick.unwrap_or(self.range_start);
                    self.seek(to);
                    self.state = State::Playing;
                    self.notices.push(Notice::Looped(self.loops_done));
                    self.process_events();
                    self.pass_points();
                } else {
                    for ch in 0..self.synth.channels() {
                        self.synth.note_off(ch);
                    }
                    self.env.fill(EnvChannel::with_frame_hz(self.song.frame_hz));
                    self.duty
                        .fill(DutyChannel::with_frame_hz(self.song.frame_hz));
                    self.pitch
                        .fill(PitchChannel::with_frame_hz(self.song.frame_hz));
                    self.sounding.fill(None);
                    self.rebuild_sounding();
                    self.notices.push(Notice::Finished);
                    self.tail_left = self.synth.tail_frames();
                    if self.tail_left == 0 {
                        self.state = State::Finished;
                        if self.sfx_active() || self.shots_active() {
                            self.step_sfx(sfx);
                            *frame = self.mix();
                            produced += 1;
                        } else {
                            *frame = [0.0, 0.0];
                        }
                        continue;
                    }
                    // 余韻を鳴らす(このフレームから)
                    self.state = State::Tail;
                    self.step_sfx(sfx);
                    *frame = self.mix();
                    produced += 1;
                    self.tail_left -= 1;
                    if self.tail_left == 0 {
                        self.state = State::Finished;
                    }
                    continue;
                }
            }
            self.tick_envelopes();
            self.tick_duty();
            self.tick_pitch();
            self.step_sfx(sfx);
            *frame = self.mix();
            produced += 1;

            self.acc += self.tempo as u64 * self.song.ppq as u64 * self.tempo_scale;
            if self.acc >= denom {
                self.tick += self.acc / denom;
                self.acc %= denom;
            }
        }
        produced
    }

    /// 音源から 1 サンプルを作る(BGM のミュート・ソロと全体の音量を効かせる)。
    pub(super) fn mix(&mut self) -> [f32; 2] {
        let audible = self.audible_mask();
        // ショットは音源の仕上げ(リミッターなど)の前に入れてもらう。音源が受け取らなければ後で足す
        let mut shots = None;
        if !self.shot_pcm.is_empty() {
            let frame = self.mix_shots(audible);
            if !self.synth.mix_input(frame) {
                shots = Some(frame);
            }
        }
        let [mut l, mut r] = self.synth.next(audible);
        if let Some([sl, sr]) = shots {
            l += sl;
            r += sr;
        }
        [
            (l * self.volume).clamp(-1.0, 1.0),
            (r * self.volume).clamp(-1.0, 1.0),
        ]
    }

    /// 音量エンベロープを1サンプル進める。
    pub(super) fn tick_envelopes(&mut self) {
        let sr = self.sample_rate;
        let song = &self.song;
        let synth = &mut self.synth;
        for (ti, ec) in self.env.iter_mut().enumerate() {
            if ec.is_running() {
                let env = envelope_of(song, self.env_current[ti]);
                ec.tick(synth, ti, env, sr);
            }
        }
    }

    /// 音色エンベロープを1サンプル進める。
    pub(super) fn tick_duty(&mut self) {
        let sr = self.sample_rate;
        let song = &self.song;
        let synth = &mut self.synth;
        for (ti, dc) in self.duty.iter_mut().enumerate() {
            if dc.is_running() {
                dc.tick(synth, ti, duty_of(song, self.duty_current[ti]), sr);
            }
        }
    }

    /// 音程エフェクトを1サンプル進める。
    pub(super) fn tick_pitch(&mut self) {
        let sr = self.sample_rate;
        let song = &self.song;
        let synth = &mut self.synth;
        for (ti, pc) in self.pitch.iter_mut().enumerate() {
            // ビブラートの表を選んでいなければ `fx.vib` は常に `None`(`vibrato_of`)。
            // 何も動いていないチャンネルは、毎サンプル `fx` を組み立てずにここで飛ばす
            if self.vib_current[ti].is_none() && !pc.is_running() {
                continue;
            }
            let sounding = self.env[ti].is_held() || self.env[ti].is_releasing();
            let fx = pitch_fx_of(
                song,
                self.vib_current[ti],
                self.detune_current[ti],
                self.arp_current[ti],
            );
            // ビブラートがなく、デチューン・アルペジオも止まっているチャンネルは何もしない
            if fx.vib.is_some() || pc.is_running() {
                pc.tick(synth, ti, sounding, fx, sr);
            }
        }
    }

    /// 再生中の移調をかけた音の高さ。音域の外へ折り返したら(移調ごとに 1 回)通知する。
    fn shift_key(&mut self, ti: usize, key: u8) -> u8 {
        let (k, wrapped) = pikopiko_runtime::transpose_key(&self.synth, ti, key, self.transpose);
        if wrapped && !self.fold_reported {
            self.fold_reported = true;
            self.notices.push(Notice::Transposed { track: ti as u8 });
        }
        k
    }

    pub(super) fn process_events(&mut self) {
        let mut changed = false;
        while let Some(e) = self.song.events.get(self.next_event) {
            if e.tick > self.tick {
                break;
            }
            let e = *e;
            self.next_event += 1;
            let ti = e.track as usize;
            match e.kind {
                EventKind::NoteOn { key, vel } => {
                    let key = self.shift_key(ti, key);
                    if let Some(ec) = self.env.get_mut(ti) {
                        // 音を離していれば新しい音なので、選んでいるエンベロープに切り替える
                        let retrigger = !ec.is_held();
                        if retrigger {
                            self.env_current[ti] = self.env_selected[ti];
                            self.vib_current[ti] = self.vib_selected[ti];
                            self.detune_current[ti] = self.detune_selected[ti];
                            self.arp_current[ti] = self.arp_selected[ti];
                            self.duty_current[ti] = self.duty_selected[ti];
                        }
                        if retrigger {
                            // 音色のエンベロープも、音源の note_on より前に最初の段の音色にする
                            let d = duty_of(&self.song, self.duty_current[ti]);
                            self.duty[ti].note_on(&mut self.synth, ti, d);
                        }
                        // 音程のずれは、音源の note_on より前に渡す
                        self.pitch[ti].note_on(
                            &mut self.synth,
                            ti,
                            retrigger,
                            pitch_fx_of(
                                &self.song,
                                self.vib_current[ti],
                                self.detune_current[ti],
                                self.arp_current[ti],
                            ),
                        );
                        let env = envelope_of(&self.song, self.env_current[ti]);
                        ec.note_on(&mut self.synth, ti, key, vel, env);
                    }
                    self.record_note_on(ti, &[key]);
                    if let Some(s) = self.sounding.get_mut(ti) {
                        *s = Some(e.span);
                        changed = true;
                    }
                }
                EventKind::Chord { keys, vel, legato } => {
                    let mut shifted = [0u8; crate::compiler::song::MAX_CHORD_NOTES];
                    let src = keys.as_slice();
                    let count = src.len();
                    for (d, &k) in shifted.iter_mut().zip(src) {
                        *d = self.shift_key(ti, k);
                    }
                    if let Some(ec) = self.env.get_mut(ti) {
                        // 和音はいつも新しい音として、選んでいるエンベロープと音程エフェクトで始める
                        self.env_current[ti] = self.env_selected[ti];
                        self.vib_current[ti] = self.vib_selected[ti];
                        self.detune_current[ti] = self.detune_selected[ti];
                        self.arp_current[ti] = self.arp_selected[ti];
                        self.duty_current[ti] = self.duty_selected[ti];
                        let d = duty_of(&self.song, self.duty_current[ti]);
                        self.duty[ti].note_on(&mut self.synth, ti, d);
                        self.pitch[ti].note_on(
                            &mut self.synth,
                            ti,
                            true,
                            pitch_fx_of(
                                &self.song,
                                self.vib_current[ti],
                                self.detune_current[ti],
                                self.arp_current[ti],
                            ),
                        );
                        let env = envelope_of(&self.song, self.env_current[ti]);
                        ec.chord_on(&mut self.synth, ti, &shifted[..count], vel, legato, env);
                    }
                    self.record_note_on(ti, &shifted[..count]);
                    if let Some(s) = self.sounding.get_mut(ti) {
                        *s = Some(e.span);
                        changed = true;
                    }
                }
                EventKind::NoteOff => {
                    self.record_note_off(ti);
                    if let Some(ec) = self.env.get_mut(ti) {
                        self.pitch[ti].note_off(pitch_fx_of(
                            &self.song,
                            self.vib_current[ti],
                            self.detune_current[ti],
                            self.arp_current[ti],
                        ));
                        let env = envelope_of(&self.song, self.env_current[ti]);
                        ec.note_off(&mut self.synth, ti, env);
                        let d = duty_of(&self.song, self.duty_current[ti]);
                        self.duty[ti].note_off(&mut self.synth, ti, d);
                    }
                    if let Some(s) = self.sounding.get_mut(ti) {
                        *s = None;
                        changed = true;
                    }
                }
                EventKind::Tempo(t) => {
                    self.tempo = t;
                    self.send_tempo();
                }
                EventKind::Tone(t) => {
                    self.synth.set_tone(ti, t);
                    if let Some(s) = self.tone_set.get_mut(ti) {
                        *s = t;
                    }
                }
                EventKind::Wave(i) => {
                    if let Some(w) = self.song.waves.get(i as usize) {
                        self.synth.set_wave(ti, w);
                    }
                }
                EventKind::Param { id, value } => {
                    pikopiko_runtime::set_param_id(&mut self.synth, ti, id, value)
                }
                EventKind::Envelope(i) => {
                    if let Some(s) = self.env_selected.get_mut(ti) {
                        *s = Some(i);
                    }
                }
                EventKind::Vibrato(i) => {
                    if let Some(s) = self.vib_selected.get_mut(ti) {
                        *s = i;
                    }
                }
                EventKind::Detune(i) => {
                    if let Some(s) = self.detune_selected.get_mut(ti) {
                        *s = i;
                    }
                }
                EventKind::Arp(i) => {
                    if let Some(s) = self.arp_selected.get_mut(ti) {
                        *s = i;
                    }
                }
                EventKind::Duty(i) => {
                    if let Some(s) = self.duty_selected.get_mut(ti) {
                        *s = i;
                    }
                    if i.is_none() {
                        // 解除:動かしていた音色を止め、最後に書いた音色へ戻す
                        self.duty_current[ti] = None;
                        self.duty[ti].reset();
                        let t = self.tone_set[ti];
                        self.synth.set_tone(ti, t);
                    }
                }
                EventKind::Portamento { cents, frames } => {
                    if let Some(pc) = self.pitch.get_mut(ti) {
                        let vib = vibrato_of(&self.song, self.vib_current[ti]);
                        pc.glide(&mut self.synth, ti, cents, frames, vib);
                    }
                }
                EventKind::Shot { id, vel } => self.start_shot(id, vel, e.track),
            }
        }
        if changed {
            self.rebuild_sounding();
        }
    }
}