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
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! 呼び出し側(ゲームのスレッドなど)で持つ操作口([`MixerHandle`])。
//!
//! 曲・クリップ・先読みの溜め場所はここで作り(確保はこちらのスレッドで行う)、リングバッファで
//! オーディオスレッドへ移す。鳴り終わって戻ってきたものもここで手放す([`MixerHandle::collect_garbage`])。

use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;

use super::engine::{BusOp, Garbage, Msg, Source};
use super::lookahead::{self, LaShared, Worker, WorkerMsg};
use super::tap::Tap;
use super::{
    unpack_activity, BusId, Clip, ClipId, ClipOptions, MixerError, PlayOptions, Playheads, SoundId,
    SwitchAt, SwitchOptions, TapRead, LOOKAHEAD_BLOCK, MAX_LOOKAHEAD, MAX_SOUNDS,
    MAX_TRACK_ACTIVITY, MIN_LOOKAHEAD,
};
use crate::player::TrackActivity;
use crate::{Command, Notice, Player, Song};
use pikopiko_runtime::output::EqSettings;

/// 鳴らしている曲の、呼び出し側から見た情報。
struct Active {
    id: SoundId,
    bus: BusId,
    /// 先読みする曲なら、その共有の値。
    lookahead: Option<Arc<LaShared>>,
}

/// 呼び出し側(ゲームのスレッドなど)で持つ操作口。
pub struct MixerHandle {
    tx: rtrb::Producer<Msg>,
    garbage: rtrb::Consumer<Garbage>,
    notices: rtrb::Consumer<(SoundId, Notice)>,
    heads: Arc<Playheads>,
    tap: Arc<Tap>,
    next_id: u64,
    next_clip: u64,
    active: Vec<Active>,
    sample_rate: u32,
    /// 先読みのスレッド。最初に先読みする曲を鳴らすときに立てる。
    worker: Option<Worker>,
}

impl MixerHandle {
    pub(super) fn new(
        tx: rtrb::Producer<Msg>,
        garbage: rtrb::Consumer<Garbage>,
        notices: rtrb::Consumer<(SoundId, Notice)>,
        heads: Arc<Playheads>,
        tap: Arc<Tap>,
        sample_rate: u32,
    ) -> MixerHandle {
        MixerHandle {
            tx,
            garbage,
            notices,
            heads,
            tap,
            next_id: 1,
            next_clip: 1,
            active: Vec::with_capacity(MAX_SOUNDS),
            sample_rate,
            worker: None,
        }
    }

    pub fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    /// 曲を、曲が選んだ音源(`synth::ALL` から探す)で `Player` にする。
    fn player(&self, song: Arc<Song>, looping: bool) -> Player {
        let mut p = crate::synth::player(song, self.sample_rate);
        if looping {
            p.handle(Command::SetLooping(true));
        }
        p
    }

    /// 曲を頭から1回鳴らす([`BusId::MAIN`])。鳴り終わると自動で取り除かれる。
    /// 音源は曲が選んだもの(`va` などの機能で入れた音源も)。
    pub fn play(&mut self, song: Arc<Song>) -> Result<SoundId, MixerError> {
        let p = self.player(song, false);
        self.play_player(p)
    }

    /// 曲をループ再生する(ループ点 `*` があればそこへ戻る。[`BusId::MAIN`])。止めるまで鳴り続ける。
    pub fn play_looped(&mut self, song: Arc<Song>) -> Result<SoundId, MixerError> {
        let p = self.player(song, true);
        self.play_player(p)
    }

    /// 用意した `Player` を鳴らす(独自音源、範囲再生、ソロなどを先に設定したいとき。[`BusId::MAIN`])。
    /// `Player` のサンプルレートはミキサーと同じにすること。
    pub fn play_player(&mut self, player: Player) -> Result<SoundId, MixerError> {
        self.play_with(player, PlayOptions::default())
    }

    /// 曲を無音から `fade` かけて等倍まで上げながら、ループ再生する(BGM の始まり。[`BusId::MAIN`])。
    pub fn play_looped_with_fade_in(
        &mut self,
        song: Arc<Song>,
        fade: Duration,
    ) -> Result<SoundId, MixerError> {
        let p = self.player(song, true);
        self.play_player_with_fade_in(p, fade)
    }

