pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! 曲の概要。耳で確かめられない利用者(生成AIなど)が数値で曲を確認するためのもの。

use crate::compiler::song::{EventKind, Song, DEFAULT_TEMPO_MILLI};

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TrackInfo {
    pub name: String,
    /// 鳴らす音の数(タイでつないだ音は1つと数える)。
    pub note_count: usize,
    /// 最も低い音と高い音(MIDIノート番号)。音がなければ `None`。
    pub lowest_key: Option<u8>,
    pub highest_key: Option<u8>,
    /// `o4c` 形式の音名。
    pub lowest_note: Option<String>,
    pub highest_note: Option<String>,
    /// 使った音色(昇順)。
    pub tones: Vec<u8>,
    /// 音に使った音量エンベロープの名前(使った順)。
    pub envelopes: Vec<String>,
    /// 最後の音が終わるtick。
    pub end_tick: u64,
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SongInfo {
    /// 使う音源の名前。
    pub synth: String,
    pub ppq: u32,
    pub length_ticks: u64,
    /// 演奏時間(秒、テンポ倍率 1.0)。
    pub duration_secs: f64,
    /// ループ点(`*`)の位置。tick と秒。
    pub loop_tick: Option<u64>,
    pub loop_secs: Option<f64>,
    /// 使ったテンポ(BPM、現れた順、重複なし)。小数のテンポ(`t128.5`)もある。
    /// JSON では、整数のテンポは整数(`120`)、小数のテンポは小数(`128.5`)で書く。
    #[cfg_attr(feature = "serde", serde(serialize_with = "ser_tempos"))]
    pub tempos: Vec<f64>,
    pub tracks: Vec<TrackInfo>,
    /// 推定した調。音の高さを持つ音がない曲では `None`。
    pub key: Option<KeyInfo>,
    /// 曲の情報(`#title` など)。JSON では、1 つも書いていなければキーを出さない。
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            skip_serializing_if = "crate::compiler::song::SongMeta::is_empty"
        )
    )]
    pub meta: crate::compiler::song::SongMeta,
    /// マーカー(`@mark`)。JSON では、なければキーを出さない。
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub markers: Vec<MarkerInfo>,
    /// 拍子(`#meter`)。JSON では、4/4(既定)ならキーを出さない。
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "is_common_time")
    )]
    pub meter: crate::compiler::song::Meter,
    /// 曲で使うショット(`@shot`)。JSON では、なければキーを出さない。
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub shots: Vec<ShotInfo>,
}

/// ショットの情報。
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShotInfo {
    pub name: String,
    /// 中身を鳴らす音源の名前。
    pub synth: String,
    /// 中身の長さ(秒。音源の余韻は含まない)。
    pub secs: f64,
    /// 鳴らすたびに音源を沈める(`duck`)。
    pub duck: bool,
    /// 鳴らす回数(ループ・マクロで繰り返す分も数える)。
    pub count: usize,
}

#[cfg(feature = "serde")]
fn is_common_time(m: &crate::compiler::song::Meter) -> bool {
    *m == crate::compiler::song::Meter::default()
}

/// マーカーの位置。
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MarkerInfo {
    pub name: String,
    pub tick: u64,
    /// 曲の頭からの秒数(テンポの変化を含む)。
    pub secs: f64,
}

/// 推定した調([`crate::composer::analysis::song_key`])。
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct KeyInfo {
    /// `C major`、`F# minor` など。
    pub name: String,
    /// 主音(`o4c` 形式ではなく音名だけ。`c`、`f+` など、MML の書き方)。
    pub tonic: String,
    pub mode: crate::composer::analysis::Mode,
    /// 確からしさ(音の分布と調の型の相関、-1〜1。0.7 を下回るときは調がはっきりしない)。
    pub confidence: f64,
}

const PC_NAMES: [&str; 12] = [
    "c", "c+", "d", "d+", "e", "f", "f+", "g", "g+", "a", "a+", "b",
];

/// MIDIノート番号を `o4c+` 形式の音名にする。
pub fn key_name(key: u8) -> String {
    let oct = key as i32 / 12 - 1;
    format!("o{}{}", oct, PC_NAMES[key as usize % 12])
}

