pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! 多オペレーターの FM(音色 `@15`、`FMX`)。2〜3 本のオペレーター(サイン波)を、アルゴリズムの表に
//! 従ってつなぎ、整数倍でない倍音の系列や、オペレーターごとに違う減衰(高い倍音から消える金属的な余韻)を作る。
//!
//! `@12`(2 オペレーター、`osc.rs` の `tone::FM`)は変えない(既存の曲の音とハッシュを守る)。この音色は
//! 別の状態 [`FmxState`] を持ち、`phases`(スーパーソウと共有の 15 個の位相)は使わない。
//!
//! 守っていること:
//! - 評価の順はアルゴリズムの表に固定してある(変調する側を先に計算する)ので、計算の順が決まっていて決定的。
//! - 三角関数・指数関数は `m`(`libm`)だけを使う。確保しない。
//! - 位相は無音から鳴らすとき 0 から始める(出だしのプチノイズ対策。`@12` と同じ)。
//! - オペレーターごとの減衰は状態を持たず、鳴らしてからの秒数 `md.t` だけで決める(`e^(-t/τ)`)。
//!   単音・和音・ポリフォニックのどれでも同じ式で、声ごとの状態が増えない。
//!
//! 段階 3 は 6 オペレーター・32 アルゴリズムまで。状態は 6 オペレーター分の大きさで持つので、
//! 4〜6 本と 32 のアルゴリズムは、表とパラメータを末尾に足すだけで広げられる。

use super::*;

/// 今実装しているオペレーターの最大の本数(段階 3 は 6)。
pub(super) const FMX_OPS_MAX: usize = 6;

/// 状態が持つオペレーターの数(段階 3 の 6 本まで見込んだ大きさ)。
const STATE_OPS: usize = 6;

/// アルゴリズム 1 つ分:オペレーターのつなぎ方。オペレーターの番号は 0 から(パラメータの `fmx1` が 0)。
#[derive(Clone, Copy)]
pub(super) struct Algo {
    /// `mods_in[n]`:オペレーター `n` の位相を動かす(変調する)オペレーターの集合(ビット `j` が `j`)。
    mods_in: [u8; STATE_OPS],
    /// 音になる(キャリア)オペレーターの集合。
    carriers: u8,
    /// 帰還をかけるオペレーター。
    fb_op: u8,
    /// 評価の順(変調する側が先)。
    order: [u8; STATE_OPS],
}

const fn algo(mods_in: [u8; STATE_OPS], carriers: u8, fb_op: u8, order: [u8; STATE_OPS]) -> Algo {
    Algo {
        mods_in,
        carriers,
        fb_op,
        order,
    }
}

/// 2 オペレーター:0 = 2 → 1(直列)、1 = 1 + 2(並列、足し合わせ)。
const ALGOS_2: [Algo; 2] = [
    algo([0b10, 0, 0, 0, 0, 0], 0b01, 1, [1, 0, 0, 0, 0, 0]),
    algo([0, 0, 0, 0, 0, 0], 0b11, 0, [1, 0, 0, 0, 0, 0]),
];

/// 3 オペレーター:0 = 3 → 2 → 1(直列)、1 = 2 と 3 が 1 を変調(並列の変調)、
/// 2 = 3 → 2 で 2 と 1 が出力(片方だけ変調)、3 = 3 つとも出力(足し合わせ)。
const ALGOS_3: [Algo; 4] = [
    algo([0b010, 0b100, 0, 0, 0, 0], 0b001, 2, [2, 1, 0, 0, 0, 0]),
    algo([0b110, 0, 0, 0, 0, 0], 0b001, 1, [2, 1, 0, 0, 0, 0]),
    algo([0, 0b100, 0, 0, 0, 0], 0b011, 2, [2, 1, 0, 0, 0, 0]),
    algo([0, 0, 0, 0, 0, 0], 0b111, 0, [2, 1, 0, 0, 0, 0]),
];

