pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! 音色エンベロープ(`@duty`)のバイナリ対応:拡張ヘッダーの音色エンベロープ表と `DUTY` 命令。
//! SCC(音色番号で波形が変わるので、音で違いが分かる)で、`Sequencer` が `Player` と
//! サンプル単位で同じ音を出すこと(ループの復元・解除・余韻を含む)と、壊れた表を断ることを確かめる。
#![cfg(feature = "scc")]

use std::sync::Arc;

use pikopiko::export::binary::{encode, EncodeError};
use pikopiko::synth::scc::{scc_config, SccSynth};
use pikopiko::synth::{compile as compile_all, player};
use pikopiko::{Command, Song};
use pikopiko_runtime::binary::{ext, ext_byte, DecodeError, Sequencer};

const SR: u32 = 22_050;

fn compile(src: &str) -> Song {
    let (song, d) = compile_all(src);
    song.unwrap_or_else(|| panic!("{d:?}"))
}

fn render_player(song: &Song, frames: usize, loops: Option<u32>) -> Vec<[f32; 2]> {
    let mut p = player(Arc::new(song.clone()), SR);
    if let Some(n) = loops {
        p.handle(Command::SetLooping(true));
        p.handle(Command::SetLoopLimit(Some(n)));
    }
    let mut out = vec![[0.0f32; 2]; frames];
    p.render(&mut out);
    out
}

fn render_binary(song: &Song, frames: usize, loops: Option<u32>) -> Vec<[f32; 2]> {
    let bytes = encode(song).unwrap();
    let mut seq = Sequencer::<26>::new(&bytes, SR).unwrap();
    if let Some(n) = loops {
        seq.set_looping(true);
        seq.set_loop_limit(Some(n));
    }
    let mut synth = SccSynth::new(scc_config(&song.synth), SR, song.tracks.len());
    let mut out = vec![[0.0f32; 2]; frames];
    for chunk in out.chunks_mut(333) {
        seq.render(&mut synth, chunk);
    }
    out
}

const SONGS: &[&str] = &[
    // 段を進める。音ごとに頭から
    "@duty d = 1:3 2:3 3:3\nA t120 @duty d l4 c d e f",
    // 余韻(離したあとに別の音色へ)と、* からの繰り返し
    "@duty d = 1:3 * 2:3 / 3:4\nA t120 @duty d c4 r4 d2",
    // 解除で最後に書いた音色(@3)へ戻る
    "@duty d = 1:3 2:3\nA t120 @3 @duty d c4 @duty off d4 e4",
    // 解除で曲の既定の音色へ戻る(音色を書いていない)
    "@duty d = 1:3 2:3\nA t120 @duty d c4 @duty off d4 e4",
    // ループ:点の前で選んだものをループの頭で復元する。ループの中で解除する
    "@duty d = 1:3 2:3 3:3\nA t240 l8 @duty d c d * e f @duty off g a\nB @4 c4 * c4 r4 c4",
    "@duty d = 1:2 2:2\n@duty e = 3:2 0:2\nA t240 l8 @duty d c d * @duty e e f @duty d g",
    // 2 つのトラックで別々に
    "@duty d = 1:3 2:3\n@duty e = 3:2 0:2\nA t120 @duty d c4 d4\nB t120 @duty e e4 f4",
];

#[test]
fn binary_matches_the_player_including_loop_restore_and_off() {
    for body in SONGS {
        let src = format!("#synth scc\n{body}");
        let song = compile(&src);
        let frames = SR as usize * 6;
        let want = render_player(&song, frames, Some(2));
        let got = render_binary(&song, frames, Some(2));
        assert!(want.iter().any(|f| f[0].abs() > 0.01), "{body}");
        assert_eq!(want, got, "{body}");
    }
}

#[test]
fn duty_changes_the_sound() {
    // 音色エンベロープがバイナリでも効いている(効かなければ上の一致は意味がない)
    let with = compile("#synth scc\n@duty d = 1:3 2:3 3:3\nA t120 @duty d l4 c d e f");
    let without = compile("#synth scc\nA t120 l4 c d e f");
    let frames = SR as usize * 3;
    assert_ne!(
        render_binary(&with, frames, None),
        render_binary(&without, frames, None)
    );
}