/// tick を秒に直す(テンポ変化を考慮)。
pub fn ticks_to_secs(song: &Song, tick: u64) -> f64 {
    let mut secs = 0.0;
    let mut last = 0u64;
    let mut tempo = DEFAULT_TEMPO_MILLI;
    for e in &song.events {
        if e.tick >= tick {
            break;
        }
        if let EventKind::Tempo(t) = e.kind {
            secs += (e.tick - last) as f64 * 60_000.0 / (tempo as f64 * song.ppq as f64);
            last = e.tick;
            tempo = t;
        }
    }
    secs + (tick - last.min(tick)) as f64 * 60_000.0 / (tempo as f64 * song.ppq as f64)
}

/// 秒を tick に直す(テンポ変化を考慮、切り捨て)。曲の長さを超えたら曲の長さを返す。
pub fn secs_to_ticks(song: &Song, secs: f64) -> u64 {
    if !secs.is_finite() || secs <= 0.0 {
        return 0;
    }
    let mut elapsed = 0.0;
    let mut last = 0u64;
    let mut tempo = DEFAULT_TEMPO_MILLI;
    let per_tick = |t: u32| 60_000.0 / (t as f64 * song.ppq as f64);
    for e in &song.events {
        if let EventKind::Tempo(t) = e.kind {
            let seg = (e.tick - last) as f64 * per_tick(tempo);
            if elapsed + seg > secs {
                break;
            }
            elapsed += seg;
            last = e.tick;
            tempo = t;
        }
    }
    let t = last + ((secs - elapsed) / per_tick(tempo)).floor() as u64;
    t.min(song.length_ticks)
}

/// 曲の概要。音源の説明は内蔵の音源([`crate::synth::BUILTIN`])から探す。
/// 拡張音源の曲は [`describe_with`] で音源の一覧を渡すと、調の推定でドラムなどの音を除ける。
pub fn describe(song: &Song) -> SongInfo {
    describe_with(song, crate::synth::BUILTIN)
}