/// 4 オペレーター(OPN 系の 8 種。番号は 1 から、`a→b` は a が b を変調する。1 が主のキャリア):
/// 0 = 4→3→2→1、1 = (4+3)→2→1、2 = 4 + (3→2) → 1、3 = (4→3) + 2 → 1、
/// 4 = 4→3 と 2→1 の 2 組が出力、5 = 4 が 3・2・1 を変調、6 = 4→3 で 3・2・1 が出力、7 = 4 本とも出力。
const ALGOS_4: [Algo; 8] = [
    algo(
        [0b0010, 0b0100, 0b1000, 0, 0, 0],
        0b0001,
        3,
        [3, 2, 1, 0, 0, 0],
    ),
    algo([0b0010, 0b1100, 0, 0, 0, 0], 0b0001, 3, [3, 2, 1, 0, 0, 0]),
    algo([0b1010, 0b0100, 0, 0, 0, 0], 0b0001, 3, [3, 2, 1, 0, 0, 0]),
    algo([0b0110, 0, 0b1000, 0, 0, 0], 0b0001, 3, [3, 2, 1, 0, 0, 0]),
    algo([0b0010, 0, 0b1000, 0, 0, 0], 0b0101, 3, [3, 2, 1, 0, 0, 0]),
    algo(
        [0b1000, 0b1000, 0b1000, 0, 0, 0],
        0b0111,
        3,
        [3, 2, 1, 0, 0, 0],
    ),
    algo([0, 0, 0b1000, 0, 0, 0], 0b0111, 3, [3, 2, 1, 0, 0, 0]),
    algo([0; 6], 0b1111, 3, [3, 2, 1, 0, 0, 0]),
];

/// オペレーターの番号は 1 から(`a → b` は `a` が `b` を変調する。`a > b` の向きだけを書く)の表記で、
/// キャリアの番号の列と変調の辺の列から [`Algo`] を作る。評価の順は番号の大きい方から、
/// 帰還は変調する側で一番番号の大きいオペレーター(辺がなければ 1 本目)にかける。
const fn from_graph(carriers: &[u8], edges: &[(u8, u8)]) -> Algo {
    let mut mods_in = [0u8; STATE_OPS];
    let mut carrier_mask = 0u8;
    let mut top = 1u8;
    let mut fb = 0u8;
    let mut i = 0;
    while i < carriers.len() {
        carrier_mask |= 1 << (carriers[i] - 1);
        if carriers[i] > top {
            top = carriers[i];
        }
        i += 1;
    }
    let mut k = 0;
    while k < edges.len() {
        let (from, to) = edges[k];
        mods_in[(to - 1) as usize] |= 1 << (from - 1);
        if from > top {
            top = from;
        }
        if from - 1 > fb {
            fb = from - 1;
        }
        k += 1;
    }
    let mut order = [0u8; STATE_OPS];
    let mut n = 0;
    while n < top as usize {
        order[n] = top - 1 - n as u8;
        n += 1;
    }
    Algo {
        mods_in,
        carriers: carrier_mask,
        fb_op: fb,
        order,
    }
}

/// [`from_graph`] と同じだが、帰還をかけるオペレーター(番号は 1 から)を指定する。DX7 のアルゴリズムの表
/// ([`ALGOS_DX7`])は、帰還の位置がアルゴリズムごとに決まっているので、これで組む。
const fn from_graph_fb(carriers: &[u8], edges: &[(u8, u8)], fb_op: u8) -> Algo {
    let a = from_graph(carriers, edges);
    Algo {
        fb_op: fb_op - 1,
        ..a
    }
}

