pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! 機械可読の報告(`serde` 機能)。CLI の `--json` と MCP サーバーが同じ JSON を返すための共通部品。

use std::borrow::Cow;

use serde::Serialize;

use crate::compiler::diagnostic::{Diagnostic, Severity};
use crate::synth::{OptionKind, Scope, SynthSpec};

/// 検査の結果(`pikopiko check --json`、MCP の `check_mml`)。
///
/// JSON は `ok`・`errors`・`warnings`・`diagnostics` の順。診断の `message` は `lang` の言語
/// ([`CheckReport::in_lang`]、既定は英語)。`lang` そのものは JSON に出さない。
#[derive(Debug, Clone, PartialEq)]
pub struct CheckReport {
    /// エラーがなく、曲として鳴らせる。
    pub ok: bool,
    pub errors: usize,
    pub warnings: usize,
    pub diagnostics: Vec<Diagnostic>,
    /// 診断の `message` の言語。
    pub lang: &'static str,
    /// 使う側が作った診断の文([`CheckReport::with_messages`])。空なら `lang` の言語で表から作る。
    pub messages: Vec<String>,
}

impl CheckReport {
    /// 診断から報告を作る。`ok` は「エラーが1つもない」こと。`message` は言語を指定しないときの
    /// 言語(英語)。表示の言語にするには [`CheckReport::in_lang`]。
    pub fn new(diagnostics: Vec<Diagnostic>) -> Self {
        let errors = diagnostics
            .iter()
            .filter(|d| d.severity == Severity::Error)
            .count();
        CheckReport {
            ok: errors == 0,
            errors,
            warnings: diagnostics.len() - errors,
            diagnostics,
            lang: crate::text::DEFAULT_LANG,
            messages: Vec::new(),
        }
    }

    /// 診断の `message` を `lang` の言語にする(`key`・`args` は言語によらない)。
    pub fn in_lang(mut self, lang: &'static str) -> Self {
        self.lang = lang;
        self
    }

    /// 診断の `message` を `f` で作る(使う側の訳で上書きするとき。`key`・`args` は言語によらない)。
    pub fn with_messages(mut self, mut f: impl FnMut(&Diagnostic) -> String) -> Self {
        self.messages = self.diagnostics.iter().map(&mut f).collect();
        self
    }
}

impl Serialize for CheckReport {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use serde::ser::{SerializeSeq, SerializeStruct};
        struct Diags<'a>(&'a [Diagnostic], &'a str, &'a [String]);
        impl Serialize for Diags<'_> {
            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
                let mut seq = s.serialize_seq(Some(self.0.len()))?;
                for (i, d) in self.0.iter().enumerate() {
                    let l = d.in_lang(self.1);
                    match self.2.get(i) {
                        Some(m) => seq.serialize_element(&l.with_message(m))?,
                        None => seq.serialize_element(&l)?,
                    }
                }
                seq.end()
            }
        }
        let mut st = s.serialize_struct("CheckReport", 4)?;
        st.serialize_field("ok", &self.ok)?;
        st.serialize_field("errors", &self.errors)?;
        st.serialize_field("warnings", &self.warnings)?;
        st.serialize_field(
            "diagnostics",
            &Diags(&self.diagnostics, self.lang, &self.messages),
        )?;
        st.end()
    }
}

/// 音源の説明(`pikopiko synths --json`、MCP の `list_synths`)。
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SynthDescription {
    pub name: &'static str,
    pub aliases: &'static [&'static str],
    pub description: Cow<'static, str>,
    pub max_tracks: usize,
    /// 1 トラックで同時に鳴らせる音の数(和音 `'c e g'` の音の数の上限)。
    pub polyphony: u8,
    pub default_tone: u8,
    pub tones: Vec<ToneDescription>,
    pub params: Vec<ParamDescription>,
    pub options: Vec<OptionDescription>,
    /// 音色のプリセット(`$名前` のマクロとして使う)。
    pub presets: Vec<PresetDescription>,
    /// 音色を大まかに寄せるつまみ([`crate::synth::Knob`])。なければ空。
    pub knobs: Vec<KnobDescription>,
    /// 組み込みの音色集の音色(`#include` の `file` を書き、トラックで `$名前` と呼ぶ)。なければ空。
    pub library: Vec<LibraryToneDescription>,
}

