pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! 出力の EQ の文字の書き方(`render --eq` と MCP の `render_mml` の `eq`)。
//!
//! # 何のためにあるか
//!
//! 書き出す WAV に、ゲームの再生側と同じ出力の EQ(`pikopiko::runtime::output`)をかけて、
//! 耳と数値(`render_mml` の `stats`)で確かめられるようにする。コマンドラインと AI のツールは
//! 文字でしか設定を渡せないので、その書き方をここで 1 つに決め、両方から使う。
//!
//! # 書き方
//!
//! 項目を `,` で区切って並べ、書いた順にかける(合わせて 6 バンドまで)。
//!
//! | 項目 | 意味 |
//! | --- | --- |
//! | `famicom`・`small-speaker`・`subsonic` | 用意した補正(`profile::NAMED`)。中のバンドがそのまま並ぶ |
//! | `flat` | 何もしない(項目はこれ 1 つだけのときに使う) |
//! | `lowcut1:HZ`・`highcut1:HZ` | 1 次のハイパス・ローパス |
//! | `lowcut:HZ[:Q]`・`highcut:HZ[:Q]` | 2 次のハイパス・ローパス(Q の既定は 0.707) |
//! | `lowshelf:HZ:DB`・`highshelf:HZ:DB` | 低域・高域の棚形 |
//! | `peak:HZ:DB[:Q]` | ピーキング(Q の既定は 1) |
//!
//! 例:`small-speaker`、`subsonic,highshelf:8000:-3`、`peak:2500:-4:1.5`。
//! 数の範囲の外はライブラリと同じく範囲に収める(周波数 10Hz〜サンプルレートの 0.45 倍など)。
//! 読めない項目とバンドの数の超過は誤り([`EqTextError`])にし、文は使う側が表示の言語で作る。

use pikopiko::runtime::output::{profile, Band, EqSettings, MAX_BANDS};

/// 書き方の誤り。文は持たず、使う側(CLI・MCP)が自分の `.ftl` のキーで表示の言語の文にする。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EqTextError {
    /// 読めない項目(その項目の文字)。
    Item(String),
    /// バンドが [`MAX_BANDS`] 個より多い。
    TooMany,
}

/// 書き方の例として案内する名前(用意した補正と `flat`)を `, ` でつないだもの。
pub fn names() -> String {
    let mut v: Vec<&str> = profile::NAMED.iter().map(|(n, _)| *n).collect();
    v.push("flat");
    v.join(", ")
}

/// 文字の設定を、`sample_rate` の係数にする。
pub fn parse(text: &str, sample_rate: u32) -> Result<EqSettings, EqTextError> {
    let bands = parse_bands(text)?;
    EqSettings::new(&bands, sample_rate).ok_or(EqTextError::TooMany)
}

/// 文字の設定を、バンドの並びにする(係数は作らない)。
pub fn parse_bands(text: &str) -> Result<Vec<Band>, EqTextError> {
    let items: Vec<&str> = text.split(',').map(str::trim).collect();
    if items == ["flat"] {
        return Ok(Vec::new());
    }
    let mut bands = Vec::new();
    for item in items {
        if let Some(p) = profile::by_name(item) {
            bands.extend_from_slice(p);
        } else {
            bands.push(band(item).ok_or_else(|| EqTextError::Item(item.to_string()))?);
        }
    }
    if bands.len() > MAX_BANDS {
        return Err(EqTextError::TooMany);
    }
    Ok(bands)
}

/// `種類:値:…` の 1 項目。
fn band(item: &str) -> Option<Band> {
    let mut parts = item.split(':');
    let kind = parts.next()?;
    let nums: Vec<f32> = parts
        .map(|s| s.trim().parse::<f32>().ok().filter(|v| v.is_finite()))
        .collect::<Option<_>>()?;
    let b = match (kind, nums.as_slice()) {
        ("lowcut1", &[hz]) => Band::LowCut1 { hz },
        ("highcut1", &[hz]) => Band::HighCut1 { hz },
        ("lowcut", &[hz]) => Band::LowCut { hz, q: 0.707 },
        ("lowcut", &[hz, q]) => Band::LowCut { hz, q },
        ("highcut", &[hz]) => Band::HighCut { hz, q: 0.707 },
        ("highcut", &[hz, q]) => Band::HighCut { hz, q },
        ("lowshelf", &[hz, gain_db]) => Band::LowShelf { hz, gain_db },
        ("highshelf", &[hz, gain_db]) => Band::HighShelf { hz, gain_db },
        ("peak", &[hz, gain_db]) => Band::Peak {
            hz,
            gain_db,
            q: 1.0,
        },
        ("peak", &[hz, gain_db, q]) => Band::Peak { hz, gain_db, q },
        _ => return None,
    };
    Some(b)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn profiles_and_bands_are_read_in_order() {
        assert_eq!(
            parse_bands("small-speaker").unwrap(),
            profile::SMALL_SPEAKER
        );
        assert_eq!(
            parse_bands(" subsonic , highshelf:8000:-3, peak:2500:-4:1.5 ").unwrap(),
            vec![
                Band::LowCut { hz: 30.0, q: 0.707 },
                Band::HighShelf {
                    hz: 8000.0,
                    gain_db: -3.0
                },
                Band::Peak {
                    hz: 2500.0,
                    gain_db: -4.0,
                    q: 1.5
                },
            ]
        );
        assert_eq!(parse_bands("flat").unwrap(), Vec::<Band>::new());
        assert!(parse("famicom", 44_100).is_ok());
    }

    #[test]
    fn errors_name_the_item() {
        for bad in [
            "",
            "loud",
            "peak:1000",
            "lowcut1:abc",
            "lowcut1:NaN",
            "flat,subsonic",
            "peak:1:2:3:4",
        ] {
            assert!(
                matches!(parse_bands(bad), Err(EqTextError::Item(_))),
                "{bad}"
            );
        }
        assert_eq!(
            parse_bands("famicom,famicom,lowcut1:10"),
            Err(EqTextError::TooMany)
        );
    }
}