use std::sync::Arc;
use pikopiko::export::binary::{encode, encode_with_stats};
use pikopiko::synth::create_builtin;
use pikopiko::{compile, Command, Player};
use pikopiko_runtime::binary::{DecodeError, Sequencer};
const SR: u32 = 22_050;
fn via_player(src: &str, loops: Option<u32>, frames: usize) -> Vec<[f32; 2]> {
let song = Arc::new(compile(src).unwrap());
let mut p = Player::new(song, 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 via_binary(src: &str, loops: Option<u32>, frames: usize) -> Vec<[f32; 2]> {
let song = compile(src).unwrap();
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 = create_builtin(&song.synth, SR, song.tracks.len());
let mut out = vec![[0.0f32; 2]; frames];
for chunk in out.chunks_mut(333) {
seq.render(synth.as_mut(), chunk);
}
out
}
fn assert_same(src: &str, loops: Option<u32>) {
let frames = SR as usize * 6;
let a = via_player(src, loops, frames);
let b = via_binary(src, loops, frames);
if let Some(i) = (0..frames).find(|&i| a[i] != b[i]) {
panic!("{i} フレーム目で食い違う: {:?} / {:?}\n{src}", a[i], b[i]);
}
}
const SONGS: &[&str] = &[
"A t150 l8 o4 cdefgab>c",
"A t140 l8 o4 [cegc >c<gec]2 [fafc >c<afa]2",
"A q6 l16 c d e r e d c4 r8 c4^8 c4&c8 c4&e4 v8 g o2 c o7 c",
"A @1 o5 l8 cege\nB @3 o3 l4 c g\nC @4 o6 l16 [c r c c]2\nD @0 v15 c1",
"A t120 c4 t60 c4 t200 c4\nB r8 @1 c4 @0 d4",
"$bass = o2 l8 [c c >c< c]2\nA t140 [$bass | r4]2\nB l16 [[c d]2 e f]3",
"#synth ay pan=abc\nA t150 @0 v13 o5 l8 [c e g >c<]2\nB %env=1 %env_shape=10 %env_period=600 o3 c1\nC @1 %noise=4 v10 l16 [c r r c]4",
"#synth ym2149\nA %env=1 %env_shape=14 %env_period=300 o4 l2 c g\nB @2 %noise=20 l4 c d e",
"A l8 c d e f g a b > c d e f g a b > c d e f g a b",
"A l3 c d e l5 c d e f g l1920 c",
"A %pan=2 l8 c d %pan=14 e f\nB %pan=0 c2",
"#synth ay\nA %noise=0 @1 o4 c4 %noise=31,2 c2 c4\nB %pan=0 %pan=16,1 c1",
"#synth ay pan=abc\nA %pan=12 l8 c d e\nB @1 %pan=4 c4\nC c4 %pan=8 d4",
"@env p = 15 12 9 6 3 0\nA t150 @env p l8 o5 c d e f g r c4 q4 c4",
"@env s = 4 8 12 15 * 13 11 13 15 / 10 7 4 2 1\n@env d = 15:5 10:5 5:5\nA q6 @env s l8 c d e r c4&e4 @env d f g\nB @env d @3 o3 c2 v8 c2 @env s c4 r4",
"@env r = 15 * 12 / 8:3 4:3 0\nA l16 @env r c d e r c^16 r c4&c8 c4&e4 r8\nB @env r q4 l8 [c d]4",
"#synth ay pan=abc\n@env a = 15 13 11 9 * 8 7 / 5 3 1\nA @env a l8 c e g r\nB %env=1 %env_shape=10 @env a c2\nC @1 %noise=4 @env a l16 [c r]4",
"@env x = 15:40 3\n@env y = 2 4 8 15\nA @env x c4 @env y d4 @env x e4 r4 @env y f1",
"@vib w = 12 55 30\nA t150 @vib w l4 o4 c d e f\nB o3 c1",
"@vib w = 0 80 40\n@vib f = 6 30 15\nA @vib w l8 c d e r c4&e4 @vib f g a mpof b c",
"@detune d = 0 -20 * 20 -20\nA t120 @detune d l4 o4 a b >c<a\nB @detune d @1 o3 c2 d2",
"@detune s = 0:5 -200:5 -100 / 0:6 100:3\nA @detune s q8 l4 o4 c d e f\nB q4 l8 [c d]4",
"@env e = 15 12 9 6 3 0\n@vib w = 6 50 25\n@detune d = 0 30 * -30\nA @env e @vib w @detune d l8 c d e f g r c4&c8 c4\nB @vib w @1 c2 ep d epof c2",
"#synth ay pan=abc\n@vib w = 8 60 20\n@detune d = 0 -10\nA @vib w @detune d t150 l8 [c e g >c<]2\nB @vib w @1 o3 c1\nC @detune d @0 v10 l16 [c r c c]4",
"#synth ym2149\n@vib w = 4 70 35\nA @vib w t200 l8 o5 c d e f g a b >c",
"@vib w = 0 50 20\nA t200 l16 @vib w c d e f mpof g a b >c< mp w d e",
"A t150 l8 o4 {c e}4 g {g >c}2 r2 {e c}4^4",
"A t120 q4 l8 {c g}4 {a <a}4 c4\nB @1 o3 {g c}2 {c e}8 c r4 {e g}1",
"@vib w = 6 50 25\n@detune d = 0 30 * -30\n@env e = 15 12 9 6 3 0\nA @env e @vib w @detune d t140 l8 {c >c}4 {d g}4^8 {e c}2\nB @vib w {g <g}1",
"#synth ay pan=abc\nA t150 l8 o4 {c g}4 {a e}4^4 {c >c}2\nB @1 o3 {g c}2 {e c}2\nC @1 %noise=4 v10 l16 [c r c c]4",
"#synth ym2149\nA t200 l8 o5 {c >c}2 {g c}4 d4",
"A t60 {c e}1\nB r4 t120 c\nC t90 r2 {c g}2",
"A t30 o0 {c >>>>>>>>>c}1",
"@arp m = * 0:2 4:2 7:2\nA t150 @arp m l8 o4 c d e r c4&e4 @arp off f g",
"@arp k = 12 7 3 0 / -5:4 -12:4\n@arp o = * 0:3 12:3\nA @arp k l4 c r c q4 d\nB @arp o o3 c2 en k d4 enof e4",
"@arp m = * 0:2 3:2 7:2\n@vib w = 6 50 25\n@detune d = 0 -20 * 20\n@env e = 15 12 9 6 3 0\nA @env e @vib w @detune d @arp m l8 c d {e g}4 f g\nB @arp m @1 c2",
"#synth ay pan=abc\n@arp m = * 0:2 4:2 7:2\nA @arp m t150 l8 [c e g >c<]2\nB @1 %noise=4 @arp m c2\nC %env=1 %env_shape=8 %env_period=100 @arp m o3 c1",
"#synth ym2149\n@arp d = * 24 12 0 -12 -24\nA @arp d t200 l4 o5 c d",
"A t150 l28 c d e f g a b c4 l36 c d e f g a b > c d <",
"A l14 [c e g]2 c%120\nB c%7 d%13 r%1 e%480 l28 f g",
"@arp m = * 0:2 4:2 7:2\n@env e = 15 12 9 6 3 0\nA @env e @arp m l28 c d e f g a b\nB {c e}28 l9 c d {g c}36",
"#synth ay pan=abc\nA t140 l28 c d e f g * a b c d e f g\nB @1 %noise=4 l28 c d e f g * l7 a b",
"A t128.5 l8 c d e f t97.25 g a b > c\nB t60 c1",
"A t120 c4 t60,1 c1 d4\nB l8 [c d]8 t200,2. e2",
"@vib w = 6 50 25\nA t90 @vib w {c >c}2 t180,1 {e c}1 t72.5 c4",
"A c%7 d%13 r%1 e%480 l%90 f g\nB t133 c%2000 d4^%30",
];
#[test]
fn binary_playback_matches_player() {
for src in SONGS {
assert_same(src, None);
}
}
const LOOP_SONGS: &[&str] = &[
"A t150.5 l8 c d t200,4 e f g a * t90.75,4 c d e f t180,2 g a\nB l28 [c d e f g a b]3 * c4 c2",
"A t200 l8 c e g * a g e\nB l4 c r8 * f c",
"A t200 @1 l8 c d * @3 e f @1 g\nB r4 * c4 v6 d4",
"#synth ay\nA t240 %env=1 %env_shape=8 %env_period=200 c4 * %env_shape=12 d4 e4\nB @1 %noise=3 c4 * %noise=9 c8 c8\nC t180 c4 * d2",
"A t240 c2 * d2 e2\nB t300 l16 [c d e f]2 * [g a]4",
"A t240 l8 [c d]2 * [c d]2 [e f]2",
"A t240 c4 d4\nB c8 * c8 c4",
"#synth ay pan=acb\nA t240 %pan=0 c4 * %pan=16 d4 e4\nB %pan=3 c4 * c4 %pan=13 c4",
"@env a = 15 10 * 8 6 / 4 2\n@env b = 15:4 0\nA t240 @env a l8 c d * @env b e f @env a g\nB @env b c4 * c4 r4 c4",
"@env a = 15 12 / 9 6 3\nA t240 @env a l8 c d e f * g a b r",
"@vib w = 4 60 30\nA t240 @vib w l8 c d * e f g a\nB l8 c d * e f",
"@vib w = 4 60 30\n@detune d = 0 -15 * 15\nA t240 l8 c d @vib w @detune d e f * g a mpof b >c<\nB @detune d c2 * @vib w d4 e4",
"@vib a = 0 40 20\n@vib b = 3 90 50\nA t240 @vib a l8 c d * @vib b e f @vib a g\nB @vib b c4 * c4 r4 c4",
"@detune s = 0:4 -100:4 100 / 0:3 50:3\n@env a = 15 12 / 9 6 3\nA t240 @env a @detune s l8 c d e f * g a b r",
"A t240 l8 {c e}4 * {g c}4 d e\nB l4 c * {e g}2",
"A t240 l8 [{c g}4 d]2 * [{e c}4 f]2",
"@vib w = 4 60 30\nA t240 @vib w l8 {c e}4 * {g >c}4 <g",
"@arp m = * 0:2 4:2 7:2\n@arp n = 0 -12\nA t240 @arp m l8 c d * @arp n e f @arp m g\nB @arp n c4 * c4 enof r4 c4",
];
#[test]
fn binary_loop_playback_matches_player() {
for src in LOOP_SONGS {
assert_same(src, Some(2));
assert_same(src, None);
}
}
#[test]
fn looping_without_loop_point_returns_to_start() {
assert_same("A t300 l8 c d e", Some(3));
}
#[test]
fn short_loop_example_is_small() {
let song = compile("#synth ay\nA t140 l8 o4 [cegc >c<gec]2 [fafc >c<afa]2").unwrap();
let (bytes, stats) = encode_with_stats(&song).unwrap();
assert!(bytes.len() <= 40, "{} バイト: {stats:?}", bytes.len());
assert!(stats.tracks[0] < stats.uncompressed[0]);
assert_eq!(stats.total, bytes.len());
}
#[test]
fn header_contents() {
let song = compile("#synth ay\nA l8 c * d\nB c4").unwrap();
let bytes = encode(&song).unwrap();
let seq = Sequencer::<4>::new(&bytes, SR).unwrap();
let h = seq.header();
assert_eq!(h.synth, 1);
assert_eq!(h.tracks, 2);
assert_eq!(h.unit, 5040);
assert_eq!(h.length, 2);
assert_eq!(h.loop_at, Some(1));
}
#[test]
fn envelope_table_is_always_written() {
let plain = encode(&compile("A c d e").unwrap()).unwrap();
assert_eq!(plain[0] >> 4, 1);
let song =
compile("@env p = 15 12:20 * 9 6 / 3\n@env u = 1\nA @env p c d @env u e\nB @env p c")
.unwrap();
assert_eq!(song.envelopes.len(), 2);
let (bytes, stats) = encode_with_stats(&song).unwrap();
assert_eq!(bytes[0] >> 4, 1);
assert_eq!(stats.envelopes, 1 + (3 + 6) + (3 + 1));
let seq = Sequencer::<4>::new(&bytes, SR).unwrap();
assert_eq!(seq.header().version, 1);
assert_eq!(seq.header().envelopes, 2);
}
#[test]
fn effect_tables_are_always_written() {
let song =
compile("@vib w = 12 55 30\n@detune d = 0 -20 * 20:3 / 5\nA @vib w @detune d c d").unwrap();
assert_eq!((song.vibratos.len(), song.detunes.len()), (1, 1));
let (bytes, stats) = encode_with_stats(&song).unwrap();
assert_eq!(bytes[0] >> 4, 1);
assert_eq!(stats.effects, (1 + 3) + (1 + 3 + 4 * 3) + 1);
assert_eq!(stats.envelopes, 1); let seq = Sequencer::<4>::new(&bytes, SR).unwrap();
let h = seq.header();
assert_eq!(
(h.version, h.envelopes, h.vibratos, h.detunes, h.arps),
(1, 0, 1, 1, 0)
);
}
#[test]
fn arpeggio_table_is_part_of_the_one_format() {
let song = compile("@arp m = * 0 4 7\n@vib w = 12 55 30\nA @arp m @vib w c d").unwrap();
assert_eq!(song.arps.len(), 1);
assert_eq!(song.arps[0].steps, [(0, 1), (400, 1), (700, 1)]);
let (bytes, stats) = encode_with_stats(&song).unwrap();
assert_eq!(bytes[0] >> 4, 1);
assert_eq!(stats.effects, (1 + 3) + 1 + (1 + 3 + 3 * 3));
let seq = Sequencer::<4>::new(&bytes, SR).unwrap();
let h = seq.header();
assert_eq!((h.version, h.vibratos, h.detunes, h.arps), (1, 1, 0, 1));
}
#[test]
fn time_is_always_counted_in_ppq_10080() {
use pikopiko_runtime::binary::VERSION;
assert_eq!(VERSION, 1);
let song = compile("A l28 c d e f g a b c4").unwrap();
let bytes = encode(&song).unwrap();
let seq = Sequencer::<4>::new(&bytes, SR).unwrap();
assert_eq!((seq.header().version, seq.header().ppq), (1, 10080));
assert_eq!((seq.header().envelopes, seq.header().arps), (0, 0));
assert_eq!(seq.header().unit, 1440);
let song = compile("A c%7 d%120 e4").unwrap();
let bytes = encode(&song).unwrap();
let seq = Sequencer::<4>::new(&bytes, SR).unwrap();
assert_eq!((seq.header().ppq, seq.header().unit), (10080, 21));
}
#[test]
fn decimal_and_integer_tempos_both_play_the_same() {
assert_same("A t128.5 l8 c d e f g", None);
assert_same("A t120 c4 t60,1 c1", None);
assert_same("A t100 c4 t132,1 c1", None);
}
fn with_track_prefix(prefix: &[u8]) -> Vec<u8> {
let mut bytes = encode(&compile("A c").unwrap()).unwrap();
let track_start = bytes.len() - 2;
assert_eq!(bytes[track_start], 1, "トラックの長さ 1 バイトの曲のはず");
bytes[track_start] = 1 + prefix.len() as u8;
bytes.splice(track_start + 1..track_start + 1, prefix.iter().copied());
bytes
}
#[test]
fn param_numbers_are_varints() {
use pikopiko_runtime::binary::{ext, ext_byte};
for (id, val) in [(5u8, vec![0x03]), (200, vec![0x03])] {
let mut prefix = vec![ext_byte(ext::PARAM)];
if id < 128 {
prefix.push(id);
} else {
prefix.extend_from_slice(&[0x80 | (id & 0x7f), id >> 7]);
}
prefix.extend_from_slice(&val);
assert!(Sequencer::<4>::new(&with_track_prefix(&prefix), SR).is_ok());
}
for id in [[0x80, 0x02], [0xff, 0x03]] {
let prefix = [ext_byte(ext::PARAM), id[0], id[1], 0x03];
assert!(Sequencer::<4>::new(&with_track_prefix(&prefix), SR).is_ok());
}
let prefix = [ext_byte(ext::PARAM), 0x80, 0x04, 0x03];
assert!(matches!(
Sequencer::<4>::new(&with_track_prefix(&prefix), SR),
Err(DecodeError::BadOp { .. })
));
}
#[test]
fn escape_command_is_reserved() {
use pikopiko_runtime::binary::{ext, ext_byte};
let prefix = [ext_byte(ext::ESCAPE), 0];
assert!(matches!(
Sequencer::<4>::new(&with_track_prefix(&prefix), SR),
Err(DecodeError::BadOp { .. })
));
assert!(Sequencer::<4>::new(&with_track_prefix(&[ext_byte(ext::ESCAPE)]), SR).is_err());
}
#[test]
fn unknown_versions_are_refused() {
let bytes = encode(&compile("A c").unwrap()).unwrap();
for v in [0u8, 2, 5, 15] {
let mut b = bytes.clone();
b[0] = (v << 4) | (b[0] & 0x0f);
assert_eq!(
Sequencer::<4>::new(&b, SR).err(),
Some(DecodeError::Version(v))
);
}
}
fn with_extension_header(ext_header: &[u8]) -> Vec<u8> {
use pikopiko_runtime::binary::FLAG_EXTENSIONS;
let mut bytes = encode(&compile("A c").unwrap()).unwrap();
bytes[0] |= FLAG_EXTENSIONS;
let at = bytes.len() - 2;
bytes.splice(at..at, ext_header.iter().copied());
bytes
}
#[test]
fn extension_header_skips_optional_blocks() {
let b = with_extension_header(&[2, 0x01, 2, 0xaa, 0xbb, 0x7f, 0]);
let seq = Sequencer::<4>::new(&b, SR).unwrap();
assert_eq!(seq.header().extensions, 2);
let plain = encode(&compile("A c").unwrap()).unwrap();
let mut synth = create_builtin(&pikopiko::SynthConfig::default(), SR, 1);
let mut with = Sequencer::<4>::new(&b, SR).unwrap();
let mut without = Sequencer::<4>::new(&plain, SR).unwrap();
let (mut x, mut y) = ([[0.0f32; 2]; 512], [[0.0f32; 2]; 512]);
with.render(synth.as_mut(), &mut x);
let mut synth = create_builtin(&pikopiko::SynthConfig::default(), SR, 1);
without.render(synth.as_mut(), &mut y);
assert_eq!(x, y);
}
#[test]
fn extension_header_refuses_unknown_required_blocks_and_bad_shapes() {
assert_eq!(
Sequencer::<4>::new(&with_extension_header(&[1, 0x82, 0]), SR).err(),
Some(DecodeError::Header)
);
assert_eq!(
Sequencer::<4>::new(&with_extension_header(&[1, 0x81, 0]), SR).err(),
Some(DecodeError::Header)
);
assert_eq!(
Sequencer::<4>::new(&with_extension_header(&[0]), SR).err(),
Some(DecodeError::Header)
);
assert!(Sequencer::<4>::new(&with_extension_header(&[1, 0x01, 9, 0xaa]), SR).is_err());
let mut b = encode(&compile("A c").unwrap()).unwrap();
b[0] |= pikopiko_runtime::binary::FLAG_EXTENSIONS;
assert!(Sequencer::<4>::new(&b, SR).is_err());
}
#[test]
fn arp_selection_must_point_into_the_table() {
use pikopiko_runtime::binary::{ext, ext_byte};
let bytes = encode(&compile("@arp m = 12\nA @arp m c").unwrap()).unwrap();
let n = bytes.len();
assert_eq!(&bytes[n - 4..], &[3, ext_byte(ext::ARP), 1, 0x10]);
assert!(Sequencer::<4>::new(&bytes, SR).is_ok());
let mut bad = bytes.clone();
bad[n - 2] = 2;
assert!(matches!(
Sequencer::<4>::new(&bad, SR),
Err(DecodeError::BadOp { .. })
));
let mut off = bytes.clone();
off[n - 2] = 0;
assert!(Sequencer::<4>::new(&off, SR).is_ok());
}
#[test]
fn effects_are_compact() {
let song = compile("@vib w = 6 50 25\nA @vib w l8 [c d e f]4 mpof g").unwrap();
let (bytes, stats) = encode_with_stats(&song).unwrap();
assert!(bytes.len() < 40, "{}", bytes.len());
assert!(stats.tracks[0] < stats.uncompressed[0]);
}
#[test]
fn too_many_effects_are_refused() {
let mut src = String::new();
for i in 0..256 {
src.push_str(&format!("@vib v{i} = 0 50 10\n"));
}
src.push('A');
for i in 0..256 {
src.push_str(&format!(" @vib v{i} c"));
}
assert!(compile(&src).is_err());
}
#[test]
fn broken_effect_tables_are_rejected() {
let song =
compile("@vib w = 12 55 30\n@detune d = 0 -20 * 20\nA @vib w @detune d c d").unwrap();
let bytes = encode(&song).unwrap();
assert_eq!(&bytes[6..8], &[0, 1]);
assert_eq!(&bytes[8..11], &[12, 55, 30]);
assert_eq!(&bytes[11..15], &[1, 3, 3, 0]);
let mut bad = bytes.clone();
bad[17] = 0;
assert_eq!(
Sequencer::<4>::new(&bad, SR).err(),
Some(DecodeError::Header)
);
assert!(Sequencer::<4>::new(&bytes[..13], SR).is_err());
use pikopiko_runtime::binary::{ext, ext_byte};
let pos = bytes
.windows(2)
.rposition(|w| w[0] == ext_byte(ext::VIBRATO) && w[1] == 1)
.unwrap();
let mut bad = bytes.clone();
bad[pos + 1] = 2;
assert!(matches!(
Sequencer::<4>::new(&bad, SR),
Err(DecodeError::BadOp { .. })
));
let mut old = bytes.clone();
old[0] = (old[0] & 0x0f) | 0x20;
assert_eq!(
Sequencer::<4>::new(&old, SR).err(),
Some(DecodeError::Version(2))
);
}
#[test]
fn broken_envelope_tables_are_rejected() {
let song = compile("@env p = 15 * 9 / 3\nA @env p c d").unwrap();
let bytes = encode(&song).unwrap();
assert_eq!(&bytes[6..10], &[1, 3, 2, 3]);
let mut bad = bytes.clone();
bad[9] = 1; assert_eq!(
Sequencer::<4>::new(&bad, SR).err(),
Some(DecodeError::Header)
);
let mut bad = bytes.clone();
bad[6] = 0; assert!(Sequencer::<4>::new(&bad, SR).is_err());
let pos = bytes
.windows(2)
.rposition(|w| {
w[0] == pikopiko_runtime::binary::ext_byte(pikopiko_runtime::binary::ext::ENVELOPE)
&& w[1] == 0
})
.unwrap();
let mut bad = bytes.clone();
bad[pos + 1] = 1;
assert!(matches!(
Sequencer::<4>::new(&bad, SR),
Err(DecodeError::BadOp { .. })
));
}
#[test]
fn too_many_tracks_for_the_sequencer() {
let song = compile("A c\nB c\nC c").unwrap();
let bytes = encode(&song).unwrap();
assert_eq!(
Sequencer::<2>::new(&bytes, SR).err(),
Some(DecodeError::Tracks(3))
);
}
#[test]
fn no_tracks_cannot_be_encoded() {
assert!(encode(&compile("").unwrap()).is_err());
}
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
}
#[test]
fn broken_data_never_panics() {
let mut rng = Rng(7);
let mut synth = create_builtin(&pikopiko::SynthConfig::default(), 8000, 4);
let mut buf = [[0.0f32; 2]; 256];
for _ in 0..3000 {
let n = (rng.next() % 48) as usize;
let mut b: Vec<u8> = (0..n).map(|_| rng.next() as u8).collect();
if !b.is_empty() && rng.next() % 2 == 0 {
b[0] = 0x10 | (b[0] & 0x0f);
}
if let Ok(mut s) = Sequencer::<4>::new(&b, 8000) {
s.set_looping(true);
for _ in 0..4 {
s.render(synth.as_mut(), &mut buf);
}
}
}
for src in SONGS.iter().chain(LOOP_SONGS) {
let song = compile(src).unwrap();
let good = encode(&song).unwrap();
for _ in 0..200 {
let mut b = good.clone();
let i = (rng.next() as usize) % b.len();
b[i] = rng.next() as u8;
if rng.next() % 4 == 0 {
b.truncate((rng.next() as usize) % b.len());
}
if let Ok(mut s) = Sequencer::<26>::new(&b, 8000) {
s.set_looping(true);
for _ in 0..8 {
s.render(synth.as_mut(), &mut buf);
}
}
}
}
}
#[test]
fn binary_format_doc_matches_constants() {
use pikopiko_runtime::binary::{ext, op};
let doc = include_str!("../../../docs/binary-format.md");
let ops = [
("NOTE_REL", op::NOTE_REL),
("NOTE_WAIT", op::NOTE_WAIT),
("WAIT", op::WAIT),
("VOLUME", op::VOLUME),
("OFF_WAIT", op::OFF_WAIT),
("TONE", op::TONE),
("LEGATO_REL", op::LEGATO_REL),
("EXT", op::EXT),
];
for (name, v) in ops {
assert!(
doc.contains(&format!("| `{name}` | {v} |")),
"binary-format.md に {name} = {v} がない"
);
}
let exts = [
("NOTE_ABS", ext::NOTE_ABS),
("LEGATO_ABS", ext::LEGATO_ABS),
("PARAM", ext::PARAM),
("TEMPO", ext::TEMPO),
("WAIT_LONG", ext::WAIT_LONG),
("REF", ext::REF),
("LOOP", ext::LOOP),
("CHANNEL", ext::CHANNEL),
("ENVELOPE", ext::ENVELOPE),
("VIBRATO", ext::VIBRATO),
("DETUNE", ext::DETUNE),
("PORTAMENTO", ext::PORTAMENTO),
("ARP", ext::ARP),
("TEMPO_FINE", ext::TEMPO_FINE),
("WAVE", ext::WAVE),
("ESCAPE", ext::ESCAPE),
];
for (name, v) in exts {
assert!(
doc.contains(&format!("| `{name}` | {v} |")),
"binary-format.md に {name} = {v} がない"
);
}
let song = compile("#synth ay\nA t140 l8 o4 [cegc >c<gec]2 [fafc >c<afa]2").unwrap();
let bytes = encode(&song).unwrap();
let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
let mut doc_hex = String::new();
let sec = &doc[doc.find("## 6. 例").unwrap()..];
let block = &sec[sec.find("```text").unwrap() + 7..];
for line in block[..block.find("```").unwrap()].lines() {
let bytes_part = line.split(" ").next().unwrap_or("");
for w in bytes_part.split_whitespace() {
if w.len() == 2 && w.chars().all(|c| c.is_ascii_hexdigit()) {
doc_hex.push_str(w);
}
}
}
assert_eq!(doc_hex, hex, "binary-format.md の例が実際の出力と違う");
let example_hex = |title: &str| -> String {
let from = &sec[sec.find(title).unwrap()..];
let block = &from[from.find("```text").unwrap() + 7..];
let mut doc_hex = String::new();
for line in block[..block.find("```").unwrap()].lines() {
let bytes_part = line.split(" ").next().unwrap_or("");
for w in bytes_part.split_whitespace() {
if w.len() == 2 && w.chars().all(|c| c.is_ascii_hexdigit()) {
doc_hex.push_str(w);
}
}
}
doc_hex
};
let hex_of = |bytes: &[u8]| -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() };
let cases = [
("エンベロープ表の例", "@env p = 15 * 9 / 3\nA @env p c d"),
(
"ビブラート表とデチューン表の例",
"@vib w = 12 55 30\n@detune d = 0 -20 * 20\nA @vib w @detune d c d",
),
("アルペジオ表の例", "@arp m = * 0 4 7\nA @arp m c d"),
(
"波形表の例",
"@wave w = -128 -120 -112 -104 -96 -88 -80 -72 -64 -56 -48 -40 -32 -24 -16 -8 0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120\nA @wave w c d",
),
];
for (title, src) in cases {
let bytes = encode(&compile(src).unwrap()).unwrap();
assert_eq!(
example_hex(title),
hex_of(&bytes),
"binary-format.md の「{title}」が実際の出力と違う"
);
}
let ext_bytes = with_extension_header(&[2, 0x01, 2, 0xaa, 0xbb, 0x7f, 0]);
assert_eq!(
example_hex("拡張ヘッダーの例"),
hex_of(&ext_bytes),
"binary-format.md の拡張ヘッダーの例が違う"
);
assert_eq!(
Sequencer::<4>::new(&ext_bytes, SR)
.unwrap()
.header()
.extensions,
2
);
}
#[test]
fn unbind_and_bind_keep_the_sound() {
let src = SONGS[3];
let frames = SR as usize * 3;
let expected = via_binary(src, None, frames);
let song = compile(src).unwrap();
let bytes = encode(&song).unwrap();
let owned = bytes.clone();
let mut state = Sequencer::<26>::new(&bytes, SR).unwrap().unbind();
let mut synth = create_builtin(&song.synth, SR, song.tracks.len());
let mut out = vec![[0.0f32; 2]; frames];
for chunk in out.chunks_mut(97) {
let mut seq = state.bind(&owned).expect("同じデータ");
seq.render(synth.as_mut(), chunk);
state = seq.unbind();
}
assert_eq!(out, expected);
}
#[test]
fn bind_refuses_different_data_and_unbound_is_silent() {
let song = compile(SONGS[0]).unwrap();
let bytes = encode(&song).unwrap();
let other = encode(&compile(SONGS[1]).unwrap()).unwrap();
let state = Sequencer::<26>::new(&bytes, SR).unwrap().unbind();
let mut unbound = Sequencer::<26>::new(&bytes, SR).unwrap().unbind();
let mut synth = create_builtin(&song.synth, SR, song.tracks.len());
let mut out = vec![[1.0f32; 2]; 100];
unbound.render(synth.as_mut(), &mut out);
assert!(out.iter().all(|f| *f == [0.0, 0.0]));
assert_eq!(unbound.position(), 0);
assert!(state.bind(&other).is_none());
}
#[test]
fn english_binary_format_matches_japanese() {
let ja = include_str!("../../../docs/binary-format.md");
let en = include_str!("../../../docs/en/binary-format.md");
let headings = |doc: &str| -> Vec<String> {
let mut in_code = false;
let mut out = Vec::new();
for line in doc.lines() {
if line.starts_with("```") {
in_code = !in_code;
} else if !in_code && line.starts_with('#') {
let (hashes, rest) = line.split_once(' ').unwrap();
let num = rest.split_whitespace().next().unwrap_or("");
let num = if num.chars().next().is_some_and(|c| c.is_ascii_digit()) {
num.trim_end_matches('.')
} else {
""
};
out.push(format!("{hashes} {num}"));
}
}
out
};
assert_eq!(headings(ja), headings(en), "見出しの並びが違う");
let rows = |doc: &str| -> Vec<(String, String)> {
doc.lines()
.filter_map(|l| {
let mut cells = l.split('|').map(str::trim);
cells.next()?; let name = cells.next()?;
let value = cells.next()?;
(name.starts_with('`')
&& name.ends_with('`')
&& name[1..name.len() - 1]
.chars()
.all(|c| c.is_ascii_uppercase() || c == '_')
&& value.chars().all(|c| c.is_ascii_digit())
&& !value.is_empty())
.then(|| (name.to_string(), value.to_string()))
})
.collect()
};
assert_eq!(rows(ja), rows(en), "命令の表の名前と値が違う");
assert!(rows(ja).len() >= 24);
let blocks = |doc: &str| -> Vec<(String, String)> {
let mut out = Vec::new();
let mut cur: Option<(String, String)> = None;
for line in doc.lines() {
if let Some(info) = line.strip_prefix("```") {
match cur.take() {
Some(b) => out.push(b),
None => cur = Some((info.to_string(), String::new())),
}
} else if let Some((info, hex)) = cur.as_mut() {
if info == "text" {
for w in line.split(" ").next().unwrap_or("").split_whitespace() {
if w.len() == 2 && w.chars().all(|c| c.is_ascii_hexdigit()) {
hex.push_str(w);
}
}
}
}
}
out
};
let (bj, be) = (blocks(ja), blocks(en));
assert_eq!(bj.len(), be.len(), "コードブロックの数が違う");
let sec = |doc: &str, title: &str| -> usize {
doc[..doc.find(title).unwrap()].matches("```").count() / 2
};
let (from_ja, from_en) = (sec(ja, "## 6. 例"), sec(en, "## 6. Examples"));
assert_eq!(from_ja, from_en, "6 章より前のコードブロックの数が違う");
for i in from_ja..bj.len() {
assert_eq!(
bj[i].1,
be[i].1,
"6 章の {} 番目の例のバイト列が違う",
i - from_ja + 1
);
assert!(!bj[i].1.is_empty());
}
}