/// 曲の概要。`synths` から曲の音源の説明を探し、音の高さを持たない音色の音を調の推定から除く。
pub fn describe_with(song: &Song, synths: &[&crate::SynthSpec]) -> SongInfo {
    let spec = crate::synth::find(synths, &song.synth.name);
    let mut tracks: Vec<TrackInfo> = song
        .tracks
        .iter()
        .map(|n| TrackInfo {
            name: n.clone(),
            note_count: 0,
            lowest_key: None,
            highest_key: None,
            lowest_note: None,
            highest_note: None,
            tones: Vec::new(),
            envelopes: Vec::new(),
            end_tick: 0,
        })
        .collect();
    let n = tracks.len();
    let mut sounding = vec![false; n];
    let mut tone = vec![song.default_tone; n];
    let mut env: Vec<Option<u8>> = vec![None; n];
    let mut last_key = vec![0u8; n];
    // 曲の頭(tick 0)でテンポを指定していなければ既定テンポで始まる
    let mut tempos = Vec::new();
    if !song
        .events
        .iter()
        .any(|e| e.tick == 0 && matches!(e.kind, EventKind::Tempo(_)))
    {
        tempos.push(DEFAULT_TEMPO_MILLI);
    }
    for e in &song.events {
        let ti = e.track as usize;
        let Some(t) = tracks.get_mut(ti) else {
            continue;
        };
        match e.kind {
            EventKind::NoteOn { key, .. } => {
                if !sounding[ti] {
                    t.note_count += 1;
                }
                sounding[ti] = true;
                last_key[ti] = key;
                t.lowest_key = Some(t.lowest_key.map_or(key, |k| k.min(key)));
                t.highest_key = Some(t.highest_key.map_or(key, |k| k.max(key)));
                if !t.tones.contains(&tone[ti]) {
                    t.tones.push(tone[ti]);
                }
                if let Some(e) = env[ti].and_then(|i| song.envelopes.get(i as usize)) {
                    if !t.envelopes.contains(&e.name) {
                        t.envelopes.push(e.name.clone());
                    }
                }
            }
            EventKind::Chord { keys, .. } => {
                // 和音は 1 つの音として数え、音域には全部の音を入れる
                t.note_count += 1;
                sounding[ti] = true;
                last_key[ti] = keys.as_slice()[0];
                for &key in keys.as_slice() {
                    t.lowest_key = Some(t.lowest_key.map_or(key, |k| k.min(key)));
                    t.highest_key = Some(t.highest_key.map_or(key, |k| k.max(key)));
                }
                if !t.tones.contains(&tone[ti]) {
                    t.tones.push(tone[ti]);
                }
                if let Some(e) = env[ti].and_then(|i| song.envelopes.get(i as usize)) {
                    if !t.envelopes.contains(&e.name) {
                        t.envelopes.push(e.name.clone());
                    }
                }
            }
            EventKind::NoteOff => {
                sounding[ti] = false;
                t.end_tick = t.end_tick.max(e.tick);
            }
            EventKind::Tone(v) => tone[ti] = v,
            EventKind::Param { .. }
            | EventKind::Vibrato(_)
            | EventKind::Detune(_)
            | EventKind::Arp(_)
            | EventKind::Duty(_)
            | EventKind::Wave(_) => {}
            EventKind::Portamento { cents, .. } => {
                // 着く先の音も音域に入れる
                let key = (last_key[ti] as i32 + cents as i32 / 100).clamp(0, 127) as u8;
                t.lowest_key = Some(t.lowest_key.map_or(key, |k| k.min(key)));
                t.highest_key = Some(t.highest_key.map_or(key, |k| k.max(key)));
            }
            EventKind::Envelope(i) => env[ti] = Some(i),
            EventKind::Tempo(_) | EventKind::Shot { .. } => {}
        }
    }
    // 使ったテンポ。加速・減速(`t140,2`)の段は同じ位置(span)から続けて作られるので、
    // 続いた段はまとめて最後の段(着いた先か、打ち切られたところ)だけを入れる
    let mut run: Option<(crate::Span, u32)> = None;
    for e in &song.events {
        let EventKind::Tempo(v) = e.kind else {
            continue;
        };
        match run {
            Some((sp, _)) if sp == e.span => run = Some((sp, v)),
            _ => {
                if let Some((_, last)) = run.replace((e.span, v)) {
                    if !tempos.contains(&last) {
                        tempos.push(last);
                    }
                }
            }
        }
    }
    if let Some((_, last)) = run {
        if !tempos.contains(&last) {
            tempos.push(last);
        }
    }
    for t in &mut tracks {
        t.tones.sort_unstable();
        t.lowest_note = t.lowest_key.map(key_name);
        t.highest_note = t.highest_key.map(key_name);
    }
    SongInfo {
        synth: song.synth.name.clone(),
        ppq: song.ppq,
        length_ticks: song.length_ticks,
        duration_secs: ticks_to_secs(song, song.length_ticks),
        loop_tick: song.loop_tick,
        loop_secs: song.loop_tick.map(|t| ticks_to_secs(song, t)),
        tempos: tempos.iter().map(|&m| m as f64 / 1000.0).collect(),
        tracks,
        key: crate::composer::analysis::song_key(song, spec).map(|k| KeyInfo {
            name: k.key.name(),
            tonic: PC_NAMES[k.key.tonic as usize % 12].to_string(),
            mode: k.key.mode,
            confidence: k.confidence as f64 / 1000.0,
        }),
        meta: song.meta.clone(),
        markers: song
            .markers
            .iter()
            .map(|m| MarkerInfo {
                name: m.name.clone(),
                tick: m.tick,
                secs: ticks_to_secs(song, m.tick),
            })
            .collect(),
        meter: song.meter,
        shots: song
            .shots
            .iter()
            .enumerate()
            .map(|(i, s)| ShotInfo {
                name: s.name.clone(),
                synth: s.song.synth.name.clone(),
                secs: ticks_to_secs(&s.song, s.song.length_ticks),
                duck: s.duck,
                count: song
                    .events
                    .iter()
                    .filter(|e| matches!(e.kind, EventKind::Shot { id, .. } if id as usize == i))
                    .count(),
            })
            .collect(),
    }
}

/// テンポの並びを JSON に書く。整数のテンポは整数(`120`)、小数のテンポは小数(`128.5`)。
#[cfg(feature = "serde")]
fn ser_tempos<S: serde::Serializer>(v: &[f64], s: S) -> Result<S::Ok, S::Error> {
    use serde::ser::SerializeSeq;
    let mut seq = s.serialize_seq(Some(v.len()))?;
    for &t in v {
        if t.fract() == 0.0 && (0.0..=u32::MAX as f64).contains(&t) {
            seq.serialize_element(&(t as u32))?;
        } else {
            seq.serialize_element(&t)?;
        }
    }
    seq.end()
}