pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! MML の音源 `#synth sfx`。差し替え口(`SynthSpec` と `Synth`)だけを使う。

use std::boxed::Box;
use std::vec::Vec;

use crate::synth::{ParamInfo, Scope, Synth, SynthSpec, ToneInfo};

use crate::synth::sfx::Voice;
use crate::synth::sfx::{id, Category, SfxParams, PARAMS};

/// トラック数の上限(同時に鳴らせる効果音の数)。
const MAX_TRACKS: usize = 8;
/// 鳴らし直すときに、前の音を絞る時間(秒の 1/1000)。プチノイズを出さない。
const FADE_MS: u32 = 2;
/// 曲の終わりの後に鳴らし続ける長さの上限(秒)。
const MAX_TAIL_SECS: u32 = 10;

const fn build_params() -> [ParamInfo; id::COUNT] {
    let base = Category::Coin.preset();
    let mut out = [ParamInfo {
        name: "",
        min: 0,
        max: 0,
        default: 0,
        scope: Scope::Track,
    }; id::COUNT];
    let mut i = 0;
    while i < id::COUNT {
        let d = PARAMS[i];
        out[i] = ParamInfo {
            name: d.name,
            min: d.min as u32,
            max: d.max as u32,
            default: base.values_const()[i] as u32,
            scope: Scope::Track,
        };
        i += 1;
    }
    out
}

const SYNTH_PARAMS: [ParamInfo; id::COUNT] = build_params();

const TONES: [ToneInfo; 8] = [
    ToneInfo { id: 0 },
    ToneInfo { id: 1 },
    ToneInfo { id: 2 },
    ToneInfo { id: 3 },
    ToneInfo { id: 4 },
    ToneInfo { id: 5 },
    ToneInfo { id: 6 },
    ToneInfo { id: 7 },
];

/// `#synth sfx` の説明。
pub const SFX: SynthSpec = SynthSpec {
    texts: crate::synth::sfx::text_table::CATALOGS,
    name: "sfx",
    aliases: &[],
    max_tracks: MAX_TRACKS,
    polyphony: 1,
    tones: &TONES,
    default_tone: 0,
    unpitched_tones: &[],
    duty_tones: false,
    wave_memory: false,
    params: &SYNTH_PARAMS,
    options: &[],
    presets: crate::synth::sfx::presets::PRESETS,
    knobs: &[],
    tone_files: crate::synth::tones::sfx::FILES,
    check_sample: None,
    key_range: |_| (0, 127),
    create: |_, sr, n| Box::new(SfxSynth::new(sr, n)),
};

struct Channel {
    params: SfxParams,
    voice: Voice,
    /// 鳴らし直したときの前の音([`FADE_MS`] で絞る)。
    old: Voice,
    old_fade: u32,
    key: u8,
    cents_q8: i32,
    vel: u8,
}

impl Channel {
    fn new() -> Self {
        Channel {
            params: SfxParams::default(),
            voice: Voice::new(),
            old: Voice::new(),
            old_fade: 0,
            key: 60,
            cents_q8: 0,
            vel: 15,
        }
    }

    /// 音符の高さとセントのずれを、1/256 半音のずれに(`o4 c` = 60 が 0)。
    fn offset_q8(&self) -> i32 {
        (self.key as i32 - 60) * 256 + self.cents_q8 / 100
    }
}

/// `#synth sfx` の実体。
pub struct SfxSynth {
    sample_rate: u32,
    channels: Vec<Channel>,
    fade_len: u32,
}

impl SfxSynth {
    /// `channels` トラック分を作る(メモリはここで確保し、鳴らす間は確保しない)。
    pub fn new(sample_rate: u32, channels: usize) -> Self {
        let sample_rate = sample_rate.max(1);
        SfxSynth {
            sample_rate,
            channels: (0..channels.min(MAX_TRACKS))
                .map(|_| Channel::new())
                .collect(),
            fade_len: (sample_rate * FADE_MS / 1000).max(1),
        }
    }
}

impl Synth for SfxSynth {
    fn channels(&self) -> usize {
        self.channels.len()
    }

    fn reset(&mut self) {
        for c in &mut self.channels {
            c.params = SfxParams::default();
            c.voice.stop();
            c.old.stop();
            c.old_fade = 0;
            c.key = 60;
            c.cents_q8 = 0;
            c.vel = 15;
        }
    }

    fn set_tone(&mut self, ch: usize, tone: u8) {
        if let (Some(c), Some(cat)) = (self.channels.get_mut(ch), Category::from_index(tone)) {
            // 音色を選ぶと、すべてのパラメータがそのカテゴリのプリセットになる
            c.params = cat.preset();
        }
    }

    fn set_param(&mut self, ch: usize, param: u8, value: u32) {
        if let Some(c) = self.channels.get_mut(ch) {
            c.params.set(param as usize, value);
        }
    }

    fn param(&self, ch: usize, param: u8) -> Option<u32> {
        let i = param as usize;
        if i >= id::COUNT {
            return None;
        }
        self.channels.get(ch).map(|c| c.params.get(i) as u32)
    }

    fn note_on(&mut self, ch: usize, key: u8, vel: u8) {
        let (sr, fade) = (self.sample_rate, self.fade_len);
        let Some(c) = self.channels.get_mut(ch) else {
            return;
        };
        if c.voice.is_active() {
            // 鳴っている音は短く絞って消す(波形が途切れないように)
            core::mem::swap(&mut c.voice, &mut c.old);
            c.old_fade = fade;
        }
        c.key = key;
        c.vel = vel;
        let off = c.offset_q8();
        c.voice.start(&c.params, sr, off);
    }

    fn note_off(&mut self, _ch: usize) {
        // ワンショット:音符が終わっても効果音は最後まで鳴らす
    }

    fn set_volume(&mut self, ch: usize, vel: u8) {
        if let Some(c) = self.channels.get_mut(ch) {
            c.vel = vel;
        }
    }

    fn set_pitch(&mut self, ch: usize, cents_q8: i32) {
        if let Some(c) = self.channels.get_mut(ch) {
            c.cents_q8 = cents_q8;
            let off = c.offset_q8();
            c.voice.set_pitch_offset(off);
        }
    }

    fn next(&mut self, audible: u32) -> [f32; 2] {
        let (mut l, mut r) = (0i64, 0i64);
        let fade_len = self.fade_len as i64;
        for (i, c) in self.channels.iter_mut().enumerate() {
            let mut s = c.voice.next_sample() as i64;
            if c.old_fade > 0 {
                let o = c.old.next_sample() as i64;
                s += o * c.old_fade as i64 / fade_len;
                c.old_fade -= 1;
                if c.old_fade == 0 {
                    c.old.stop();
                }
            }
            if audible & (1 << i) == 0 || s == 0 {
                continue;
            }
            let s = s * c.vel.min(15) as i64 / 15;
            let pan = c.params.get(id::PAN) as i64;
            l += s * (16 - pan).min(8) / 8;
            r += s * pan.min(8) / 8;
        }
        [l as f32 / 32768.0, r as f32 / 32768.0]
    }

    fn tail_frames(&self) -> u32 {
        let longest = self
            .channels
            .iter()
            .map(|c| c.voice.remaining().max(c.old_fade))
            .max()
            .unwrap_or(0);
        longest.min(self.sample_rate * MAX_TAIL_SECS)
    }
}