pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! 効果音の割り込み:BGM と同じ音源のチャンネルを借りて効果音を鳴らし、終わったら BGM の状態を
//! 書き戻す(`Player::register_sfx`・`play_sfx`・`stop_sfx` など)。
//!
//! 効果音はバイナリにして `Sequencer` で鳴らし、BGM の音源の呼び出しは `Routed` を通して
//! ランタイムの `Interrupt` に任せる(マイコンのランタイムと同じ道を通り、同じ音になるように)。
//! 効果音を登録しない間は、この道を通らない。

use super::*;

/// 効果音の割り込みの状態(チャンネル 32 本、パラメータ 64 個まで覚える)。
pub(super) type Ints = Interrupt<32, 64>;

/// BGM を鳴らす音源。効果音を登録していれば、効果音に貸しているチャンネルへの BGM の書き込みを
/// 影の状態にだけ入れる([`Interrupt::bgm`])。登録していなければ、音源へそのまま渡す。
pub(super) struct Routed {
    pub(super) inner: Box<dyn Synth>,
    pub(super) ints: Option<Box<Ints>>,
}

/// BGM の音源の呼び出しを、効果音を登録していれば `Interrupt` 経由に、していなければ直接に回す。
macro_rules! route {
    ($self:ident, $name:ident ( $($arg:expr),* )) => {
        match $self.ints.as_deref_mut() {
            Some(i) => i.bgm(&mut *$self.inner).$name($($arg),*),
            None => $self.inner.$name($($arg),*),
        }
    };
}

impl Synth for Routed {
    fn channels(&self) -> usize {
        self.inner.channels()
    }
    fn reset(&mut self) {
        route!(self, reset())
    }
    fn set_tone(&mut self, ch: usize, tone: u8) {
        route!(self, set_tone(ch, tone))
    }
    fn prepare_tone(&mut self, tone: u8) {
        self.inner.prepare_tone(tone)
    }
    fn set_wave(&mut self, ch: usize, wave: &[i8]) {
        route!(self, set_wave(ch, wave))
    }
    fn set_param(&mut self, ch: usize, param: u8, value: u32) {
        route!(self, set_param(ch, param, value))
    }
    fn set_param_hi(&mut self, ch: usize, param: u8, value: u32) {
        route!(self, set_param_hi(ch, param, value))
    }
    fn param_hi(&self, ch: usize, param: u8) -> Option<u32> {
        self.inner.param_hi(ch, param)
    }
    fn note_on(&mut self, ch: usize, key: u8, vel: u8) {
        route!(self, note_on(ch, key, vel))
    }
    fn note_off(&mut self, ch: usize) {
        route!(self, note_off(ch))
    }
    fn set_volume(&mut self, ch: usize, vel: u8) {
        route!(self, set_volume(ch, vel))
    }
    fn set_pitch(&mut self, ch: usize, cents_q8: i32) {
        route!(self, set_pitch(ch, cents_q8))
    }
    fn next(&mut self, audible: u32) -> [f32; 2] {
        route!(self, next(audible))
    }
    fn set_tempo(&mut self, bpm_milli: u32) {
        self.inner.set_tempo(bpm_milli)
    }
    fn chord_on(&mut self, ch: usize, keys: &[u8], vel: u8, legato: bool) {
        route!(self, chord_on(ch, keys, vel, legato))
    }
    fn tail_frames(&self) -> u32 {
        self.inner.tail_frames()
    }
    fn latency_frames(&self) -> u32 {
        self.inner.latency_frames()
    }
    fn param(&self, ch: usize, param: u8) -> Option<u32> {
        self.inner.param(ch, param)
    }
    fn set_sfx_mask(&mut self, mask: u32) {
        self.inner.set_sfx_mask(mask)
    }
    fn shot_duck(&mut self) {
        self.inner.shot_duck()
    }
    fn mix_input(&mut self, frame: [f32; 2]) -> bool {
        route!(self, mix_input(frame))
    }
}

/// 登録した効果音。
pub(super) struct SfxEntry {
    /// イベント列バイナリ。
    pub(super) data: Box<[u8]>,
    pub(super) tracks: u8,
    pub(super) tone: u8,
}

/// 効果音のシーケンサー(曲データを外した状態で持ち、`render` の間だけ付ける)。
pub(super) type SfxSeq<'a> = Sequencer<'a, MAX_SFX_TRACKS>;

impl Player {
    /// 鳴っている効果音があるか。
    pub fn sfx_active(&self) -> bool {
        self.sfx_playing.iter().any(Option::is_some)
    }

    /// 効果音 `id` が鳴っているか。
    pub fn is_sfx_playing(&self, id: SfxId) -> bool {
        self.sfx_playing.contains(&Some(id.0))
    }

