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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! イベント列バイナリ:変換して no_std のシーケンサーで鳴らした音が、
//! Player で鳴らした音とサンプル単位で一致することを確かめる。

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",
    // 7 連符・9 連符
    "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",
    // 小数のテンポと加速・減速(TEMPO_FINE)
    "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",
    // tick で書いた音長
    "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] = &[
    // 加速・減速と小数のテンポ、7 連符とループ(復元ブロックに TEMPO_FINE)
    "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();
    // ヘッダー(表の件数 4 つを含む)+ テンポ 2 + 32 音。参照なしなら 10 バイトほど大きくなる
    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);
    // 時間は 4分音符 10080 tick で数え、単位は 8 分音符(5040 tick)
    assert_eq!(h.unit, 5040);
    assert_eq!(h.length, 2);
    assert_eq!(h.loop_at, Some(1));
}

#[test]
fn envelope_table_is_always_written() {
    // エンベロープを使わない曲でも、表は件数 0 で書く(版はいつも 1)
    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);
    // 件数 1 + (段数, *, /, 段 6) + (段数, *, /, 段 1):12:20 は 16 + 4 フレームの 2 段になる
    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() {
    // 音程エフェクトだけの曲(エンベロープ表は 0 件)
    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);
    // ビブラート 件数 1 + 3 バイト、デチューン 件数 1 + (段数, *, /) + 段 4 つ × 3 バイト
    // (20:3 は 1 段、`/ 5` は余韻の 1 段で、`-20` `0` と合わせて 4 段)、アルペジオ 件数 0
    assert_eq!(stats.effects, (1 + 3) + (1 + 3 + 4 * 3) + 1);
    assert_eq!(stats.envelopes, 1); // 件数 0 だけ
    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);
    // ビブラート 件数 1 + 3、デチューン 件数 0、アルペジオ 件数 1 + (段数, *, /) + 段 3 つ × 3 バイト
    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);
    // 7 連符の単位は 1440 tick
    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);
    // 4分音符 480 tick で表せる曲も同じ数え方(表記上の 1 tick は内部の 21 tick)
    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() {
    // 小数のテンポは TEMPO_FINE、整数は短い TEMPO で書くが、どちらも Player と同じ音になる
    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);
}

/// 1 トラックの曲 `A c`(終わりが「トラックの長さ 1 バイト + 命令 1 バイト」)の命令列の先頭に
/// `prefix` を差し込む。
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};
    // 127 までは 1 バイト、128 以上は 2 バイト。値のあとに音が続く
    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());
    }
    // 口は 2 ページ(0〜255 と 256〜511)。256 と 511 は通り、512 以上は読まずに断る
    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))
        );
    }
}

/// `A c` の曲の、トラックの長さの直前(表のあと)に拡張ヘッダー `ext_header` を差し込む。
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() {
    // ブロック 2 つ:番号 0x01(長さ 2)と番号 0x7f(長さ 0)。どちらも必須ではないので読み飛ばす
    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)
    );
    // 波形表(0x81)は中身が空でも壊れている
    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());
    // flags は立てたが拡張ヘッダーがない
    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};
    // 命令列は ARP 表の 0 番(ec 01)と NOTE_REL +0(10)。末尾は「トラックの長さ 2 + 命令列」
    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 { .. })
    ));
    // 0 は解除
    let mut off = bytes.clone();
    off[n - 2] = 0;
    assert!(Sequencer::<4>::new(&off, SR).is_ok());
}

#[test]
fn effects_are_compact() {
    // 同じ音程エフェクトの選び直しは 2 バイトの命令になり、後方参照にも入る
    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"));
    }
    // 展開の段階で 256 個目を断られるので、曲そのものができない
    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();
    // ヘッダー:版, 音源, トラック数, unit(2 バイト), length, エンベロープ 0 件,
    // ビブラート 1 件 + 3 バイト, デチューン 1 件 + (段数 3, *, /) + 段 3 つ
    assert_eq!(&bytes[6..8], &[0, 1]);
    assert_eq!(&bytes[8..11], &[12, 55, 30]);
    assert_eq!(&bytes[11..15], &[1, 3, 3, 0]);
    // デチューンの段が 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());
    // VIBRATO 命令の番号が表の外(番号 + 1 が件数を超える)
    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();
    // ヘッダー:版, 音源, トラック数, unit(2 バイト), length, 件数, 段数, *, /, 段 x3
    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; // 件数 0
    assert!(Sequencer::<4>::new(&bad, SR).is_err());
    // ENVELOPE 命令の番号が表の外
    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 {
            // 版 1 のヘッダーにする(flags は元のビットのまま)
            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} がない"
        );
    }
    // 6章の例のバイト列が実際の出力と同じ
    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
    );
}

/// 曲データを外して付け直しても、1 フレームごとに繰り返しても、音が変わらない(ゲーム側で曲データを差し替える使い方)。
#[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());
}

/// 英語版(`docs/en/binary-format.md`)が日本語版(正本)と同じ構成であること:見出しの番号、
/// 命令の表の行(名前と値)、コードブロックの数、6 章の例のバイト列。英語の文の正しさは見ないので、
/// 人が読んで確かめる。
#[test]
fn english_binary_format_matches_japanese() {
    let ja = include_str!("../../../docs/binary-format.md");
    let en = include_str!("../../../docs/en/binary-format.md");

    // 見出しの番号(`### 3.4 …` の `3.4`)。番号のない見出しは `#` の数だけ
    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), "見出しの並びが違う");

    // 命令の表の行(`| `NAME` | 値 |` で始まる行)の名前と値
    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);

    // コードブロックの数と、`text` のブロックの 16 進(バイトの列。説明の文は見ない)
    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(), "コードブロックの数が違う");
    // 6 章(例)のブロックだけ、バイト列が同じ(それ以外の `text` は書式の説明)
    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());
    }
}