pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! Yamaha DX7 のパッチ(SysEx)を、`va` の多オペレーター FM(`@15`)の音色(MML のマクロ 1 行)に変える。
//!
//! 何のためにあるか:DX7 の音色は公開・配布されたものが非常に多く、`@15` の 6 オペレーター・32 アルゴリズム
//! (`fmx_algo` 32〜63 が DX7 の 1〜32 番)に載せれば、ベルや電気ピアノなどの音の骨格をそのまま使える。
//! 作る側(人や AI)が 33 個のパラメータを書かずに済む、「書きやすさの対策」の延長。
//!
//! 読めるもの:32 ボイスのバルクダンプ(SysEx 4104 バイト、または頭と終わりのない 4096 バイト)、
//! 1 ボイスのダンプ(SysEx 163 バイト、または 155 バイト)、詰めた 1 ボイス(128 バイト)。チェックサムは見ない
//! (壊れたデータは値の範囲で弾く)。
//!
//! 変換は近似で、音は DX7 とは同じにならない。取り込むのは、アルゴリズム・帰還・オペレーターごとの周波数
//! (粗調整・微調整・固定周波数)・ずれ・出力レベル・エンベロープ(出だしの高さと減衰)だけ。キースケーリング・
//! ベロシティ感度・ピッチエンベロープ・LFO・トランスポーズは取り込まない(出力の注釈に残す)。
//! 4 番・6 番のアルゴリズムの別オペレーターへ戻る帰還は、6 番の自己帰還で近似する。
//!
//! ```
//! use pikopiko::synth::va::dx7;
//! let mut packed = [0u8; 128];
//! packed[14] = 99; // OP6 の出力レベル(先頭のブロックが OP6)
//! packed[118..128].copy_from_slice(b"INIT VOICE");
//! let voices = dx7::parse_sysex(&packed).unwrap();
//! assert_eq!(voices[0].name, "INIT VOICE");
//! assert!(dx7::to_mml(&voices[0], "init_voice").contains("@15 %fmx_ops=6"));
//! ```

/// DX7 のオペレーター 1 つ分(取り込む項目だけ)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dx7Op {
    /// エンベロープの速さ R1〜R4(0〜99)。
    pub rates: [u8; 4],
    /// エンベロープの高さ L1〜L4(0〜99)。
    pub levels: [u8; 4],
    /// 出力レベル(0〜99)。
    pub output_level: u8,
    /// 固定周波数のオペレーターか(鳴らす高さに追従しない)。
    pub fixed: bool,
    /// 周波数の粗調整(0〜31。比率のときは 0 が 0.5 倍)。
    pub coarse: u8,
    /// 周波数の微調整(0〜99)。
    pub fine: u8,
    /// 音程のずれ(0〜14、7 がずれなし)。
    pub detune: u8,
}

/// DX7 のボイス 1 つ分。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dx7Voice {
    /// ボイス名(最大 10 文字)。
    pub name: String,
    /// アルゴリズム(0〜31。DX7 の表示は 1〜32)。
    pub algorithm: u8,
    /// 帰還の量(0〜7)。
    pub feedback: u8,
    /// トランスポーズ(0〜48、24 が C3 = ずれなし)。取り込まない。
    pub transpose: u8,
    /// オペレーター。0 番目が DX7 の OP1(一番下のキャリア)。
    pub ops: [Dx7Op; 6],
}

/// DX7 のデータを読めなかった理由。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dx7Error {
    /// DX7 のバルクダンプ・1 ボイスのダンプ・詰めた 1 ボイスのどれでもない(大きさや SysEx の頭が合わない)。
    Unrecognized,
    /// 値が DX7 の範囲の外(`voice` は 0 から数えたボイスの番号)。
    BadValue {
        /// 壊れていたボイスの番号(0 から)。
        voice: usize,
    },
}

impl crate::text::Localized for Dx7Error {
    fn text_key(&self) -> &'static str {
        match self {
            Dx7Error::Unrecognized => "err-dx7-unrecognized",
            Dx7Error::BadValue { .. } => "err-dx7-bad-value",
        }
    }

    fn text_args(&self, f: &mut dyn FnMut(&'static str, crate::text::TextArg<'_>)) {
        if let Dx7Error::BadValue { voice } = self {
            f("voice", crate::text::TextArg::Int(*voice as i64 + 1));
        }
    }

    fn catalogs(&self) -> &'static [crate::text::Catalog] {
        crate::synth::va::text_table::CATALOGS
    }
}

impl core::fmt::Display for Dx7Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        crate::text::write_localized(f, self, crate::text::DEFAULT_LANG)
    }
}

impl std::error::Error for Dx7Error {}

/// 詰めた 1 ボイスの大きさ(バイト)。
const PACKED: usize = 128;
/// 1 ボイスのダンプ(詰めていない)の大きさ。
const SINGLE: usize = 155;
/// ボイスの数(バルクダンプ)。
const BANK: usize = 32;