    /// 用意した `Player` を、無音から `fade` かけて等倍まで上げながら鳴らす([`BusId::MAIN`])。
    pub fn play_player_with_fade_in(
        &mut self,
        player: Player,
        fade: Duration,
    ) -> Result<SoundId, MixerError> {
        // 0 フレームだと等倍で始まるので、少なくとも 1 フレームかける
        let fade = fade.max(Duration::from_nanos(1));
        self.play_with(
            player,
            PlayOptions {
                fade_in: fade,
                ..PlayOptions::default()
            },
        )
    }

    /// 用意した `Player` を、バス・フェードイン・先読みを選んで鳴らす。
    ///
    /// `Player` のサンプルレートはミキサーと同じにすること(曲が選んだ音源で作るなら
    /// `pikopiko::synth::player(song, handle.sample_rate())`)。先読みについては
    /// [`PlayOptions::lookahead`]。先読みする曲の `Player` は、先読みのスレッドへ移る。
    pub fn play_with(&mut self, player: Player, opts: PlayOptions) -> Result<SoundId, MixerError> {
        let bus = opts.bus;
        bus.index()?;
        let fade = if opts.fade_in.is_zero() {
            0
        } else {
            self.frames(opts.fade_in).max(1)
        };
        self.add(player, bus, fade, opts.lookahead, None)
    }

    /// 鳴っている曲 `from` から、次の曲 `to` へ切り替える。`to` は `from` と同じバスで鳴らす。
    ///
    /// [`SwitchAt::Now`] ならすぐ、[`SwitchAt::NextBar`] なら `from` の次の小節の頭で `to` を鳴らし始め、
    /// 同時に `from` を `fade` かけて下げて取り除く(クロスフェード)。待っている間、`to` は枠を 1 つ使い、
    /// 先読みするなら溜めておく。`from` がもう鳴っていなければ [`MixerError::NotPlaying`]。
    pub fn switch(
        &mut self,
        from: SoundId,
        to: Player,
        opts: SwitchOptions,
    ) -> Result<SoundId, MixerError> {
        self.collect_garbage();
        let Some(bus) = self.active.iter().find(|a| a.id == from).map(|a| a.bus) else {
            return Err(MixerError::NotPlaying);
        };
        let fade = self.frames(opts.fade);
        match opts.at {
            SwitchAt::Now => {
                let id = self.add(to, bus, fade.max(1), opts.lookahead, None)?;
                self.send_fade(from, 0.0, opts.fade, true)?;
                Ok(id)
            }
            SwitchAt::NextBar => self.add(to, bus, fade, opts.lookahead, Some(from)),
        }
    }

    fn add(
        &mut self,
        player: Player,
        bus: BusId,
        fade_in: u32,
        lookahead: Duration,
        after: Option<SoundId>,
    ) -> Result<SoundId, MixerError> {
        self.collect_garbage();
        if self.active.len() >= MAX_SOUNDS {
            return Err(MixerError::TooManySounds);
        }
        let id = SoundId(self.next_id);
        self.next_id += 1;
        let bar_ticks = bar_ticks(player.song());
        let length = player.song().length_ticks;
        let (source, shared) = if lookahead.is_zero() {
            (Source::Player(Box::new(player)), None)
        } else {
            let capacity = self.frames(MAX_LOOKAHEAD) as usize;
            let target = self.lookahead_frames(lookahead);
            let (job, stream) = lookahead::channel(id, player, capacity, target);
            let shared = stream.shared.clone();
            self.worker
                .get_or_insert_with(Worker::spawn)
                .send(WorkerMsg::Add(job));
            (Source::Stream(stream), Some(shared))
        };
        let msg = Msg::Add {
            id,
            source,
            fade_in,
            bus: bus.0,
            bar_ticks,
            length,
            after,
        };
        if let Err(rtrb::PushError::Full(msg)) = self.tx.push(msg) {
            if let Msg::Add {
                source: Source::Stream(s),
                ..
            } = &msg
            {
                // 先読みのスレッドに渡した `Player` を手放させる
                s.shared.removed.store(true, Ordering::Release);
            }
            return Err(MixerError::QueueFull);
        }
        self.active.push(Active {
            id,
            bus,
            lookahead: shared,
        });
        Ok(id)
    }