#[test]
fn seek_restores_the_selected_duty() {
    // 2 小節目の頭から鳴らした音は、選んだあとで最初から鳴らした音と同じ(Player・バイナリとも)
    let late = compile("#synth scc\n@duty d = 1:3 2:3\nA @duty d t120 r1 c1");
    let early = compile("#synth scc\n@duty d = 1:3 2:3\nA @duty d t120 c1");
    let want = render_player(&early, 4000, None);
    assert!(want.iter().any(|f| f[0].abs() > 0.01));

    let mut p = player(Arc::new(late.clone()), SR);
    p.handle(Command::Seek(pikopiko::WHOLE_TICKS as u64));
    let mut got = vec![[0.0f32; 2]; 4000];
    p.render(&mut got);
    assert_eq!(got, want);

    let bytes = encode(&late).unwrap();
    let mut seq = Sequencer::<26>::new(&bytes, SR).unwrap();
    seq.seek(pikopiko::WHOLE_TICKS as u64);
    let mut synth = SccSynth::new(scc_config(&late.synth), SR, late.tracks.len());
    let mut got = vec![[0.0f32; 2]; 4000];
    seq.render(&mut synth, &mut got);
    assert_eq!(got, want);
}

#[test]
fn binary_header_has_a_required_duty_block() {
    let song = compile("#synth scc\n@duty d = 1:3 2:3\nA @duty d c4");
    let bytes = encode(&song).unwrap();
    // 版 1 と flags(ビット 3 = 拡張ヘッダーあり)
    assert_eq!(bytes[0], 0x18);
    let seq = Sequencer::<26>::new(&bytes, SR).unwrap();
    let h = seq.header();
    assert_eq!((h.duties, h.waves, h.extensions), (1, 0, 1));
    // 使わない曲は今までと同じ(拡張ヘッダーなし)
    let plain = encode(&compile("#synth scc\nA c4")).unwrap();
    assert_eq!(plain[0], 0x10);
    let seq = Sequencer::<26>::new(&plain, SR).unwrap();
    assert_eq!((seq.header().duties, seq.header().extensions), (0, 0));
}

#[test]
fn waves_and_duties_share_the_extension_header() {
    let wave: Vec<String> = (0..32).map(|i| (i * 4 - 64).to_string()).collect();
    let src = format!(
        "#synth scc\n@wave w = {}\n@duty d = 1:3 2:3\nA @wave w c4 @duty d d4",
        wave.join(" ")
    );
    let song = compile(&src);
    let bytes = encode(&song).unwrap();
    let seq = Sequencer::<26>::new(&bytes, SR).unwrap();
    let h = seq.header();
    assert_eq!((h.waves, h.duties, h.extensions), (1, 1, 2));
    let frames = SR as usize * 2;
    assert_eq!(
        render_player(&song, frames, None),
        render_binary(&song, frames, None)
    );
}

#[test]
fn bad_duty_data_is_refused() {
    let song = compile("#synth scc\n@duty d = 1:3 2:3\nA @duty d c4");
    let good = encode(&song).unwrap();
    // 音色エンベロープ表のブロック(数 1、番号 0x82、長さ、個数 1、段の数 2、ループなし、余韻なし、段 2 つ)
    let at = good
        .windows(7)
        .position(|w| w == [1, 0x82, 6, 1, 2, 0, 0])
        .expect("音色エンベロープ表のブロック");
    // 個数 0
    let mut b = good.clone();
    b[at + 3] = 0;
    assert_eq!(
        Sequencer::<26>::new(&b, SR).err(),
        Some(DecodeError::Header)
    );
    // 個数とブロックの長さが合わない
    let mut b = good.clone();
    b[at + 3] = 2;
    assert!(Sequencer::<26>::new(&b, SR).is_err());
    // 命令の番号が表の外(`DUTY` の引数は表の番号 + 1。2 は 1 個の表の外)
    let op = good
        .iter()
        .rposition(|&x| x == ext_byte(ext::DUTY))
        .expect("DUTY 命令");
    let mut b = good.clone();
    b[op + 1] = 2;
    assert!(Sequencer::<26>::new(&b, SR).is_err());
}

#[test]
fn too_many_duties_are_refused_by_the_encoder() {
    // MML からは作れない(コンパイラが 255 個で止める)ので、`Song` を直接ふくらませる
    let mut song = compile("#synth scc\n@duty d = 1\nA @duty d c4");
    let one = song.duties[0].clone();
    song.duties = vec![one; 256];
    assert_eq!(encode(&song), Err(EncodeError::TooManyDuties(256)));
    song.duties.truncate(255);
    assert!(encode(&song).is_ok());
}