/// 音色集(`#include "@va/bass"`)の音色 1 つ。
///
/// 中身(`@n %…`)は載せない:音色集が育つと一覧が長くなりすぎ、AI は名前と種類と説明で選んで
/// `#include` と `$名前` を書けば足りるため(中身はファイルを開けば読める)。
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct LibraryToneDescription {
    pub name: &'static str,
    pub kind: &'static str,
    /// `#include` に書く名前(`@va/bass`)。
    pub file: String,
    pub description: Cow<'static, str>,
}

/// 音源の大まかなつまみ([`crate::synth::Knob`])。
///
/// AI(MCP の `list_synths`)と人(CLI の `synths`)に、つまみの意味と中身を同じ形で見せる。
/// `targets` を載せるのは、AI が `%名前=値` を自分で書くときにも、どのパラメータをどの向きに
/// 動かせばよいかが分かるようにするため(つまみで直すときは `edit_timbre` が計算する)。
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct KnobDescription {
    pub name: &'static str,
    /// 表示名(「明るさ」など)。
    pub label: Cow<'static, str>,
    /// 何を動かすか。
    pub description: Cow<'static, str>,
    /// 動かすパラメータと 1 段あたりの変化量。段は `-steps`〜`+steps`。
    pub targets: Vec<KnobTarget>,
    /// 段の最大([`crate::synth::KNOB_STEPS`])。
    pub steps: i32,
}

/// つまみが動かすパラメータ 1 つ。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct KnobTarget {
    pub param: &'static str,
    pub per_step: i32,
}