/// 5 オペレーター(8 種。1 が主のキャリア、5 が帰還つきの最上段)。
const ALGOS_5: [Algo; 8] = [
    from_graph(&[1], &[(5, 4), (4, 3), (3, 2), (2, 1)]),
    from_graph(&[1, 3], &[(2, 1), (5, 4), (4, 3)]),
    from_graph(&[1, 4], &[(3, 2), (2, 1), (5, 4)]),
    from_graph(&[1, 3], &[(2, 1), (5, 3), (4, 3)]),
    from_graph(&[1, 3, 5], &[(2, 1), (4, 3)]),
    from_graph(&[1], &[(5, 1), (4, 1), (3, 1), (2, 1)]),
    from_graph(&[1, 2, 3, 4], &[(5, 4)]),
    from_graph(&[1, 2, 3, 4, 5], &[]),
];

/// 6 オペレーター(32 種。DX7 とは別に決めた表で、1 が主のキャリア、番号の大きい方が上段):
/// 1〜7 は 1 本の列と束ね方、8〜12 は 1 本の列とキャリアの組み合わせ、13〜20 は 2〜3 組の独立した列、
/// 21〜32 は並列のキャリアと 1 本の上段(6)が複数を変調する形など。
const ALGOS_6: [Algo; 32] = [
    from_graph(&[1], &[(6, 5), (5, 4), (4, 3), (3, 2), (2, 1)]),
    from_graph(&[1], &[(6, 4), (5, 4), (4, 3), (3, 2), (2, 1)]),
    from_graph(&[1], &[(6, 5), (5, 4), (4, 2), (3, 2), (2, 1)]),
    from_graph(&[1], &[(6, 5), (5, 4), (4, 3), (3, 1), (2, 1)]),
    from_graph(&[1], &[(6, 3), (5, 3), (4, 3), (3, 2), (2, 1)]),
    from_graph(&[1], &[(6, 2), (5, 2), (4, 2), (3, 2), (2, 1)]),
    from_graph(&[1], &[(6, 1), (5, 1), (4, 1), (3, 1), (2, 1)]),
    from_graph(&[1, 2], &[(6, 5), (5, 4), (4, 3), (3, 2)]),
    from_graph(&[1, 3], &[(2, 1), (6, 5), (5, 4), (4, 3)]),
    from_graph(&[1, 4], &[(3, 2), (2, 1), (6, 5), (5, 4)]),
    from_graph(&[1, 5], &[(4, 3), (3, 2), (2, 1), (6, 5)]),
    from_graph(&[1, 6], &[(5, 4), (4, 3), (3, 2), (2, 1)]),
    from_graph(&[1, 3, 5], &[(2, 1), (4, 3), (6, 5)]),
    from_graph(&[1, 2, 3], &[(6, 5), (5, 4), (4, 3)]),
    from_graph(&[1, 3], &[(2, 1), (6, 4), (5, 4), (4, 3)]),
    from_graph(&[1, 4], &[(3, 2), (2, 1), (6, 4), (5, 4)]),
    from_graph(&[1, 3], &[(2, 1), (6, 3), (5, 3), (4, 3)]),
    from_graph(&[1, 2], &[(6, 2), (5, 2), (4, 2), (3, 2)]),
    from_graph(&[1, 2, 3], &[(6, 3), (5, 3), (4, 3)]),
    from_graph(&[1, 2, 3, 4], &[(6, 5), (5, 4)]),
    from_graph(&[1, 2, 3, 4, 5], &[(6, 5), (6, 4), (6, 3), (6, 2), (6, 1)]),
    from_graph(&[1, 2, 3, 4], &[(6, 4), (5, 4)]),
    from_graph(&[1, 2, 3, 5], &[(6, 5), (4, 3)]),
    from_graph(&[1, 2, 4, 5], &[(3, 2), (6, 5)]),
    from_graph(&[1, 2, 3, 4, 5, 6], &[]),
    from_graph(&[1, 2, 3, 4, 5], &[(6, 5)]),
    from_graph(&[1, 2, 3, 4], &[(6, 4), (5, 3)]),
    from_graph(&[1, 2, 3], &[(4, 1), (5, 2), (6, 3)]),
    from_graph(&[1, 3], &[(2, 1), (6, 5), (5, 3), (4, 3)]),
    from_graph(&[1, 2], &[(6, 5), (5, 4), (4, 1), (3, 2)]),
    from_graph(&[1, 4], &[(2, 1), (3, 1), (6, 5), (5, 4)]),
    from_graph(&[1, 2], &[(6, 5), (5, 4), (4, 3), (3, 1)]),
];