    /// 先読みの長さをフレーム数にする。最短は [`MIN_LOOKAHEAD`] と出力の遅れの 2 倍の長いほう
    /// (出力が 1 回に持っていく量より十分に溜めないと、補充が間に合わずに尽きるため)、上限は
    /// [`MAX_LOOKAHEAD`]。出力の遅れは、このときに知らされている値を使う(まだなら 0)。
    fn lookahead_frames(&self, d: Duration) -> u32 {
        let floor = self
            .frames(MIN_LOOKAHEAD)
            .max(self.output_latency_frames().saturating_mul(2))
            .max(LOOKAHEAD_BLOCK as u32);
        let max = self.frames(MAX_LOOKAHEAD);
        self.frames(d.min(MAX_LOOKAHEAD)).max(floor).min(max)
    }

    /// 先読みしている曲の、先読みの長さを変える。長くすると先読みのスレッドが追加で作って溜め、短くすると
    /// 溜まっている分を鳴らし終えるまで新しく作らない(溜めた音は捨てない)。0 や短すぎる値は最短
    /// ([`MIN_LOOKAHEAD`] と出力の遅れの 2 倍の長いほう)、[`MAX_LOOKAHEAD`] より長い値は上限にする。確保はしない。
    ///
    /// 先読みせずに鳴らし始めた曲は [`MixerError::NotLookahead`](先読みするかは鳴らし始めに決まる)。
    pub fn set_lookahead(&mut self, id: SoundId, lookahead: Duration) -> Result<(), MixerError> {
        self.collect_garbage();
        let target = self.lookahead_frames(lookahead);
        let a = self
            .active
            .iter()
            .find(|a| a.id == id)
            .ok_or(MixerError::NotPlaying)?;
        let shared = a.lookahead.as_ref().ok_or(MixerError::NotLookahead)?;
        shared.target.store(target, Ordering::Relaxed);
        Ok(())
    }

    /// その曲がいま溜めている長さ(これから送る操作が聞こえるまでの遅れ)。先読みしていない曲は 0。
    /// 鳴っていない曲は `None`。決めた長さではなく、実際に溜まっている量を返す。
    pub fn lookahead(&mut self, id: SoundId) -> Option<Duration> {
        self.collect_garbage();
        let a = self.active.iter().find(|a| a.id == id)?;
        Some(match &a.lookahead {
            Some(s) => Duration::from_secs_f64(s.buffered() as f64 / self.sample_rate as f64),
            None => Duration::ZERO,
        })
    }

    /// 先読みしている曲で、溜めた音が尽きて無音を出した回数(鳴らし始める前の待ちは数えない)。
    /// 先読みしていない曲は 0、鳴っていない曲は `None`。増えるようなら先読みを長くする。
    pub fn lookahead_underruns(&mut self, id: SoundId) -> Option<u32> {
        self.collect_garbage();
        let a = self.active.iter().find(|a| a.id == id)?;
        Some(
            a.lookahead
                .as_ref()
                .map_or(0, |s| s.underruns.load(Ordering::Relaxed)),
        )
    }

    /// 曲ごとの音量を、`fade` かけて `volume`(1.0 が等倍)まで直線で変える。
    /// `Duration::ZERO` ならすぐ変わる。`Command::SetVolume` とは別に掛け合わさる。
    /// 途中で次のフェードを送ると、その時点の音量から新しいフェードを始める。先読みしていても遅れない。
    pub fn fade_to(&mut self, id: SoundId, volume: f32, fade: Duration) -> Result<(), MixerError> {
        self.send_fade(id, clean_volume(volume), fade, false)
    }

    /// `fade` かけて無音まで下げ、下げきったら止めて取り除く(BGM の終わり、曲の切り替え)。
    pub fn fade_out_and_stop(&mut self, id: SoundId, fade: Duration) -> Result<(), MixerError> {
        self.send_fade(id, 0.0, fade, true)
    }

    fn send_fade(
        &mut self,
        id: SoundId,
        target: f32,
        fade: Duration,
        stop: bool,
    ) -> Result<(), MixerError> {
        self.collect_garbage();
        if !self.active.iter().any(|a| a.id == id) {
            return Err(MixerError::NotPlaying);
        }
        let frames = self.frames(fade);
        self.push(Msg::Fade {
            id,
            target,
            frames,
            stop,
        })
    }

    /// 時間をフレーム数にする(四捨五入、`u32` に収まらなければ上限)。
    fn frames(&self, d: Duration) -> u32 {
        (d.as_secs_f64() * self.sample_rate as f64)
            .round()
            .min(u32::MAX as f64) as u32
    }

    fn push(&mut self, msg: Msg) -> Result<(), MixerError> {
        self.tx.push(msg).map_err(|_| MixerError::QueueFull)
    }