/// 音源の音色のプリセット。`macro` の行を曲の先頭に書き、トラックで `$名前` と呼ぶ。
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PresetDescription {
    pub name: &'static str,
    pub kind: &'static str,
    pub description: Cow<'static, str>,
    /// 曲の先頭に書くマクロの定義(`$名前 = 中身`)。
    #[serde(rename = "macro")]
    pub macro_line: String,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ToneDescription {
    pub id: u8,
    pub description: Cow<'static, str>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ParamDescription {
    pub name: &'static str,
    pub min: u32,
    pub max: u32,
    pub default: u32,
    pub scope: Scope,
    pub description: Cow<'static, str>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct OptionDescription {
    pub name: &'static str,
    /// 使える値(範囲なら `0〜16`、選択肢なら `a / b / c`)。
    pub values: String,
    pub default: &'static str,
    pub description: Cow<'static, str>,
}

fn option_values(k: &OptionKind, range: &str) -> String {
    match k {
        OptionKind::Range { min, max } => format!("{min}{range}{max}"),
        OptionKind::Choice(c) => c.join(" / "),
    }
}

/// 音源の一覧を報告の形にする(説明は既定の言語)。
pub fn synth_catalog(synths: &[&SynthSpec]) -> Vec<SynthDescription> {
    synth_catalog_in(synths, crate::text::DEFAULT_LANG)
}

/// 音源の一覧を報告の形にする。説明は `lang` の文(各音源の表。なければ基準の英語)。
/// 範囲の区切りも表の `term-range` で引く。
pub fn synth_catalog_in(synths: &[&SynthSpec], lang: &str) -> Vec<SynthDescription> {
    synth_catalog_with(synths, lang, &mut |_| None)
}

/// [`synth_catalog_in`] で、説明の文をキー(`synth::text_key` の形)で先に `text` から引く。`text` が
/// `None` を返したキーは音源の表の文。使う側が自分の訳で上書き・追加するときに使う。
pub fn synth_catalog_with(
    synths: &[&SynthSpec],
    lang: &str,
    text: &mut dyn FnMut(&str) -> Option<String>,
) -> Vec<SynthDescription> {
    let range: Cow<'static, str> = match text("term-range") {
        Some(t) => Cow::Owned(t),
        None => match crate::compiler::diagnostic::lookup(lang, "term-range") {
            Some([crate::text::Seg::Lit(t)]) => Cow::Borrowed(t),
            _ => Cow::Borrowed("-"),
        },
    };
    use crate::synth::text_key;
    let mut pick = |key: String, own: &'static str| -> Cow<'static, str> {
        match text(&key) {
            Some(t) => Cow::Owned(t),
            None => Cow::Borrowed(own),
        }
    };
    synths
        .iter()
        .map(|c| SynthDescription {
            name: c.name,
            aliases: c.aliases,
            description: pick(text_key::synth(c.name), c.description(lang)),
            max_tracks: c.max_tracks,
            polyphony: c.polyphony,
            default_tone: c.default_tone,
            tones: c
                .tones
                .iter()
                .map(|t| ToneDescription {
                    id: t.id,
                    description: pick(text_key::tone(c.name, t.id), c.tone_description(t.id, lang)),
                })
                .collect(),
            params: c
                .params
                .iter()
                .map(|p| ParamDescription {
                    name: p.name,
                    min: p.min,
                    max: p.max,
                    default: p.default,
                    scope: p.scope,
                    description: pick(
                        text_key::param(c.name, p.name),
                        c.param_description(p.name, lang),
                    ),
                })
                .collect(),
            options: c
                .options
                .iter()
                .map(|o| OptionDescription {
                    name: o.name,
                    values: option_values(&o.kind, &range),
                    default: o.default,
                    description: pick(
                        text_key::option(c.name, o.name),
                        c.option_description(o.name, lang),
                    ),
                })
                .collect(),
            presets: c
                .presets
                .iter()
                .map(|p| PresetDescription {
                    name: p.name,
                    kind: p.kind,
                    description: pick(
                        c.preset_text_key(p.name),
                        c.preset_description(p.name, lang),
                    ),
                    macro_line: p.macro_line(),
                })
                .collect(),
            knobs: c
                .knobs
                .iter()
                .map(|k| KnobDescription {
                    name: k.name,
                    label: pick(text_key::knob(c.name, k.name), c.knob_label(k.name, lang)),
                    description: pick(
                        text_key::knob_help(c.name, k.name),
                        c.knob_description(k.name, lang),
                    ),
                    targets: k
                        .targets
                        .iter()
                        .map(|&(param, per_step)| KnobTarget { param, per_step })
                        .collect(),
                    steps: crate::synth::KNOB_STEPS,
                })
                .collect(),
            library: crate::synth::tones::tones(c)
                .into_iter()
                .map(|t| LibraryToneDescription {
                    name: t.name,
                    kind: t.kind,
                    file: t.path(),
                    description: pick(t.text_key(), c.library_description(t.name, lang)),
                })
                .collect(),
        })
        .collect()
}

/// イベント列バイナリの大きさの内訳(`pikopiko build --json`、MCP の `build_mml`)。
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BuildSizes {
    pub total: usize,
    pub header: usize,
    /// ヘッダーのうちエンベロープ表のバイト数。
    pub envelopes: usize,
    /// トラック名とバイト数。
    pub tracks: Vec<(String, usize)>,
    /// 後方参照を使わなかった場合のバイト数。
    pub uncompressed: usize,
}

impl BuildSizes {
    pub fn new(song: &crate::Song, stats: &crate::export::binary::EncodeStats) -> Self {
        BuildSizes {
            total: stats.total,
            header: stats.header,
            envelopes: stats.envelopes,
            tracks: song
                .tracks
                .iter()
                .cloned()
                .zip(stats.tracks.iter().copied())
                .collect(),
            uncompressed: stats.header + stats.uncompressed.iter().sum::<usize>(),
        }
    }
}

/// 書き出した波形の統計。耳で確かめられないAIが、無音や割れに気づくためのもの。
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct AudioStats {
    /// 最大振幅(0.0〜1.0)。
    pub peak: f32,
    /// 全体の実効値(RMS)。
    pub rms: f32,
    /// ±1.0 に張り付いた(割れた)フレームの数。
    pub clipped_frames: usize,
    /// まったく鳴っていない。
    pub silent: bool,
    /// 最初に音が出るまでの無音(秒)。
    pub silent_head_secs: f64,
    /// 最後に音が消えてからの無音(秒)。
    pub silent_tail_secs: f64,
}

/// 無音とみなす振幅。
const SILENCE: f32 = 1e-3;