/// DX7 の 32 のアルゴリズム(6 オペレーター。`fmx_algo` 32〜63 が DX7 の 1〜32 番)。DX7 のパッチを取り込むための表で、
/// オペレーターの番号は DX7 のまま(1 が一番下のキャリア)。辺はすべて番号の大きい方から小さい方へ向く。
/// 帰還は、DX7 の 4 番・6 番(別のオペレーターへ戻る形)だけは近似で、変調する側の一番上(6)の自己帰還にしてある。
/// 表は公開されているアルゴリズムの図から書き起こした(キャリアの数は各アルゴリズムの図の説明と合うことを
/// `tests/va_fmx.rs` で確かめる)。
const ALGOS_DX7: [Algo; 32] = [
    from_graph_fb(&[1, 3], &[(2, 1), (6, 5), (5, 4), (4, 3)], 6),
    from_graph_fb(&[1, 3], &[(2, 1), (6, 5), (5, 4), (4, 3)], 2),
    from_graph_fb(&[1, 4], &[(3, 2), (2, 1), (6, 5), (5, 4)], 6),
    from_graph_fb(&[1, 4], &[(3, 2), (2, 1), (6, 5), (5, 4)], 6),
    from_graph_fb(&[1, 3, 5], &[(2, 1), (4, 3), (6, 5)], 6),
    from_graph_fb(&[1, 3, 5], &[(2, 1), (4, 3), (6, 5)], 6),
    from_graph_fb(&[1, 3], &[(2, 1), (6, 5), (5, 3), (4, 3)], 6),
    from_graph_fb(&[1, 3], &[(2, 1), (6, 5), (5, 3), (4, 3)], 4),
    from_graph_fb(&[1, 3], &[(2, 1), (6, 5), (5, 3), (4, 3)], 2),
    from_graph_fb(&[1, 4], &[(3, 2), (2, 1), (6, 4), (5, 4)], 3),
    from_graph_fb(&[1, 4], &[(3, 2), (2, 1), (6, 4), (5, 4)], 6),
    from_graph_fb(&[1, 3], &[(2, 1), (6, 3), (5, 3), (4, 3)], 2),
    from_graph_fb(&[1, 3], &[(2, 1), (6, 3), (5, 3), (4, 3)], 6),
    from_graph_fb(&[1, 3], &[(2, 1), (4, 3), (6, 4), (5, 4)], 6),
    from_graph_fb(&[1, 3], &[(2, 1), (4, 3), (6, 4), (5, 4)], 2),
    from_graph_fb(&[1], &[(2, 1), (3, 1), (5, 1), (4, 3), (6, 5)], 6),
    from_graph_fb(&[1], &[(2, 1), (3, 1), (5, 1), (4, 3), (6, 5)], 2),
    from_graph_fb(&[1], &[(2, 1), (3, 1), (4, 1), (5, 4), (6, 5)], 3),
    from_graph_fb(&[1, 4, 5], &[(3, 2), (2, 1), (6, 4), (6, 5)], 6),
    from_graph_fb(&[1, 2, 4], &[(3, 1), (3, 2), (5, 4), (6, 4)], 3),
    from_graph_fb(&[1, 2, 4, 5], &[(3, 1), (3, 2), (6, 4), (6, 5)], 3),
    from_graph_fb(&[1, 3, 4, 5], &[(2, 1), (6, 3), (6, 4), (6, 5)], 6),
    from_graph_fb(&[1, 2, 4, 5], &[(3, 2), (6, 4), (6, 5)], 6),
    from_graph_fb(&[1, 2, 3, 4, 5], &[(6, 3), (6, 4), (6, 5)], 6),
    from_graph_fb(&[1, 2, 3, 4, 5], &[(6, 4), (6, 5)], 6),
    from_graph_fb(&[1, 2, 4], &[(3, 2), (5, 4), (6, 4)], 6),
    from_graph_fb(&[1, 2, 4], &[(3, 2), (5, 4), (6, 4)], 3),
    from_graph_fb(&[1, 3, 6], &[(2, 1), (4, 3), (5, 4)], 5),
    from_graph_fb(&[1, 2, 3, 5], &[(4, 3), (6, 5)], 6),
    from_graph_fb(&[1, 2, 3, 6], &[(4, 3), (5, 4)], 5),
    from_graph_fb(&[1, 2, 3, 4, 5], &[(6, 5)], 6),
    from_graph_fb(&[1, 2, 3, 4, 5, 6], &[], 6),
];

