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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! 音を作る処理:1 サンプルずつ命令を実行し、エンベロープと音程エフェクトを進める。
//!
//! [`Sequencer::step`] が 1 サンプルの入口で、[`Sequencer::render`] はそれと音源の `next` を
//! 繰り返す。命令の実行(`process_inner`)はシークでも使い、そのときは音を鳴らさずに音色・
//! パラメータ・テンポ・選択だけを反映する。音源の呼び出しの順は `pikopiko::Player` と同じに
//! してある(`tests/binary.rs` がサンプル単位で突き合わせる)。メモリ確保・ロック・I/O・
//! パニックはしない。
use super::*;
impl<'a, const TRACKS: usize> Sequencer<'a, TRACKS> {
/// `out` を埋める。メモリ確保、ロック、I/O、パニックをしない。
pub fn render<C: Synth + ?Sized>(&mut self, synth: &mut C, out: &mut [[f32; 2]]) {
for frame in out.iter_mut() {
if !self.step(synth) {
*frame = [0.0, 0.0];
continue;
}
let [l, r] = synth.next(self.audible);
*frame = [
(l * self.volume).clamp(-1.0, 1.0),
(r * self.volume).clamp(-1.0, 1.0),
];
}
}
/// 1 サンプル分だけ進める(イベントを送り、エンベロープと音程エフェクトを進める)。
/// 音源の `next` は呼ばないので、ほかの曲(効果音など)と同じ音源を鳴らすときに使う。
/// 鳴らすべきサンプルなら `true`、終わっている(終わった)なら `false`。
/// [`Sequencer::render`] は、これと音源の `next(audible)` を 1 サンプルずつ呼ぶのと同じ。
pub fn step<C: Synth + ?Sized>(&mut self, synth: &mut C) -> bool {
if self.finished {
return false;
}
if self.data.is_empty() && self.fingerprint.0 != 0 {
// `unbind` したまま。曲データがないので何も鳴らさない
return false;
}
if self.x.paused {
return false;
}
if !self.started {
synth.reset();
self.started = true;
self.x.tempo_sent = None;
}
if let Some(t) = self.x.pending_seek.take() {
self.do_seek(synth, t);
if self.finished {
return false;
}
}
match self.x.pending_jump {
Some((m, JumpAt::Now, _)) => self.do_jump(synth, m),
Some((m, JumpAt::Beat | JumpAt::Bar, due)) if self.tick >= due => {
self.do_jump(synth, m)
}
_ => {}
}
// テンポは 1/1000 BPM なので、分母も 1000 倍する(整数の比のまま、誤差なし)
let denom = 60 * self.sample_rate as u64 * SCALE_ONE * 1000;
let step = self.header.ppq as u64 * self.x.tempo_scale;
let end = self.end_tick();
self.process(synth);
self.send_tempo(synth);
self.pass_points();
if self.tick >= end {
let may_loop = self.looping && self.loop_limit.is_none_or(|n| self.loops_done < n);
if let Some((m, _, _)) = self.x.pending_jump {
// 待っている移動は、曲の終わりで(ループや終わりの代わりに)
self.do_jump(synth, m);
self.process(synth);
self.send_tempo(synth);
self.pass_points();
} else if may_loop {
self.loops_done = self.loops_done.saturating_add(1);
if self.header.loop_at.is_none() && self.x.range_start > 0 {
// ループ点のない曲は、再生範囲の頭へ戻る(`pikopiko::Player` と同じ)
self.do_seek(synth, self.x.range_start);
} else {
self.jump_to_loop(synth);
}
self.x.tempo_sent = None;
self.reset_points(self.tick);
self.x.notices.push(SeqNotice::Looped(self.loops_done));
self.process(synth);
self.send_tempo(synth);
self.pass_points();
} else {
for ch in 0..synth.channels() {
synth.note_off(ch);
}
for c in self.cursors.iter_mut() {
c.env.reset();
c.duty.reset();
c.pitch.reset();
}
self.finished = true;
self.x.notices.push(SeqNotice::Finished);
return false;
}
}
self.tick_envelopes(synth);
self.tick_duty(synth);
self.tick_pitch(synth);
self.acc += self.tempo as u64 * step;
if self.acc >= denom {
self.tick += self.acc / denom;
self.acc %= denom;
}
true
}
/// 今のテンポ(曲のテンポ × テンポ倍率)が変わっていれば、音源に知らせる。
pub(super) fn send_tempo<C: Synth + ?Sized>(&mut self, synth: &mut C) {
let bpm_milli =
(self.tempo as u64 * self.x.tempo_scale / SCALE_ONE).min(u32::MAX as u64) as u32;
if self.x.tempo_sent != Some(bpm_milli) {
self.x.tempo_sent = Some(bpm_milli);
synth.set_tempo(bpm_milli);
}
}
/// 音量エンベロープを1サンプル進める(`pikopiko::Player` と同じ順)。
pub(super) fn tick_envelopes<C: Synth + ?Sized>(&mut self, synth: &mut C) {
let (lk, sr) = (self.lookup(), self.sample_rate);
for t in 0..self.header.tracks as usize {
let c = &mut self.cursors[t];
if c.env.is_running() {
c.env.tick(synth, t, lk.env(c.env_current), sr);
}
}
}
/// 音色エンベロープ(`@duty`)を1サンプル進める(`pikopiko::Player` と同じ順)。
pub(super) fn tick_duty<C: Synth + ?Sized>(&mut self, synth: &mut C) {
let (lk, sr) = (self.lookup(), self.sample_rate);
for t in 0..self.header.tracks as usize {
let c = &mut self.cursors[t];
if c.duty.is_running() {
c.duty.tick(synth, t, lk.duty(c.duty_current), sr);
}
}
}
/// 音程エフェクトを1サンプル進める(`pikopiko::Player` と同じ順・同じ条件)。
pub(super) fn tick_pitch<C: Synth + ?Sized>(&mut self, synth: &mut C) {
let (lk, sr) = (self.lookup(), self.sample_rate);
for t in 0..self.header.tracks as usize {
let c = &mut self.cursors[t];
let sounding = c.env.is_held() || c.env.is_releasing();
let fx = lk.pitch_fx(c);
if fx.vib.is_some() || c.pitch.is_running() {
c.pitch.tick(synth, t, sounding, fx, sr);
}
}
}
pub(super) fn lookup(&self) -> Lookup<'a> {
Lookup {
data: self.data,
tables: self.tables,
transpose: self.x.transpose,
}
}
pub(super) fn jump_to_loop<C: Synth + ?Sized>(&mut self, synth: &mut C) {
synth.reset();
self.tempo = TEMPO_MILLI;
let loop_tick = self.header.loop_at.unwrap_or(0) as u64 * self.header.unit as u64;
self.tick = loop_tick;
self.acc = 0;
let data = self.data;
let lk = self.lookup();
// 復元ブロックで選び直すエンベロープ(トラックの順に処理するので、最後にまとめて反映する)
let mut pending_env: [Option<u8>; TRACKS] = [None; TRACKS];
let mut pending_vib: [Option<Option<u8>>; TRACKS] = [None; TRACKS];
let mut pending_det: [Option<Option<u8>>; TRACKS] = [None; TRACKS];
let mut pending_arp: [Option<Option<u8>>; TRACKS] = [None; TRACKS];
let mut pending_duty: [Option<Option<u8>>; TRACKS] = [None; TRACKS];
for t in 0..self.header.tracks as usize {
let c = &mut self.cursors[t];
match c.loop_pos {
Some(pos) => {
c.stack[0] = (pos, c.end);
c.sp = 0;
c.done = pos == c.end;
c.next_tick = loop_tick;
c.last_key = c.snap_key;
c.last_wait = c.snap_wait;
c.vel = c.snap_vel;
c.reset_effects();
let block = c.loop_block;
// 復元ブロック:ループ点の時点の音色、パラメータ、テンポ
let mut target = t;
let mut p = block.0;
while p < block.1 {
let Some(b) = data.get(p).copied() else { break };
p += 1;
let (o, a) = (b >> 5, b & 31);
if o == op::TONE {
let tone = if a == 31 {
let v = data.get(p).copied().unwrap_or(0);
p += 1;
v
} else {
a
};
synth.set_tone(target, tone);
} else if a == ext::PARAM {
let id = read_varint(data, &mut p).unwrap_or(0) as u16;
let v = read_varint(data, &mut p).unwrap_or(0);
crate::set_param_id(synth, target, id, v);
} else if a == ext::TEMPO {
let v = read_varint(data, &mut p).unwrap_or(TEMPO as u32);
self.tempo = v.clamp(1, 999) * 1000;
} else if a == ext::TEMPO_FINE {
let v = read_varint(data, &mut p).unwrap_or(TEMPO_MILLI);
self.tempo = v.clamp(MIN_TEMPO_MILLI, MAX_TEMPO_MILLI);
} else if a == ext::WAVE {
let i = data.get(p).copied().unwrap_or(0);
p += 1;
if let Some(w) = lk.wave(i) {
synth.set_wave(target, &w);
}
} else if a == ext::CHANNEL {
target = data.get(p).copied().unwrap_or(0) as usize;
p += 1;
} else if a == ext::ENVELOPE {
let i = data.get(p).copied().unwrap_or(0);
p += 1;
pending_env[target.min(TRACKS - 1)] = Some(i);
} else if a == ext::DUTY {
let v = data.get(p).copied().unwrap_or(0);
p += 1;
pending_duty[target.min(TRACKS - 1)] = Some(v.checked_sub(1));
} else if a == ext::VIBRATO || a == ext::DETUNE || a == ext::ARP {
let v = data.get(p).copied().unwrap_or(0);
p += 1;
let sel = v.checked_sub(1);
let i = target.min(TRACKS - 1);
match a {
ext::VIBRATO => pending_vib[i] = Some(sel),
ext::DETUNE => pending_det[i] = Some(sel),
_ => pending_arp[i] = Some(sel),
}
} else {
break;
}
}
}
None => {
// ループ点がない曲は頭へ戻る
c.rewind();
c.next_tick = loop_tick;
}
}
}
for (t, c) in self.cursors.iter_mut().enumerate() {
if pending_env[t].is_some() {
c.env_selected = pending_env[t];
}
if let Some(v) = pending_duty[t] {
c.duty_selected = v;
}
if let Some(v) = pending_vib[t] {
c.vib_selected = v;
}
if let Some(v) = pending_det[t] {
c.detune_selected = v;
}
if let Some(v) = pending_arp[t] {
c.arp_selected = v;
}
}
}
/// 現在の tick までの命令を、トラックの順に実行する。
pub(super) fn process<C: Synth + ?Sized>(&mut self, synth: &mut C) {
self.process_inner(synth, None);
}
/// `until` が `None` なら現在の tick までの命令を実行する。`Some(t)` なら `t` より前の命令を、
/// 音を鳴らさずに実行する(シーク。音色・パラメータ・テンポ・選択だけを音源と状態に反映する)。
pub(super) fn process_inner<C: Synth + ?Sized>(&mut self, synth: &mut C, until: Option<u64>) {
let unit = self.header.unit as u64;
let data = self.data;
let lk = self.lookup();
let silent = until.is_some();
// 移調で折り返した音があった最初のトラック(移調ごとに 1 回だけ通知する)
let mut folded: Option<u8> = None;
for t in 0..self.header.tracks as usize {
let mut wrapped = false;
loop {
let c = &mut self.cursors[t];
let stop = match until {
Some(u) => c.next_tick >= u,
None => c.next_tick > self.tick,
};
if c.done || stop {
break;
}
let (pos, end) = c.stack[c.sp];
if pos >= end {
if c.sp == 0 {
c.done = true;
} else {
c.sp -= 1;
}
continue;
}
let Some(b) = data.get(pos).copied() else {
c.done = true;
break;
};
let mut p = pos + 1;
let (o, a) = (b >> 5, b & 31);
let rel = |last: u8| (last as i32 + a as i32 - 16).clamp(0, 127) as u8;
match o {
op::NOTE_REL | op::NOTE_WAIT => {
let key = rel(c.last_key);
c.last_key = key;
if !silent {
wrapped |= retrigger(synth, t, c, key, lk);
}
if o == op::NOTE_WAIT {
c.next_tick += c.last_wait as u64 * unit;
}
}
op::LEGATO_REL => {
let key = rel(c.last_key);
c.last_key = key;
if !silent {
wrapped |= note_on(synth, t, c, key, lk);
}
}
op::WAIT => {
c.last_wait = a as u32 + 1;
c.next_tick += c.last_wait as u64 * unit;
}
op::VOLUME => c.vel = a,
op::OFF_WAIT => {
if !silent {
c.pitch.note_off(lk.pitch_fx(c));
c.env.note_off(synth, t, lk.env(c.env_current));
c.duty.note_off(synth, t, lk.duty(c.duty_current));
}
if a > 0 {
c.last_wait = a as u32;
c.next_tick += a as u64 * unit;
}
}
op::TONE => {
let tone = if a == 31 {
let v = data.get(p).copied().unwrap_or(0);
p += 1;
v
} else {
a
};
synth.set_tone(t, tone);
}
_ => match a {
ext::NOTE_ABS | ext::LEGATO_ABS => {
let key = data.get(p).copied().unwrap_or(0).min(127);
p += 1;
c.last_key = key;
if silent {
} else if a == ext::NOTE_ABS {
wrapped |= retrigger(synth, t, c, key, lk);
} else {
wrapped |= note_on(synth, t, c, key, lk);
}
}
ext::PARAM => {
let id = read_varint(data, &mut p).unwrap_or(0) as u16;
let v = read_varint(data, &mut p).unwrap_or(0);
crate::set_param_id(synth, t, id, v);
}
ext::WAVE => {
let i = data.get(p).copied().unwrap_or(0);
p += 1;
if let Some(w) = lk.wave(i) {
synth.set_wave(t, &w);
}
}
ext::TEMPO => {
let v = read_varint(data, &mut p).unwrap_or(TEMPO as u32);
self.tempo = v.clamp(1, 999) * 1000;
}
ext::TEMPO_FINE => {
let v = read_varint(data, &mut p).unwrap_or(TEMPO_MILLI);
self.tempo = v.clamp(MIN_TEMPO_MILLI, MAX_TEMPO_MILLI);
}
ext::WAIT_LONG => {
let v = read_varint(data, &mut p).unwrap_or(1);
c.last_wait = v;
c.next_tick += v as u64 * unit;
}
ext::REF => {
let dist = read_varint(data, &mut p).unwrap_or(0) as usize;
let len = read_varint(data, &mut p).unwrap_or(0) as usize;
c.stack[c.sp].0 = p;
if c.sp < MAX_REF_DEPTH {
let target = pos.saturating_sub(dist);
c.sp += 1;
c.stack[c.sp] = (target, target + len);
}
continue;
}
ext::ENVELOPE => {
c.env_selected = data.get(p).copied();
p += 1;
}
ext::DUTY => {
c.duty_selected = data.get(p).copied().and_then(|v| v.checked_sub(1));
p += 1;
if c.duty_selected.is_none() && !silent {
// 解除:動かしていた音色を止める。戻す音色は、エンコーダが続けて書く `TONE`
c.duty_current = None;
c.duty.reset();
}
}
ext::VIBRATO => {
c.vib_selected = data.get(p).copied().and_then(|v| v.checked_sub(1));
p += 1;
}
ext::DETUNE => {
c.detune_selected = data.get(p).copied().and_then(|v| v.checked_sub(1));
p += 1;
}
ext::ARP => {
c.arp_selected = data.get(p).copied().and_then(|v| v.checked_sub(1));
p += 1;
}
ext::PORTAMENTO => {
let cents = i16::from_le_bytes([
data.get(p).copied().unwrap_or(0),
data.get(p + 1).copied().unwrap_or(0),
]);
p += 2;
let frames =
read_varint(data, &mut p).unwrap_or(0).min(u16::MAX as u32);
if !silent {
c.pitch.glide(
synth,
t,
cents,
frames as u16,
lk.vib(c.vib_current),
);
}
}
ext::LOOP => {
let len = read_varint(data, &mut p).unwrap_or(0) as usize;
p += len;
c.snap_key = c.last_key;
c.snap_wait = c.last_wait;
c.snap_vel = c.vel;
}
_ => {
c.done = true;
break;
}
},
}
c.stack[c.sp].0 = p;
}
if wrapped && folded.is_none() {
folded = Some(t as u8);
}
}
if let Some(track) = folded {
if !self.x.fold_reported {
self.x.fold_reported = true;
self.x.notices.push(SeqNotice::Transposed { track });
}
}
}
}
/// 音を鳴らす(`pikopiko::Player` の `NoteOn` と同じ)。音を離していれば新しい音なので、
/// 選んでいるエンベロープ・ビブラート・デチューン・アルペジオに切り替える。
pub(super) fn note_on<C: Synth + ?Sized>(
synth: &mut C,
t: usize,
c: &mut Cursor,
key: u8,
lk: Lookup<'_>,
) -> bool {
let retrigger = !c.env.is_held();
if retrigger {
c.env_current = c.env_selected;
c.vib_current = c.vib_selected;
c.detune_current = c.detune_selected;
c.arp_current = c.arp_selected;
c.duty_current = c.duty_selected;
// 音色エンベロープも、音源の note_on より前に最初の段の音色にする
c.duty.note_on(synth, t, lk.duty(c.duty_current));
}
// 音程のずれは、音源の note_on より前に渡す
let fx = lk.pitch_fx(c);
c.pitch.note_on(synth, t, retrigger, fx);
// 移調は鳴らすときだけ(`last_key` は書かれた高さのまま。相対の音符の基準になる)
let (key, wrapped) = crate::transpose_key(synth, t, key, lk.transpose);
c.env.note_on(synth, t, key, c.vel, lk.env(c.env_current));
wrapped
}
/// 音を止めてから鳴らす(`NOTE_*`)。`Player` の `NoteOff` + `NoteOn` と同じ呼び出しになる。
pub(super) fn retrigger<C: Synth + ?Sized>(
synth: &mut C,
t: usize,
c: &mut Cursor,
key: u8,
lk: Lookup<'_>,
) -> bool {
if c.env.is_held() {
c.pitch.note_off(lk.pitch_fx(c));
c.env.note_off(synth, t, lk.env(c.env_current));
c.duty.note_off(synth, t, lk.duty(c.duty_current));
} else if !c.env.is_releasing() {
synth.note_off(t);
}
note_on(synth, t, c, key, lk)
}