Skip to main content

pikopiko_runtime/binary/
render.rs

1//! 音を作る処理:1 サンプルずつ命令を実行し、エンベロープと音程エフェクトを進める。
2//!
3//! [`Sequencer::step`] が 1 サンプルの入口で、[`Sequencer::render`] はそれと音源の `next` を
4//! 繰り返す。命令の実行(`process_inner`)はシークでも使い、そのときは音を鳴らさずに音色・
5//! パラメータ・テンポ・選択だけを反映する。音源の呼び出しの順は `pikopiko::Player` と同じに
6//! してある(`tests/binary.rs` がサンプル単位で突き合わせる)。メモリ確保・ロック・I/O・
7//! パニックはしない。
8
9use super::*;
10
11impl<'a, const TRACKS: usize> Sequencer<'a, TRACKS> {
12    /// `out` を埋める。メモリ確保、ロック、I/O、パニックをしない。
13    pub fn render<C: Synth + ?Sized>(&mut self, synth: &mut C, out: &mut [[f32; 2]]) {
14        for frame in out.iter_mut() {
15            if !self.step(synth) {
16                *frame = [0.0, 0.0];
17                continue;
18            }
19            let [l, r] = synth.next(self.audible);
20            *frame = [
21                (l * self.volume).clamp(-1.0, 1.0),
22                (r * self.volume).clamp(-1.0, 1.0),
23            ];
24        }
25    }
26
27    /// 1 サンプル分だけ進める(イベントを送り、エンベロープと音程エフェクトを進める)。
28    /// 音源の `next` は呼ばないので、ほかの曲(効果音など)と同じ音源を鳴らすときに使う。
29    /// 鳴らすべきサンプルなら `true`、終わっている(終わった)なら `false`。
30    /// [`Sequencer::render`] は、これと音源の `next(audible)` を 1 サンプルずつ呼ぶのと同じ。
31    pub fn step<C: Synth + ?Sized>(&mut self, synth: &mut C) -> bool {
32        if self.finished {
33            return false;
34        }
35        if self.data.is_empty() && self.fingerprint.0 != 0 {
36            // `unbind` したまま。曲データがないので何も鳴らさない
37            return false;
38        }
39        if self.x.paused {
40            return false;
41        }
42        if !self.started {
43            synth.reset();
44            self.started = true;
45            self.x.tempo_sent = None;
46        }
47        if let Some(t) = self.x.pending_seek.take() {
48            self.do_seek(synth, t);
49            if self.finished {
50                return false;
51            }
52        }
53        match self.x.pending_jump {
54            Some((m, JumpAt::Now, _)) => self.do_jump(synth, m),
55            Some((m, JumpAt::Beat | JumpAt::Bar, due)) if self.tick >= due => {
56                self.do_jump(synth, m)
57            }
58            _ => {}
59        }
60        // テンポは 1/1000 BPM なので、分母も 1000 倍する(整数の比のまま、誤差なし)
61        let denom = 60 * self.sample_rate as u64 * SCALE_ONE * 1000;
62        let step = self.header.ppq as u64 * self.x.tempo_scale;
63        let end = self.end_tick();
64        self.process(synth);
65        self.send_tempo(synth);
66        self.pass_points();
67        if self.tick >= end {
68            let may_loop = self.looping && self.loop_limit.is_none_or(|n| self.loops_done < n);
69            if let Some((m, _, _)) = self.x.pending_jump {
70                // 待っている移動は、曲の終わりで(ループや終わりの代わりに)
71                self.do_jump(synth, m);
72                self.process(synth);
73                self.send_tempo(synth);
74                self.pass_points();
75            } else if may_loop {
76                self.loops_done = self.loops_done.saturating_add(1);
77                if self.header.loop_at.is_none() && self.x.range_start > 0 {
78                    // ループ点のない曲は、再生範囲の頭へ戻る(`pikopiko::Player` と同じ)
79                    self.do_seek(synth, self.x.range_start);
80                } else {
81                    self.jump_to_loop(synth);
82                }
83                self.x.tempo_sent = None;
84                self.reset_points(self.tick);
85                self.x.notices.push(SeqNotice::Looped(self.loops_done));
86                self.process(synth);
87                self.send_tempo(synth);
88                self.pass_points();
89            } else {
90                for ch in 0..synth.channels() {
91                    synth.note_off(ch);
92                }
93                for c in self.cursors.iter_mut() {
94                    c.env.reset();
95                    c.duty.reset();
96                    c.pitch.reset();
97                }
98                self.finished = true;
99                self.x.notices.push(SeqNotice::Finished);
100                return false;
101            }
102        }
103        self.tick_envelopes(synth);
104        self.tick_duty(synth);
105        self.tick_pitch(synth);
106        self.acc += self.tempo as u64 * step;
107        if self.acc >= denom {
108            self.tick += self.acc / denom;
109            self.acc %= denom;
110        }
111        true
112    }
113
114    /// 今のテンポ(曲のテンポ × テンポ倍率)が変わっていれば、音源に知らせる。
115    pub(super) fn send_tempo<C: Synth + ?Sized>(&mut self, synth: &mut C) {
116        let bpm_milli =
117            (self.tempo as u64 * self.x.tempo_scale / SCALE_ONE).min(u32::MAX as u64) as u32;
118        if self.x.tempo_sent != Some(bpm_milli) {
119            self.x.tempo_sent = Some(bpm_milli);
120            synth.set_tempo(bpm_milli);
121        }
122    }
123
124    /// 音量エンベロープを1サンプル進める(`pikopiko::Player` と同じ順)。
125    pub(super) fn tick_envelopes<C: Synth + ?Sized>(&mut self, synth: &mut C) {
126        let (lk, sr) = (self.lookup(), self.sample_rate);
127        for t in 0..self.header.tracks as usize {
128            let c = &mut self.cursors[t];
129            if c.env.is_running() {
130                c.env.tick(synth, t, lk.env(c.env_current), sr);
131            }
132        }
133    }
134
135    /// 音色エンベロープ(`@duty`)を1サンプル進める(`pikopiko::Player` と同じ順)。
136    pub(super) fn tick_duty<C: Synth + ?Sized>(&mut self, synth: &mut C) {
137        let (lk, sr) = (self.lookup(), self.sample_rate);
138        for t in 0..self.header.tracks as usize {
139            let c = &mut self.cursors[t];
140            if c.duty.is_running() {
141                c.duty.tick(synth, t, lk.duty(c.duty_current), sr);
142            }
143        }
144    }
145
146    /// 音程エフェクトを1サンプル進める(`pikopiko::Player` と同じ順・同じ条件)。
147    pub(super) fn tick_pitch<C: Synth + ?Sized>(&mut self, synth: &mut C) {
148        let (lk, sr) = (self.lookup(), self.sample_rate);
149        for t in 0..self.header.tracks as usize {
150            let c = &mut self.cursors[t];
151            let sounding = c.env.is_held() || c.env.is_releasing();
152            let fx = lk.pitch_fx(c);
153            if fx.vib.is_some() || c.pitch.is_running() {
154                c.pitch.tick(synth, t, sounding, fx, sr);
155            }
156        }
157    }
158
159    pub(super) fn lookup(&self) -> Lookup<'a> {
160        Lookup {
161            data: self.data,
162            tables: self.tables,
163            transpose: self.x.transpose,
164        }
165    }
166
167    pub(super) fn jump_to_loop<C: Synth + ?Sized>(&mut self, synth: &mut C) {
168        synth.reset();
169        self.tempo = TEMPO_MILLI;
170        let loop_tick = self.header.loop_at.unwrap_or(0) as u64 * self.header.unit as u64;
171        self.tick = loop_tick;
172        self.acc = 0;
173        let data = self.data;
174        let lk = self.lookup();
175        // 復元ブロックで選び直すエンベロープ(トラックの順に処理するので、最後にまとめて反映する)
176        let mut pending_env: [Option<u8>; TRACKS] = [None; TRACKS];
177        let mut pending_vib: [Option<Option<u8>>; TRACKS] = [None; TRACKS];
178        let mut pending_det: [Option<Option<u8>>; TRACKS] = [None; TRACKS];
179        let mut pending_arp: [Option<Option<u8>>; TRACKS] = [None; TRACKS];
180        let mut pending_duty: [Option<Option<u8>>; TRACKS] = [None; TRACKS];
181        for t in 0..self.header.tracks as usize {
182            let c = &mut self.cursors[t];
183            match c.loop_pos {
184                Some(pos) => {
185                    c.stack[0] = (pos, c.end);
186                    c.sp = 0;
187                    c.done = pos == c.end;
188                    c.next_tick = loop_tick;
189                    c.last_key = c.snap_key;
190                    c.last_wait = c.snap_wait;
191                    c.vel = c.snap_vel;
192                    c.reset_effects();
193                    let block = c.loop_block;
194                    // 復元ブロック:ループ点の時点の音色、パラメータ、テンポ
195                    let mut target = t;
196                    let mut p = block.0;
197                    while p < block.1 {
198                        let Some(b) = data.get(p).copied() else { break };
199                        p += 1;
200                        let (o, a) = (b >> 5, b & 31);
201                        if o == op::TONE {
202                            let tone = if a == 31 {
203                                let v = data.get(p).copied().unwrap_or(0);
204                                p += 1;
205                                v
206                            } else {
207                                a
208                            };
209                            synth.set_tone(target, tone);
210                        } else if a == ext::PARAM {
211                            let id = read_varint(data, &mut p).unwrap_or(0) as u16;
212                            let v = read_varint(data, &mut p).unwrap_or(0);
213                            crate::set_param_id(synth, target, id, v);
214                        } else if a == ext::TEMPO {
215                            let v = read_varint(data, &mut p).unwrap_or(TEMPO as u32);
216                            self.tempo = v.clamp(1, 999) * 1000;
217                        } else if a == ext::TEMPO_FINE {
218                            let v = read_varint(data, &mut p).unwrap_or(TEMPO_MILLI);
219                            self.tempo = v.clamp(MIN_TEMPO_MILLI, MAX_TEMPO_MILLI);
220                        } else if a == ext::WAVE {
221                            let i = data.get(p).copied().unwrap_or(0);
222                            p += 1;
223                            if let Some(w) = lk.wave(i) {
224                                synth.set_wave(target, &w);
225                            }
226                        } else if a == ext::CHANNEL {
227                            target = data.get(p).copied().unwrap_or(0) as usize;
228                            p += 1;
229                        } else if a == ext::ENVELOPE {
230                            let i = data.get(p).copied().unwrap_or(0);
231                            p += 1;
232                            pending_env[target.min(TRACKS - 1)] = Some(i);
233                        } else if a == ext::DUTY {
234                            let v = data.get(p).copied().unwrap_or(0);
235                            p += 1;
236                            pending_duty[target.min(TRACKS - 1)] = Some(v.checked_sub(1));
237                        } else if a == ext::VIBRATO || a == ext::DETUNE || a == ext::ARP {
238                            let v = data.get(p).copied().unwrap_or(0);
239                            p += 1;
240                            let sel = v.checked_sub(1);
241                            let i = target.min(TRACKS - 1);
242                            match a {
243                                ext::VIBRATO => pending_vib[i] = Some(sel),
244                                ext::DETUNE => pending_det[i] = Some(sel),
245                                _ => pending_arp[i] = Some(sel),
246                            }
247                        } else {
248                            break;
249                        }
250                    }
251                }
252                None => {
253                    // ループ点がない曲は頭へ戻る
254                    c.rewind();
255                    c.next_tick = loop_tick;
256                }
257            }
258        }
259        for (t, c) in self.cursors.iter_mut().enumerate() {
260            if pending_env[t].is_some() {
261                c.env_selected = pending_env[t];
262            }
263            if let Some(v) = pending_duty[t] {
264                c.duty_selected = v;
265            }
266            if let Some(v) = pending_vib[t] {
267                c.vib_selected = v;
268            }
269            if let Some(v) = pending_det[t] {
270                c.detune_selected = v;
271            }
272            if let Some(v) = pending_arp[t] {
273                c.arp_selected = v;
274            }
275        }
276    }
277
278    /// 現在の tick までの命令を、トラックの順に実行する。
279    pub(super) fn process<C: Synth + ?Sized>(&mut self, synth: &mut C) {
280        self.process_inner(synth, None);
281    }
282
283    /// `until` が `None` なら現在の tick までの命令を実行する。`Some(t)` なら `t` より前の命令を、
284    /// 音を鳴らさずに実行する(シーク。音色・パラメータ・テンポ・選択だけを音源と状態に反映する)。
285    pub(super) fn process_inner<C: Synth + ?Sized>(&mut self, synth: &mut C, until: Option<u64>) {
286        let unit = self.header.unit as u64;
287        let data = self.data;
288        let lk = self.lookup();
289        let silent = until.is_some();
290        // 移調で折り返した音があった最初のトラック(移調ごとに 1 回だけ通知する)
291        let mut folded: Option<u8> = None;
292        for t in 0..self.header.tracks as usize {
293            let mut wrapped = false;
294            loop {
295                let c = &mut self.cursors[t];
296                let stop = match until {
297                    Some(u) => c.next_tick >= u,
298                    None => c.next_tick > self.tick,
299                };
300                if c.done || stop {
301                    break;
302                }
303                let (pos, end) = c.stack[c.sp];
304                if pos >= end {
305                    if c.sp == 0 {
306                        c.done = true;
307                    } else {
308                        c.sp -= 1;
309                    }
310                    continue;
311                }
312                let Some(b) = data.get(pos).copied() else {
313                    c.done = true;
314                    break;
315                };
316                let mut p = pos + 1;
317                let (o, a) = (b >> 5, b & 31);
318                let rel = |last: u8| (last as i32 + a as i32 - 16).clamp(0, 127) as u8;
319                match o {
320                    op::NOTE_REL | op::NOTE_WAIT => {
321                        let key = rel(c.last_key);
322                        c.last_key = key;
323                        if !silent {
324                            wrapped |= retrigger(synth, t, c, key, lk);
325                        }
326                        if o == op::NOTE_WAIT {
327                            c.next_tick += c.last_wait as u64 * unit;
328                        }
329                    }
330                    op::LEGATO_REL => {
331                        let key = rel(c.last_key);
332                        c.last_key = key;
333                        if !silent {
334                            wrapped |= note_on(synth, t, c, key, lk);
335                        }
336                    }
337                    op::WAIT => {
338                        c.last_wait = a as u32 + 1;
339                        c.next_tick += c.last_wait as u64 * unit;
340                    }
341                    op::VOLUME => c.vel = a,
342                    op::OFF_WAIT => {
343                        if !silent {
344                            c.pitch.note_off(lk.pitch_fx(c));
345                            c.env.note_off(synth, t, lk.env(c.env_current));
346                            c.duty.note_off(synth, t, lk.duty(c.duty_current));
347                        }
348                        if a > 0 {
349                            c.last_wait = a as u32;
350                            c.next_tick += a as u64 * unit;
351                        }
352                    }
353                    op::TONE => {
354                        let tone = if a == 31 {
355                            let v = data.get(p).copied().unwrap_or(0);
356                            p += 1;
357                            v
358                        } else {
359                            a
360                        };
361                        synth.set_tone(t, tone);
362                    }
363                    _ => match a {
364                        ext::NOTE_ABS | ext::LEGATO_ABS => {
365                            let key = data.get(p).copied().unwrap_or(0).min(127);
366                            p += 1;
367                            c.last_key = key;
368                            if silent {
369                            } else if a == ext::NOTE_ABS {
370                                wrapped |= retrigger(synth, t, c, key, lk);
371                            } else {
372                                wrapped |= note_on(synth, t, c, key, lk);
373                            }
374                        }
375                        ext::PARAM => {
376                            let id = read_varint(data, &mut p).unwrap_or(0) as u16;
377                            let v = read_varint(data, &mut p).unwrap_or(0);
378                            crate::set_param_id(synth, t, id, v);
379                        }
380                        ext::WAVE => {
381                            let i = data.get(p).copied().unwrap_or(0);
382                            p += 1;
383                            if let Some(w) = lk.wave(i) {
384                                synth.set_wave(t, &w);
385                            }
386                        }
387                        ext::TEMPO => {
388                            let v = read_varint(data, &mut p).unwrap_or(TEMPO as u32);
389                            self.tempo = v.clamp(1, 999) * 1000;
390                        }
391                        ext::TEMPO_FINE => {
392                            let v = read_varint(data, &mut p).unwrap_or(TEMPO_MILLI);
393                            self.tempo = v.clamp(MIN_TEMPO_MILLI, MAX_TEMPO_MILLI);
394                        }
395                        ext::WAIT_LONG => {
396                            let v = read_varint(data, &mut p).unwrap_or(1);
397                            c.last_wait = v;
398                            c.next_tick += v as u64 * unit;
399                        }
400                        ext::REF => {
401                            let dist = read_varint(data, &mut p).unwrap_or(0) as usize;
402                            let len = read_varint(data, &mut p).unwrap_or(0) as usize;
403                            c.stack[c.sp].0 = p;
404                            if c.sp < MAX_REF_DEPTH {
405                                let target = pos.saturating_sub(dist);
406                                c.sp += 1;
407                                c.stack[c.sp] = (target, target + len);
408                            }
409                            continue;
410                        }
411                        ext::ENVELOPE => {
412                            c.env_selected = data.get(p).copied();
413                            p += 1;
414                        }
415                        ext::DUTY => {
416                            c.duty_selected = data.get(p).copied().and_then(|v| v.checked_sub(1));
417                            p += 1;
418                            if c.duty_selected.is_none() && !silent {
419                                // 解除:動かしていた音色を止める。戻す音色は、エンコーダが続けて書く `TONE`
420                                c.duty_current = None;
421                                c.duty.reset();
422                            }
423                        }
424                        ext::VIBRATO => {
425                            c.vib_selected = data.get(p).copied().and_then(|v| v.checked_sub(1));
426                            p += 1;
427                        }
428                        ext::DETUNE => {
429                            c.detune_selected = data.get(p).copied().and_then(|v| v.checked_sub(1));
430                            p += 1;
431                        }
432                        ext::ARP => {
433                            c.arp_selected = data.get(p).copied().and_then(|v| v.checked_sub(1));
434                            p += 1;
435                        }
436                        ext::PORTAMENTO => {
437                            let cents = i16::from_le_bytes([
438                                data.get(p).copied().unwrap_or(0),
439                                data.get(p + 1).copied().unwrap_or(0),
440                            ]);
441                            p += 2;
442                            let frames =
443                                read_varint(data, &mut p).unwrap_or(0).min(u16::MAX as u32);
444                            if !silent {
445                                c.pitch.glide(
446                                    synth,
447                                    t,
448                                    cents,
449                                    frames as u16,
450                                    lk.vib(c.vib_current),
451                                );
452                            }
453                        }
454                        ext::LOOP => {
455                            let len = read_varint(data, &mut p).unwrap_or(0) as usize;
456                            p += len;
457                            c.snap_key = c.last_key;
458                            c.snap_wait = c.last_wait;
459                            c.snap_vel = c.vel;
460                        }
461                        _ => {
462                            c.done = true;
463                            break;
464                        }
465                    },
466                }
467                c.stack[c.sp].0 = p;
468            }
469            if wrapped && folded.is_none() {
470                folded = Some(t as u8);
471            }
472        }
473        if let Some(track) = folded {
474            if !self.x.fold_reported {
475                self.x.fold_reported = true;
476                self.x.notices.push(SeqNotice::Transposed { track });
477            }
478        }
479    }
480}
481
482/// 音を鳴らす(`pikopiko::Player` の `NoteOn` と同じ)。音を離していれば新しい音なので、
483/// 選んでいるエンベロープ・ビブラート・デチューン・アルペジオに切り替える。
484pub(super) fn note_on<C: Synth + ?Sized>(
485    synth: &mut C,
486    t: usize,
487    c: &mut Cursor,
488    key: u8,
489    lk: Lookup<'_>,
490) -> bool {
491    let retrigger = !c.env.is_held();
492    if retrigger {
493        c.env_current = c.env_selected;
494        c.vib_current = c.vib_selected;
495        c.detune_current = c.detune_selected;
496        c.arp_current = c.arp_selected;
497        c.duty_current = c.duty_selected;
498        // 音色エンベロープも、音源の note_on より前に最初の段の音色にする
499        c.duty.note_on(synth, t, lk.duty(c.duty_current));
500    }
501    // 音程のずれは、音源の note_on より前に渡す
502    let fx = lk.pitch_fx(c);
503    c.pitch.note_on(synth, t, retrigger, fx);
504    // 移調は鳴らすときだけ(`last_key` は書かれた高さのまま。相対の音符の基準になる)
505    let (key, wrapped) = crate::transpose_key(synth, t, key, lk.transpose);
506    c.env.note_on(synth, t, key, c.vel, lk.env(c.env_current));
507    wrapped
508}
509
510/// 音を止めてから鳴らす(`NOTE_*`)。`Player` の `NoteOff` + `NoteOn` と同じ呼び出しになる。
511pub(super) fn retrigger<C: Synth + ?Sized>(
512    synth: &mut C,
513    t: usize,
514    c: &mut Cursor,
515    key: u8,
516    lk: Lookup<'_>,
517) -> bool {
518    if c.env.is_held() {
519        c.pitch.note_off(lk.pitch_fx(c));
520        c.env.note_off(synth, t, lk.env(c.env_current));
521        c.duty.note_off(synth, t, lk.duty(c.duty_current));
522    } else if !c.env.is_releasing() {
523        synth.note_off(t);
524    }
525    note_on(synth, t, c, key, lk)
526}