    /// 鳴らしている曲に操作を送る。先読みしている曲では、溜めた分([`MixerHandle::lookahead`])だけ
    /// 遅れて聞こえる。
    pub fn send(&mut self, id: SoundId, cmd: Command) -> Result<(), MixerError> {
        self.collect_garbage();
        let a = self
            .active
            .iter()
            .find(|a| a.id == id)
            .ok_or(MixerError::NotPlaying)?;
        if a.lookahead.is_some() {
            if let Some(w) = &self.worker {
                w.send(WorkerMsg::Cmd(id, cmd));
            }
            return Ok(());
        }
        self.push(Msg::Cmd(id, cmd))
    }

    /// 曲を止めて取り除く。
    pub fn stop(&mut self, id: SoundId) -> Result<(), MixerError> {
        self.collect_garbage();
        if !self.active.iter().any(|a| a.id == id) {
            return Err(MixerError::NotPlaying);
        }
        self.push(Msg::Remove(id))
    }

    /// すべての曲とクリップを止めて取り除く。
    pub fn stop_all(&mut self) -> Result<(), MixerError> {
        self.collect_garbage();
        self.push(Msg::RemoveAll)
    }

    /// 全体の音量(1.0 が等倍)。
    pub fn set_master_volume(&mut self, v: f32) -> Result<(), MixerError> {
        self.push(Msg::MasterVolume(v))
    }

    /// クリップを鳴らす。音量・再生速度・定位・バスは [`ClipOptions`]。遅れは出力のバッファの分だけ
    /// (先読みしない)。同時に [`super::MAX_CLIPS`] 本まで鳴り、満杯なら同じバスのいちばん古いクリップ
    /// (なければ全体でいちばん古いもの)を短く消して入れ替える。
    pub fn play_clip(&mut self, clip: &Clip, opts: ClipOptions) -> Result<ClipId, MixerError> {
        self.collect_garbage();
        let bus = opts.bus.index()? as u8;
        let rate = if opts.rate.is_finite() && opts.rate > 0.0 {
            f64::from(opts.rate)
        } else {
            1.0
        };
        let step = rate * f64::from(clip.sample_rate) / f64::from(self.sample_rate.max(1));
        let id = ClipId(self.next_clip);
        self.next_clip += 1;
        self.push(Msg::PlayClip {
            id,
            data: clip.frames.clone(),
            step,
            pan: opts.pan,
            volume: clean_volume(opts.volume),
            bus,
            looping: opts.looping,
        })?;
        Ok(id)
    }

    /// クリップを `fade` かけて下げて止める(`Duration::ZERO` ならすぐ)。もう鳴り終わっていれば何もしない。
    pub fn stop_clip(&mut self, id: ClipId, fade: Duration) -> Result<(), MixerError> {
        let frames = self.frames(fade);
        self.push(Msg::ClipFade {
            id,
            target: 0.0,
            frames,
            stop: true,
        })
    }

    /// クリップの音量を `fade` かけて `volume` へ変える。もう鳴り終わっていれば何もしない。
    pub fn set_clip_volume(
        &mut self,
        id: ClipId,
        volume: f32,
        fade: Duration,
    ) -> Result<(), MixerError> {
        let frames = self.frames(fade);
        self.push(Msg::ClipFade {
            id,
            target: clean_volume(volume),
            frames,
            stop: false,
        })
    }

    /// バスの音量を、`fade` かけて `volume`(1.0 が等倍)へ直線で変える。曲ごと・クリップごと・全体の音量と
    /// 掛け合わさる。BGM のダッキングに使う。
    pub fn set_bus_volume(
        &mut self,
        bus: BusId,
        volume: f32,
        fade: Duration,
    ) -> Result<(), MixerError> {
        let b = bus.index()? as u8;
        let frames = self.frames(fade);
        self.push(Msg::Bus(
            b,
            BusOp::Volume {
                target: clean_volume(volume),
                frames,
            },
        ))
    }

    /// バスを `fade` かけて下げて一時停止する。下げきったら、そのバスの曲もクリップも進まない(位置を保つ)。
    pub fn pause_bus(&mut self, bus: BusId, fade: Duration) -> Result<(), MixerError> {
        let b = bus.index()? as u8;
        let frames = self.frames(fade);
        self.push(Msg::Bus(b, BusOp::Pause { frames }))
    }