/// SysEx(またはその中身)から全ボイスを読む。32 ボイスのバルクダンプは 32 個、そのほかは 1 個を返す。
pub fn parse_sysex(bytes: &[u8]) -> Result<Vec<Dx7Voice>, Dx7Error> {
    let sysex_ok = |len: usize, sub: u8| {
        bytes.len() == len
            && bytes[0] == 0xF0
            && bytes[1] == 0x43
            && bytes[2] & 0xF0 == 0x00
            && bytes[3] == sub
            && bytes[len - 1] == 0xF7
    };
    if sysex_ok(6 + PACKED * BANK + 2, 0x09) {
        return packed_bank(&bytes[6..6 + PACKED * BANK]);
    }
    if sysex_ok(6 + SINGLE + 2, 0x00) {
        return Ok(vec![unpacked(&bytes[6..6 + SINGLE], 0)?]);
    }
    match bytes.len() {
        l if l == PACKED * BANK => packed_bank(bytes),
        PACKED => Ok(vec![packed(bytes, 0)?]),
        SINGLE => Ok(vec![unpacked(bytes, 0)?]),
        _ => Err(Dx7Error::Unrecognized),
    }
}

fn packed_bank(data: &[u8]) -> Result<Vec<Dx7Voice>, Dx7Error> {
    data.chunks(PACKED)
        .enumerate()
        .map(|(i, c)| packed(c, i))
        .collect()
}

/// 名前の 10 文字(表示できない文字は空白にして、前後の空白を除く)。
fn name_of(b: &[u8]) -> String {
    let s: String = b
        .iter()
        .map(|&c| {
            if (0x20..0x7F).contains(&c) {
                c as char
            } else {
                ' '
            }
        })
        .collect();
    s.trim().to_string()
}

fn check(voice: usize, values: &[u8], max: u8) -> Result<(), Dx7Error> {
    if values.iter().any(|&v| v > max) {
        Err(Dx7Error::BadValue { voice })
    } else {
        Ok(())
    }
}

/// 詰めた形式(128 バイト。先頭のブロックが OP6)。
fn packed(b: &[u8], voice: usize) -> Result<Dx7Voice, Dx7Error> {
    let mut ops: Vec<Dx7Op> = Vec::with_capacity(6);
    for i in 0..6 {
        let o = &b[i * 17..i * 17 + 17];
        check(voice, &o[0..8], 99)?;
        check(voice, &o[14..15], 99)?;
        check(voice, &o[16..17], 99)?;
        let op = Dx7Op {
            rates: [o[0], o[1], o[2], o[3]],
            levels: [o[4], o[5], o[6], o[7]],
            output_level: o[14],
            fixed: o[15] & 1 == 1,
            coarse: (o[15] >> 1) & 0x1F,
            fine: o[16],
            detune: ((o[12] >> 3) & 0x0F).min(14),
        };
        ops.push(op);
    }
    ops.reverse(); // OP6 から並んでいるのを OP1 から並べる
    Ok(Dx7Voice {
        name: name_of(&b[118..128]),
        algorithm: b[110] & 0x1F,
        feedback: b[111] & 0x07,
        transpose: b[117].min(48),
        ops: ops.try_into().expect("6 operators"),
    })
}

/// 詰めていない形式(155 バイト。先頭のブロックが OP6)。
fn unpacked(b: &[u8], voice: usize) -> Result<Dx7Voice, Dx7Error> {
    let mut ops: Vec<Dx7Op> = Vec::with_capacity(6);
    for i in 0..6 {
        let o = &b[i * 21..i * 21 + 21];
        check(voice, &o[0..8], 99)?;
        check(voice, &o[16..17], 99)?;
        check(voice, &o[19..20], 99)?;
        check(voice, &o[20..21], 14)?;
        ops.push(Dx7Op {
            rates: [o[0], o[1], o[2], o[3]],
            levels: [o[4], o[5], o[6], o[7]],
            output_level: o[16],
            fixed: o[17] & 1 == 1,
            coarse: o[18] & 0x1F,
            fine: o[19],
            detune: o[20],
        });
    }
    ops.reverse();
    Ok(Dx7Voice {
        name: name_of(&b[145..155]),
        algorithm: b[134] & 0x1F,
        feedback: b[135] & 0x07,
        transpose: b[144].min(48),
        ops: ops.try_into().expect("6 operators"),
    })
}

/// DX7 のアルゴリズム `algorithm`(0〜31)のキャリアの集合(ビット `n` がオペレーター `n + 1`)。
pub fn carriers(algorithm: u8) -> u8 {
    crate::synth::va::engine::dx7_carrier_mask(algorithm)
}

/// DX7 の出力レベル・エンベロープの高さ(0〜99)を、0〜1 の振幅にする。99 が 1 で、1 段で約 0.75 dB。
/// 20 より下は、さらに直線で 0 へ下げる(DX7 の下の方が急に落ちる性質の近似)。
fn amp(level: u8) -> f32 {
    if level == 0 {
        return 0.0;
    }
    let a = 10f32.powf(-(99.0 - level as f32) * 0.75 / 20.0);
    if level < 20 {
        a * level as f32 / 20.0
    } else {
        a
    }
}