/// 波形の統計を取る。
pub fn audio_stats(samples: &[[f32; 2]], sample_rate: u32) -> AudioStats {
    let mut peak = 0.0f32;
    let mut sum_sq = 0.0f64;
    let mut clipped = 0usize;
    let mut first: Option<usize> = None;
    let mut last = 0usize;
    for (i, f) in samples.iter().enumerate() {
        let m = f[0].abs().max(f[1].abs());
        peak = peak.max(m);
        sum_sq += f64::from(f[0]).powi(2) + f64::from(f[1]).powi(2);
        if m >= 1.0 {
            clipped += 1;
        }
        if m > SILENCE {
            first.get_or_insert(i);
            last = i;
        }
    }
    let rms = if samples.is_empty() {
        0.0
    } else {
        (sum_sq / (samples.len() as f64 * 2.0)).sqrt() as f32
    };
    let sr = f64::from(sample_rate.max(1));
    match first {
        None => AudioStats {
            peak,
            rms,
            clipped_frames: clipped,
            silent: true,
            silent_head_secs: samples.len() as f64 / sr,
            silent_tail_secs: 0.0,
        },
        Some(f) => AudioStats {
            peak,
            rms,
            clipped_frames: clipped,
            silent: false,
            silent_head_secs: f as f64 / sr,
            silent_tail_secs: (samples.len() - 1 - last) as f64 / sr,
        },
    }
}

/// AI に渡すツールの説明文と使い方の案内。MCP サーバー(`pikopiko-mcp`)が使い、
/// AI と連携する他のツールも同じ文を使える。文は `locales/tools-<言語>.ftl` にある
/// (ビルドのときに表になる)。言語で選ぶときは [`tools::for_lang`]。
pub mod tools {
    /// ツールの説明文と案内の一揃い(1 つの言語の分)。
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct Texts {
        pub get_spec: &'static str,
        pub list_synths: &'static str,
        pub check_mml: &'static str,
        pub describe_mml: &'static str,
        pub build_mml: &'static str,
        pub render_mml: &'static str,
        /// 音色を直す(置き場所の一覧・候補への差し替え・つまみ・パラメータ)。
        pub edit_timbre: &'static str,
        /// 音色を試聴フレーズで鳴らして測る。
        pub measure_tone: &'static str,
        /// 組み込みの音色集の 1 ファイルの中身を読む。
        pub get_tones: &'static str,
        /// MML を整形する。
        pub format_mml: &'static str,
        /// 使い方の案内(MCP サーバーの instructions)。
        pub guide: &'static str,
    }

    /// 表のキーの文(値の場所のない文。`lang` になければ基準の英語、それもなければ空)。
    fn get(key: &str, lang: &str) -> &'static str {
        match crate::compiler::diagnostic::lookup(lang, key) {
            Some([crate::text::Seg::Lit(t)]) => t,
            _ => "",
        }
    }

    /// 言語タグ(`en`・`ja` など)に合う一揃い(言語の部分で選ぶ。表にない言語は英語)。
    pub fn for_lang(lang: &str) -> Texts {
        let lang = if crate::is_japanese(lang) { "ja" } else { "en" };
        Texts {
            get_spec: get("tool-get-spec", lang),
            list_synths: get("tool-list-synths", lang),
            check_mml: get("tool-check-mml", lang),
            describe_mml: get("tool-describe-mml", lang),
            build_mml: get("tool-build-mml", lang),
            render_mml: get("tool-render-mml", lang),
            edit_timbre: get("tool-edit-timbre", lang),
            measure_tone: get("tool-measure-tone", lang),
            get_tones: get("tool-get-tones", lang),
            format_mml: get("tool-format-mml", lang),
            guide: get("tool-guide", lang),
        }
    }

    /// ツールの引数 `name`(`mml`・`include_hex` など)の説明。表になければ `None`。
    pub fn param(name: &str, lang: &str) -> Option<&'static str> {
        let lang = if crate::is_japanese(lang) { "ja" } else { "en" };
        let t = get(&format!("tool-param-{}", name.replace('_', "-")), lang);
        (!t.is_empty()).then_some(t)
    }
}