/// 6 オペレーターのアルゴリズムの表:前半 32 は PikoPiko の表([`ALGOS_6`])、後半 32 は DX7 の表([`ALGOS_DX7`])。
const fn algos_6_all() -> [Algo; 64] {
    let mut all = [ALGOS_6[0]; 64];
    let mut i = 0;
    while i < 32 {
        all[i] = ALGOS_6[i];
        all[32 + i] = ALGOS_DX7[i];
        i += 1;
    }
    all
}

const ALGOS_6_ALL: [Algo; 64] = algos_6_all();

/// DX7 のアルゴリズム `algorithm`(0〜31、DX7 の 1〜32 番)のキャリアの集合(ビット `n` がオペレーター `n + 1`)。
/// DX7 のパッチを取り込むとき、キャリアと変調側で出力レベルの換え方を変えるのに使う(`dx7.rs`)。
pub(crate) fn dx7_carrier_mask(algorithm: u8) -> u8 {
    ALGOS_DX7[(algorithm as usize).min(31)].carriers
}

/// `ops` 本・番号 `algo` のアルゴリズム(番号は範囲に収める)。
fn pick(ops: usize, algo: usize) -> &'static Algo {
    let table: &[Algo] = match ops {
        0..=2 => &ALGOS_2,
        3 => &ALGOS_3,
        4 => &ALGOS_4,
        5 => &ALGOS_5,
        _ => &ALGOS_6_ALL,
    };
    &table[algo.min(table.len() - 1)]
}

/// FM の声 1 つ分の状態。ユニゾン(`fm_uni`、最大 4 声)の声ごとに持つ。
#[derive(Clone, Copy)]
pub(super) struct FmxState {
    /// 声ごと・オペレーターごとの位相。
    phase: [[f32; STATE_OPS]; FM_MAX_UNISON],
    /// 声ごとの帰還(前の 2 つの出力の平均)。
    fb: [f32; FM_MAX_UNISON],
    /// 加算合成(`@16`)の状態。多本数の音色の状態をここにまとめて、声・和音の音・チャンネルの置き場所を共有する。
    pub(super) add: AddState,
}

impl FmxState {
    /// 無音から鳴らすときの状態(位相は 0 から)。
    pub(super) const fn new() -> FmxState {
        FmxState {
            phase: [[0.0; STATE_OPS]; FM_MAX_UNISON],
            fb: [0.0; FM_MAX_UNISON],
            add: AddState::new(),
        }
    }
}

/// オペレーター `n`(0 から)の `k` 番目のパラメータの番号。`k` は `param::FMX_RATIO` などの並び。
fn op_param(n: usize, k: u8) -> usize {
    param::FMX_OP_BASE as usize + n * param::FMX_OP_PARAMS as usize + k as usize
}