/// DX7 のエンベロープの速さ(0〜99)を、60dB 減衰する時間(秒)にする(99 で約 0.02 秒、9 下がるごとに 2 倍)。
fn t60(rate: u8) -> f32 {
    0.02 * 2f32.powf((99.0 - rate as f32) / 9.0)
}

/// ボイス名から MML のマクロ名(小文字の英数字と `_`)を作る。使える文字がなければ `dx7_voice`。
pub fn macro_name(name: &str) -> String {
    let mut s = String::new();
    for c in name.chars() {
        if c.is_ascii_alphanumeric() {
            s.push(c.to_ascii_lowercase());
        } else if !s.ends_with('_') && !s.is_empty() {
            s.push('_');
        }
    }
    let s = s.trim_end_matches('_').to_string();
    if s.is_empty() {
        "dx7_voice".to_string()
    } else if s.starts_with(|c: char| c.is_ascii_digit()) {
        format!("dx7_{s}")
    } else {
        s
    }
}

/// ボイスを `va` の MML の音色(注釈の行と、マクロ 1 行)にする。`name` は `$` の後ろのマクロ名。
pub fn to_mml(v: &Dx7Voice, name: &str) -> String {
    let mask = carriers(v.algorithm);
    let n_carriers = mask.count_ones().max(1);
    let mut notes: Vec<String> = Vec::new();
    let mut s = format!(
        "${name} = @15 %fmx_ops=6 %fmx_algo={} %fmx_fb={}",
        32 + v.algorithm as u32,
        (v.feedback as u32 * 100 + 3) / 7
    );
    let mut release = 0.0f32;
    for (i, op) in v.ops.iter().enumerate() {
        let n = i + 1;
        let carrier = mask & (1 << i) != 0;
        // 比(0.01 単位)。固定周波数は、C4 に対する比に直す(鳴らす高さへの追従はなくなる)
        let ratio = if op.fixed {
            let hz = 10f32.powi((op.coarse & 3) as i32) * (1.0 + op.fine as f32 * 0.0088);
            notes.push(format!(
                "OP{n} は固定周波数({hz:.0} Hz)。比に直したので高さに追従する"
            ));
            hz / 261.63
        } else {
            let c = if op.coarse == 0 {
                0.5
            } else {
                op.coarse as f32
            };
            c * (1.0 + op.fine as f32 / 100.0)
        };
        let ratio_x100 = (ratio * 100.0).round().clamp(0.0, 3200.0) as u32;
        if ratio * 100.0 > 3200.0 {
            notes.push(format!("OP{n} の比 {ratio:.1} は 32 に丸めた"));
        }
        // 出力レベルと、エンベロープの出だし(L1)・保持(L3)。キャリアは音量、変調側は深さ(0.1 単位)
        let out = amp(op.output_level);
        let scale = if carrier { 100.0 } else { 130.0 };
        let steady = out * amp(op.levels[2]);
        let start = out * amp(op.levels[0]);
        if op.levels[0] < op.levels[2] {
            notes.push(format!(
                "OP{n} は出だしより保持の方が大きい(スウェル)。保持の高さで鳴らす"
            ));
        }
        let level = (steady * scale).round().clamp(0.0, 400.0) as u32;
        let boost = ((start - steady).max(0.0) * scale)
            .round()
            .clamp(0.0, 400.0) as u32;
        let decay = ((t60(op.rates[1]) / 6.9) * 100.0).round().clamp(1.0, 500.0) as u32;
        let det = (100 + (op.detune as i32 - 7) * 3 / 2).clamp(0, 200);
        s.push_str(&format!(
            " %fmx{n}_ratio={ratio_x100} %fmx{n}_level={level} %fmx{n}_env={boost} %fmx{n}_decay={decay} %fmx{n}_det={det}"
        ));
        if carrier {
            release = release.max(t60(op.rates[3]));
        }
    }
    let release_u = (release * 100.0).round().clamp(1.0, 255.0) as u32;
    let gain = (100.0 * (n_carriers as f32).sqrt())
        .round()
        .clamp(100.0, 400.0) as u32;
    s.push_str(&format!(" %release={release_u} %gain={gain}"));

    let mut out = format!(
        "; DX7 の音色 \"{}\"(アルゴリズム {}、帰還 {})。近似の取り込みで、音量は pikopiko tone で測り直す\n",
        v.name,
        v.algorithm + 1,
        v.feedback
    );
    if matches!(v.algorithm, 3 | 5) {
        notes.push(
            "アルゴリズム 4・6 の別オペレーターへ戻る帰還は、6 の自己帰還で近似した".to_string(),
        );
    }
    notes.push(
        "キースケーリング・ベロシティ感度・ピッチエンベロープ・LFO・トランスポーズは取り込まない"
            .to_string(),
    );
    for n in notes {
        out.push_str(&format!("; {n}\n"));
    }
    out.push_str(&s);
    out.push('\n');
    out
}