    /// 一時停止したバスを、`fade` かけて戻しながら再開する。
    pub fn resume_bus(&mut self, bus: BusId, fade: Duration) -> Result<(), MixerError> {
        let b = bus.index()? as u8;
        let frames = self.frames(fade);
        self.push(Msg::Bus(b, BusOp::Resume { frames }))
    }

    /// バスの曲とクリップを、`fade` かけて下げて止めて取り除く。一時停止しているバスならすぐ取り除く。
    pub fn stop_bus(&mut self, bus: BusId, fade: Duration) -> Result<(), MixerError> {
        let b = bus.index()? as u8;
        let frames = self.frames(fade);
        self.push(Msg::Bus(b, BusOp::Stop { frames }))
    }

    /// 出力の EQ を設定する。全部の曲を混ぜた後、全体の音量の前にかかる。
    ///
    /// `settings` はミキサーのサンプルレート([`MixerHandle::sample_rate`])で作る
    /// (違えば [`MixerError::SampleRateMismatch`])。係数の計算は `settings` を作るときに済んでいるので、
    /// オーディオスレッドでは差し替えるだけで確保しない。外すときは `EqSettings::flat` を渡す。
    ///
    /// ```
    /// # #[cfg(feature = "mixer")]
    /// # {
    /// use pikopiko::runtime::output::{profile, EqSettings};
    ///
    /// let (mut handle, _mixer) = pikopiko::player::mixer::mixer(48_000);
    /// let eq = EqSettings::new(profile::SMALL_SPEAKER, handle.sample_rate()).unwrap();
    /// handle.set_output_eq(eq).unwrap();
    /// # }
    /// ```
    pub fn set_output_eq(&mut self, settings: EqSettings) -> Result<(), MixerError> {
        if settings.sample_rate() != self.sample_rate {
            return Err(MixerError::SampleRateMismatch);
        }
        self.push(Msg::OutputEq(settings))
    }

    /// まだ鳴っているか(取り除かれていないか)。
    pub fn is_playing(&mut self, id: SoundId) -> bool {
        self.collect_garbage();
        self.active.iter().any(|a| a.id == id)
    }

    /// 鳴っている曲の、いまの再生位置(tick)。直近の描画ブロックの終わりの位置。先読みしている曲でも、
    /// いま聞こえている音の位置(先読みの分だけ先へは進まない)。
    /// まだオーディオスレッドに渡っていない曲や、取り除かれた曲は `None`。
    pub fn position(&self, id: SoundId) -> Option<u64> {
        let i = self
            .heads
            .ids
            .iter()
            .position(|a| a.load(Ordering::Relaxed) == id.0)?;
        Some(self.heads.ticks[i].load(Ordering::Relaxed))
    }

    /// 出力のピーク(左右の最大の絶対値)。前に呼んでから出た最大で、呼ぶと 0 に戻る。
    /// 全体の音量・出力の EQ・±1 への収めの後の値(機器へ渡す音)。メーターの表示用。
    pub fn take_peak(&self) -> [f32; 2] {
        self.tap.take_peak()
    }

    /// 出力の最新の波形(左右の平均)を `out` に古い順に入れる。長さは [`super::SCOPE_LEN`] まで
    /// (それより長い分は 0)。まだ出ていない分は 0。オシロスコープの表示用で、
    /// 書いている最中の境目は数サンプルずれうる。
    pub fn scope(&self, out: &mut [f32]) {
        self.tap.scope(out);
    }

    /// 出力の最新の波形を、左右別に `left`・`right` へ古い順に入れる。長さは短いほうに合わせ、
    /// [`super::SCOPE_LEN`] まで(それより長い分とまだ出ていない分は 0)。ゴニオメーター・相関の表示用で、
    /// 左右を読む時刻が数サンプルずれうる。
    pub fn scope_stereo(&self, left: &mut [f32], right: &mut [f32]) {
        self.tap.scope_stereo(left, right);
    }

    /// 出力の音の流れの、いまの位置(これまでに出したサンプルの通し番号)。ここから
    /// [`MixerHandle::read_since`] で読み始めると、これから出る音を取りこぼさず順に読める。
    pub fn tap_cursor(&self) -> u64 {
        self.tap.cursor()
    }

    /// 通し番号 `since` から先のサンプルを、左右別に `left`・`right` へ古い順に入れる(短いほうの長さまで)。
    /// 返す値の `next` を次の `since` にして呼び続けると、全サンプルを 1 回ずつ読める。遅れて
    /// [`super::STREAM_LEN`] を超えた分は読めず、`missed` に数が入る。ラウドネスの計算のための口。
    pub fn read_since(&self, since: u64, left: &mut [f32], right: &mut [f32]) -> TapRead {
        self.tap.read_since(since, left, right)
    }