/// 1 サンプル(左右)。`state` を進める。`dt` は鳴らす高さの 1 サンプルあたりの位相の進み。
pub(super) fn fmx(
    params: &[u32; param::COUNT],
    state: &mut FmxState,
    dt: f32,
    md: &Mods,
) -> (f32, f32) {
    let ops = (params[param::FMX_OPS as usize] as usize).clamp(2, FMX_OPS_MAX);
    let alg = pick(ops, params[param::FMX_ALGO as usize] as usize);
    let tau = core::f32::consts::TAU;
    let p = |i: usize| params[i] as f32;

    // オペレーターごとの、比・深さ(変調側)・音量(キャリア)・音程のずれ(セント)
    let mut ratio = [1.0f32; STATE_OPS];
    let mut index = [0.0f32; STATE_OPS];
    let mut amp = [0.0f32; STATE_OPS];
    let mut det_cents = [0.0f32; STATE_OPS];
    let lfo_depth = if md.has(LFO_FM) {
        md.sum[LFO_FM] * 5.0
    } else {
        0.0
    };
    for n in 0..ops {
        ratio[n] = p(op_param(n, param::FMX_RATIO)) / 100.0;
        let mut level = p(op_param(n, param::FMX_LEVEL));
        let env = p(op_param(n, param::FMX_ENV));
        if env > 0.0 {
            // 出だしで足す量は、鳴らしてからの秒数で減衰させる(状態を持たない)
            let tau_s = (p(op_param(n, param::FMX_DECAY)) * 0.01).max(0.01);
            level += env * m::exp(-md.t / tau_s);
        }
        index[n] = (level / 10.0 + lfo_depth).max(0.0);
        amp[n] = level / 100.0;
        det_cents[n] = p(op_param(n, param::FMX_DET)) - 100.0;
    }

    let fb_amount = p(param::FMX_FB as usize) / 100.0 * FM_FB_MAX;
    let uni = (params[param::FM_UNI as usize] as usize).clamp(1, FM_MAX_UNISON);
    let uni_cents = p(param::FM_DET as usize) * 0.6;
    let drift = p(param::FM_DRIFT as usize) / 100.0 * FM_DRIFT_CENTS;
    let width = p(param::WIDTH as usize) / 100.0;
    let carriers = alg.carriers.count_ones().max(1) as f32;
    let carrier_norm = 1.0 / carriers.sqrt();

    let (mut l, mut r) = (0.0, 0.0);
    for v in 0..uni {
        let (spread, pan, mix) = supersaw_voice(uni, v);
        let mut cents = spread * uni_cents;
        if drift > 0.0 {
            cents += drift * fm_drift(v, md.t);
        }
        let dtv = if cents == 0.0 {
            dt
        } else {
            dt * m::exp2(cents / 1200.0)
        };
        let mut out = [0.0f32; STATE_OPS];
        for &o in &alg.order[..ops] {
            let n = o as usize;
            let mut input = 0.0;
            for j in 0..ops {
                if alg.mods_in[n] & (1 << j) != 0 {
                    input += index[j] * out[j];
                }
            }
            if n == alg.fb_op as usize && fb_amount > 0.0 {
                input += fb_amount * state.fb[v];
            }
            out[n] = m::sin(state.phase[v][n] * tau + input);
            if n == alg.fb_op as usize {
                // 帰還は前の 2 つの出力の平均で戻す(大きい帰還でも暴れにくい)
                state.fb[v] = (state.fb[v] + out[n]) * 0.5;
            }
        }
        let mut sum = 0.0;
        for n in 0..ops {
            if alg.carriers & (1 << n) != 0 {
                sum += out[n] * amp[n];
            }
            let step = if det_cents[n] == 0.0 {
                dtv * ratio[n]
            } else {
                dtv * ratio[n] * m::exp2(det_cents[n] / 1200.0)
            };
            dsp::advance(&mut state.phase[v][n], step.min(0.49));
        }
        let x = sum * carrier_norm * mix;
        let pan = pan * width;
        l += x * (1.0 - pan).min(1.0);
        r += x * (1.0 + pan).min(1.0);
    }
    if uni == 1 {
        (l, r)
    } else {
        let norm = 1.0 / (uni as f32).sqrt();
        (l * norm, r * norm)
    }
}