    /// 効果音を登録する。効果音は BGM と同じ音源(`#synth`)の曲で、トラックは 4 本まで。
    /// ここでイベント列バイナリにしてメモリを確保するので、オーディオスレッドでは呼ばない
    /// (鳴らす [`Command::PlaySfx`] は確保しない)。
    pub fn register_sfx(&mut self, sfx: &Song) -> Result<SfxId, SfxError> {
        if sfx.synth.name != self.song.synth.name {
            return Err(SfxError::SynthMismatch);
        }
        if sfx.tracks.is_empty() || sfx.tracks.len() > MAX_SFX_TRACKS {
            return Err(SfxError::BadTracks);
        }
        if self.sfx.len() >= MAX_REGISTERED_SFX {
            return Err(SfxError::Full);
        }
        // 効果音が使う音色も、鳴らす前に知らせる
        super::announce_tones(self.synth.inner.as_mut(), sfx);
        let data = crate::export::binary::encode(sfx)
            .map_err(|_| SfxError::Encode)?
            .into_boxed_slice();
        let seq = SfxSeq::new(&data, self.sample_rate)
            .map_err(|_| SfxError::Encode)?
            .unbind();
        if self.synth.ints.is_none() {
            let mut ints = Box::new(Ints::new());
            for &(id, default, wide) in &self.param_info {
                ints.set_param_info(id, default, wide);
            }
            ints.set_default_tone(self.song.default_tone);
            self.synth.ints = Some(ints);
        }
        let id = SfxId(self.sfx.len() as u8);
        self.sfx.push(SfxEntry {
            data,
            tracks: sfx.tracks.len() as u8,
            tone: sfx.default_tone,
        });
        self.sfx_seqs.push(Some(seq));
        Ok(id)
    }

    /// 登録した効果音を、BGM のチャンネルを借りて頭から鳴らす。メモリ確保はしない。
    ///
    /// `channels` は効果音のトラックを置く BGM のチャンネル([`SfxChannels::AUTO`] なら後ろから)。
    /// 借りたいチャンネルを別の効果音が使っていれば、`priority` が同じか高いときだけ取り替える。
    /// 同じ効果音が鳴っていれば頭から鳴らし直す。`looping` なら効果音の曲のループ点
    /// (なければ頭)へ戻って、止めるまで鳴らし続ける。
    /// 鳴らせなければ通知 [`Notice::SfxRejected`] も出す。
    pub fn play_sfx(
        &mut self,
        id: SfxId,
        channels: SfxChannels,
        priority: u8,
        looping: bool,
    ) -> Result<(), SfxError> {
        let r = self.try_play_sfx(id, channels, priority, looping);
        if r.is_err() {
            self.notices.push(Notice::SfxRejected(id));
        }
        r
    }

    pub(super) fn try_play_sfx(
        &mut self,
        id: SfxId,
        channels: SfxChannels,
        priority: u8,
        looping: bool,
    ) -> Result<(), SfxError> {
        let e = id.0 as usize;
        let entry = self.sfx.get(e).ok_or(SfxError::Unknown)?;
        let (tracks, tone) = (entry.tracks as usize, entry.tone);
        let Some(ints) = self.synth.ints.as_deref_mut() else {
            return Err(SfxError::Unknown);
        };
        let slot = match self.sfx_playing.iter().position(|p| *p == Some(id.0)) {
            Some(s) => s,
            None => self
                .sfx_playing
                .iter()
                .position(Option::is_none)
                .ok_or(SfxError::Busy)?,
        };
        let replaced = ints
            .start(
                &mut *self.synth.inner,
                slot,
                tracks,
                channels,
                priority,
                tone,
            )
            .map_err(|err| match err {
                interrupt::SfxError::Busy => SfxError::Busy,
                _ => SfxError::BadChannels,
            })?;
        for i in 0..MAX_SFX {
            if replaced & (1 << i) != 0 {
                if let Some(old) = self.sfx_playing[i].take() {
                    self.notices.push(Notice::SfxFinished(SfxId(old)));
                }
            }
        }
        if let Some(seq) = self.sfx_seqs[e].as_mut() {
            seq.restart();
            seq.set_looping(looping);
        }
        self.sfx_playing[slot] = Some(id.0);
        Ok(())
    }

    /// 効果音を止めてチャンネルを BGM に返す。鳴っていなければ何もしない。
    pub fn stop_sfx(&mut self, id: SfxId) {
        if let Some(slot) = self.sfx_playing.iter().position(|p| *p == Some(id.0)) {
            if let Some(ints) = self.synth.ints.as_deref_mut() {
                ints.stop(&mut *self.synth.inner, slot);
            }
            self.sfx_playing[slot] = None;
            self.notices.push(Notice::SfxFinished(id));
        }
    }

    /// 鳴っている効果音をすべて止める。
    pub fn stop_all_sfx(&mut self) {
        for slot in 0..MAX_SFX {
            if let Some(id) = self.sfx_playing[slot] {
                self.stop_sfx(SfxId(id));
            }
        }
    }

    /// 鳴っている効果音を 1 サンプル進める。終わった効果音はチャンネルを BGM に返す。
    pub(super) fn step_sfx(&mut self, sfx: &mut [Option<(usize, SfxSeq<'_>)>; MAX_SFX]) {
        let Some(ints) = self.synth.ints.as_deref_mut() else {
            return;
        };
        for (slot, bound) in sfx.iter_mut().enumerate() {
            let Some(id) = self.sfx_playing[slot] else {
                continue;
            };
            let Some((e, seq)) = bound.as_mut() else {
                continue;
            };
            if *e != id as usize {
                continue;
            }
            if !seq.step(&mut ints.sfx(&mut *self.synth.inner, slot)) {
                ints.stop(&mut *self.synth.inner, slot);
                self.sfx_playing[slot] = None;
                self.notices.push(Notice::SfxFinished(SfxId(id)));
            }
        }
    }

    /// 鳴らすチャンネルのビットマスク。
    pub(super) fn audible_mask(&self) -> u32 {
        match self.solo {
            Some(s) if s < 32 => 1 << s,
            Some(_) => 0,
            None => {
                let mut m = 0u32;
                for (i, muted) in self.muted.iter().enumerate().take(32) {
                    if !muted {
                        m |= 1 << i;
                    }
                }
                m
            }
        }
    }
}