    /// 鳴らしている曲 `id` の、トラックごとの発音の状態を `out` に入れ、入れた数を返す。
    /// 取り除かれた曲・まだオーディオスレッドに渡っていない曲は 0。トラックが `out` より多ければ
    /// `out` の長さまで。[`MAX_TRACK_ACTIVITY`] を超えるトラックは見えない。音そのものを測った値では
    /// なく、`Player` が音源へ渡したイベントから読んだ値([`TrackActivity`])。先読みしている曲は
    /// `Player` が先読みのスレッドにあるので 0。
    pub fn track_activity(&self, id: SoundId, out: &mut [TrackActivity]) -> usize {
        let Some(i) = self
            .heads
            .ids
            .iter()
            .position(|a| a.load(Ordering::Relaxed) == id.0)
        else {
            return 0;
        };
        let n = (self.heads.track_counts[i].load(Ordering::Relaxed) as usize)
            .min(MAX_TRACK_ACTIVITY)
            .min(out.len());
        for (t, o) in out.iter_mut().take(n).enumerate() {
            let k = i * MAX_TRACK_ACTIVITY + t;
            *o = unpack_activity(
                self.heads.tracks[k].load(Ordering::Relaxed),
                self.heads.tracks_ext[k].load(Ordering::Relaxed),
            );
        }
        n
    }

    /// 出力デバイスが、渡した音を実際に出すまでの遅れ(フレーム数)。まだ知らされていなければ 0。
    /// `cpal` の出力では、デバイスが知らせる時刻の差から更新される。
    pub fn output_latency_frames(&self) -> u32 {
        self.heads.latency.load(Ordering::Relaxed)
    }

    /// [`MixerHandle::output_latency_frames`] を秒にしたもの。映像を音に合わせるとき、波形・ピーク・
    /// 発音の状態はこの秒数だけ前の音のものを描く(`pikopiko-visualizer` の `Delay` が使える)。
    pub fn output_latency_secs(&self) -> f32 {
        self.output_latency_frames() as f32 / self.sample_rate.max(1) as f32
    }

    /// 鳴らしている曲の通知([`Notice`]:マーカー・ループ・終わり・効果音など)を 1 つ取り出す。
    /// 受け取る通知は曲ごとに `Command::SetNotify` で選ぶ。キュー([`super::NOTICE_QUEUE`] 件)が
    /// いっぱいの間に起きた通知は捨てられるので、ゲームのフレームごとに読み切る。
    /// 先読みしている曲の通知も、その音が聞こえるときに届く。
    pub fn poll_notice(&mut self) -> Option<(SoundId, Notice)> {
        self.notices.pop().ok()
    }

    /// 曲(`Player`)に登録した効果音を、BGM のチャンネルを借りて鳴らす(`Command::PlaySfx`)。
    /// 効果音は `play_player` の前に `Player::register_sfx` で登録しておく。
    pub fn play_sfx(
        &mut self,
        id: SoundId,
        sfx: crate::SfxId,
        channels: crate::SfxChannels,
        priority: u8,
    ) -> Result<(), MixerError> {
        self.send(
            id,
            Command::PlaySfx {
                sfx,
                channels,
                priority,
                looping: false,
            },
        )
    }

    /// 鳴っている曲の数。
    pub fn active_count(&mut self) -> usize {
        self.collect_garbage();
        self.active.len()
    }

    /// オーディオスレッドから戻ってきた曲・クリップを解放する。ほかのメソッドも内部で呼ぶ。
    pub fn collect_garbage(&mut self) {
        while let Ok(g) = self.garbage.pop() {
            match g {
                Garbage::Sound(id, source) => {
                    self.active.retain(|a| a.id != id);
                    drop(source);
                }
                Garbage::Clip(data) => drop(data),
            }
        }
    }
}

/// 音量の値を整える(負の値と有限でない値は 0)。
fn clean_volume(v: f32) -> f32 {
    if v.is_finite() {
        v.max(0.0)
    } else {
        0.0
    }
}

/// 曲の 1 小節の tick(拍子 `#meter` から)。
fn bar_ticks(song: &Song) -> u64 {
    let den = u64::from(song.meter.den.max(1));
    u64::from(song.ppq) * 4 * u64::from(song.meter.num.max(1)) / den
}