-
Notifications
You must be signed in to change notification settings - Fork 0
/
kbd
executable file
·2043 lines (1844 loc) · 75.6 KB
/
kbd
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# vi:set sw=2 ai sm:
# Copyright © 2021–2022 by Ambrose Li
=pod
=encoding utf8
=head1 NAME
kbd – Keyboard emulator
=head1 DESCRIPTION
This is a conceptually simple script that emulates a MIDI keyboard
using a regular keyboard for typing.
All the code for interfacing with Fluidsynth came from I<chimer>.
=cut
# see https://stackoverflow.com/questions/6162484/why-does-modern-perl-avoid-utf-8-by-default for these crazy hacks
# THERE ARE MORE CRAZY HACKS THERE FOR MORE COMPLEX PROJECTS!!
use v5.12; # minimal for unicode string feature
use v5.14; # //u modifier
use utf8;
open qw( :encoding(UTF-8) :std );
use charnames qw( :full :short );
use feature "unicode_strings";
use warnings qw( FATAL utf8 );
use Encode qw( encode decode );
#@ARGV = map { decode("UTF-8", $_) } @ARGV if grep /\P{ASCII}/ => @ARGV;
binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';
use strict;
use integer;
package Debug;
use Scalar::Util qw(blessed dualvar isdual readonly refaddr reftype tainted weaken isweak isvstring looks_like_number set_prototype);
sub lazy_sorter ($$) {
my($a, $b) = @_;
my $it;
if ($a =~ /^(.*?)(\d+(?:\.\d+)?)$/s) {
no integer;
my($a1, $a2) = ($1, $2);
if ($b =~ /^(.*?)(\d+(?:\.\d+)?)$/s) {
my($b1, $b2) = ($1, $2);
if ($a1 eq $b1 && $a1 =~ /q$/s) { # q0 = q4 therefore > q3
$it = ($a2 + 3)%4 <=> ($b2 + 3)%4;
} else {
$it = $a1 cmp $b1;
$it = $a2 <=> $b2 unless $it;
}
}
}
$it = $a cmp $b unless defined $it && $it;
return $it;
}
sub cvs ($) {
my($s) = @_;
my $it;
sub compute_size ($) {
my($s) = @_;
my $it;
if (!defined $s || !ref $s) {
$it = 1;
} elsif (ref $s eq 'ARRAY') {
for my $val (@$s) {
$it += compute_size($val);
}
} else { # hash or object
$it += 2 unless ref $s eq 'HASH';
for my $val (values %$s) {
$it += 1 + compute_size($val);
}
}
return $it;
}
sub format_scalar ($) {
my($it) = @_;
no integer;
if (!looks_like_number($it)) {
$it =~ s/([\\\(\)])/\\\1/sg;
$it =~ s/(\n)/\\n/sg;
$it = "($it)";
}
return $it;
}
sub format_as_name ($) {
my($s) = @_;
return $s =~ /^[-\.\w]+$/? "/$s": sprintf('%s cvn', cvs($s));
}
sub format_array_inner ($) {
my($s) = @_;
my $it;
if (compute_size($s) <= 12) { # cf. https://picolisp.com/wiki/?prettyPrint
$it = join(' ', map { cvs($_) } @$s);
} else {
my @s = @$s;
$it = cvs($s[0]) . "\n " . format_array_inner([@s[1..$#s]]);
}
return $it;
}
sub format_hash ($) {
my($s) = @_;
my @keys = sort { lazy_sorter($a, $b) } keys %$s;
my @size;
my $it;
for (my $i = $#keys; $i >= 0; $i -= 1) {
my $key = $keys[$i];
$size[$i] = compute_size($key) + compute_size($s->{$key});
$size[$i] += $size[$i + 1] if $i < $#keys;
}
for (my $i = 0; $i < @keys; $i += 1) {
my $key = $keys[$i];
$it .= ($size[$i] <= 12? ' ': "\n") if defined $it;
$it .= sprintf('%s %s', format_as_name $key, cvs($s->{$key}));
}
return "<<$it>>";
}
if (!defined $s) {
$it = 'null';
} elsif (ref $s eq 'ARRAY') {
$it = sprintf('[%s]', format_array_inner($s));
} elsif (ref $s eq 'HASH') {
$it = format_hash $s;
} elsif (!ref $s) {
$it = format_scalar $s;
} else { # object :-/
$it = sprintf '%s %s bless', format_hash $s, format_as_name ref $s;
}
return $it;
}
package Keyboard_Emulator;
use POSIX;
use POSIX ":sys_wait_h"; # for nonblocking read
use DateTime;
use Time::HiRes; # overrides (qw) do not seem to work
use Expect::Simple;
use Exporter;
require Exporter;
use vars qw( @ISA @EXPORT @EXPORT_OK );
@ISA = qw(Exporter);
@EXPORT_OK = qw( $dow_re $dow_range_re %expressive_mark_to_midi_velocity );
use vars qw( @restart_cmd );
@restart_cmd = ($0, @ARGV); # save this because GetOpt will clear @ARGV
use vars qw( $appName );
$appName = 'kbd';
use Getopt::Long;
use Data::Dumper;
use Curses;
use vars qw( $config );
use vars qw( $overrides );
use vars qw( $debug );
use vars qw( $no_cache_p $create_cache_p $test_p );
use vars qw( $verbose_p );
use vars qw( $quit_p );
use vars qw( $enable_nonproportional_watches );
use vars qw( $enable_qing_quarters );
use vars qw( $coords );
use vars qw( $lat $lon );
use vars qw( $use_jack_p );
use vars qw( @sinks );
use vars qw( $synth );
use vars qw( %children );
use vars qw( %expected_latency );
use vars qw( $wood_note );
use vars qw( %instrument_name_to_channel_number );
use vars qw( %instrument_name_to_mf_velocity );
use vars qw( $fluidR3 );
$fluidR3 = '/usr/share/sounds/sf2/FluidR3_GM.sf2';
use vars qw( $beat_length );
$beat_length = 1;
use vars qw( $boottime );
$boottime = Time::HiRes::time;
use vars qw( $time_displacement );
sub current_time () { no integer; Time::HiRes::time + $time_displacement }
use vars qw( $basedir $datadir );
$basedir = $1 if $0 =~ /^(.*?)\/+[^\/]+$/;
$basedir =~ s/(?:^|\/+)bin$//;
$basedir = '.' if $basedir eq '';
$datadir = "$basedir/data";
# number of times we try sleeping for 1 second until we sleep until the target event
sub COUNTDOWN () { 5 } # things stablize after 2-3 times, we do 5 just in case (10 is overkill)
# number of seconds to sleep before we disconnect the synth - from observation this must be at least 6
sub SECONDS_BEFORE_DISCONNECT () { 7 }
sub MODE__SYSLINE () { 'sysline' }
sub MODE__CUCKOO () { 'cuckoo' }
sub MODE__CARILLON () { 'carillon' }
sub METHOD__SAMPLES () { 'samples' }
sub METHOD__SYNTH () { 'synth' }
sub MELODY__ABBEY () { 'abbey' }
sub MELODY__CAMBRIDGE () { 'cambridge' }
sub MELODY__CAMBRIDGE_RCC () { 'cambridge_rcc' }
sub MELODY__CANTERBURY () { 'canterbury' }
sub MELODY__GUILDFORD () { 'guildford' }
sub MELODY__MAGDALEN () { 'magdalen' }
sub MELODY__NEWCOLLEGE () { 'newcollege' }
sub MELODY__NORWICH () { 'norwich' }
sub MELODY__TINGTANG2A () { 'tingtang2a' }
sub MELODY__TINGTANG2B () { 'tingtang2b' }
sub MELODY__TINGTANG3A () { 'tingtang3a' }
sub MELODY__TINGTANG3B () { 'tingtang3b' }
sub MELODY__TINGTANG4 () { 'tingtang4' }
sub MELODY__TINGTANG5 () { 'tingtang5' }
sub MELODY__WESTMINSTER () { 'westminster' }
sub MELODY__WHITTINGTON () { 'whittington' }
sub MELODY__WHITTINGTON11 () { 'whittington11' }
use vars qw( $mode $method $melody );
$mode = MODE__CARILLON;
$method = METHOD__SAMPLES;
$melody = MELODY__WESTMINSTER;
use vars qw( %alias_to_canonical_instrument );
%alias_to_canonical_instrument = (
'Keyboard' => 'Piano',
'Carillon' => 'Bell',
'Chimes' => 'Church Bells',
);
use vars qw( %laisser_vibrer_p );
%laisser_vibrer_p = (
'Bell' => 1,
'Gong' => 1,
);
# night watch chime patterns
sub LONG_STRIKE () { 1.5 }
sub SHORT_STRIKE () { 0.5 }
sub GAP () { 2.5 }
# watch chime patterns: repetitions, pattern
# gap needs to be long enough to hear it, but short enough to not mistake it for a long strike. This is HARD
use vars qw( @watch_chime_pattern );
@watch_chime_pattern = ( # v. https://zh.wikipedia.org/wiki/打更 (q.v.)
[3, '— .' ],
[2, '. .' ],
[3, '— . .' ],
[4, '— . . .' ],
[5, '— . . . .' ],
);
use vars qw( @midi_number_to_note %note_to_midi_number );
@midi_number_to_note = (
'c0', 'c#0', 'd0', 'd#0', 'e0', 'f0', 'f#0', 'g0', 'g#0', 'a0', 'a#0', 'b0',
'c1', 'c#1', 'd1', 'd#1', 'e1', 'f1', 'f#1', 'g1', 'g#1', 'a1', 'a#1', 'b1',
'c2', 'c#2', 'd2', 'd#2', 'e2', 'f2', 'f#2', 'g2', 'g#2', 'a2', 'a#2', 'b2',
'c3', 'c#3', 'd3', 'd#3', 'e3', 'f3', 'f#3', 'g3', 'g#3', 'a3', 'a#3', 'b3',
'c4', 'c#4', 'd4', 'd#4', 'e4', 'f4', 'f#4', 'g4', 'g#4', 'a4', 'a#4', 'b4',
'c5', 'c#5', 'd5', 'd#5', 'e5', 'f5', 'f#5', 'g5', 'g#5', 'a5', 'a#5', 'b5',
'c6', 'c#6', 'd6', 'd#6', 'e6', 'f6', 'f#6', 'g6', 'g#6', 'a6', 'a#6', 'b6',
'c7', 'c#7', 'd7', 'd#7', 'e7', 'f7', 'f#7', 'g7', 'g#7', 'a7', 'a#7', 'b7',
'c8', 'c#8', 'd8', 'd#8', 'e8', 'f8', 'f#8', 'g8', 'g#8', 'a8', 'a#8', 'b8',
'c9', 'c#9', 'd9', 'd#9', 'e9', 'f9', 'f#9', 'g9', 'g#9', 'a9', 'a#9', 'b9',
);
%note_to_midi_number = map { $midi_number_to_note[$_] => $_ } 0..$#midi_number_to_note;
use vars qw( %gong_scale %chime_scale );
%gong_scale = (
'c4' => '582141__strangehorizon__g01-c-4-gong.wav',
'c#4' => '582140__strangehorizon__g02-c-4-gong.wav',
'd4' => '582139__strangehorizon__g03-d-4-gong.wav',
'd#4' => '582138__strangehorizon__g04-d-4-gong.wav',
'e4' => '582145__strangehorizon__g05-e-4-gong.wav',
'f4' => '582144__strangehorizon__g06-f-4-gong.wav',
'f#4' => '582143__strangehorizon__g07-f-4-gong.wav',
'g4' => '582142__strangehorizon__g08-g-4-gong.wav',
'g#4' => '582147__strangehorizon__g09-g-4-gong.wav',
'a4' => '582146__strangehorizon__g10-a-4-gong.wav',
'a#4' => '582156__strangehorizon__g11-a-4-gong.wav',
'b4' => '582155__strangehorizon__g12-b-4-gong.wav',
'c5' => '582154__strangehorizon__g13-c-5-gong.wav',
'c#5' => '582153__strangehorizon__g14-c-5-gong.wav',
'd5' => '582160__strangehorizon__g15-d-5-gong.wav',
'd#5' => '582159__strangehorizon__g16-d-5-gong.wav',
'e5' => '582158__strangehorizon__g17-e-5-gong.wav',
'f5' => '582157__strangehorizon__g18-f-5-gong.wav',
'f#5' => '582162__strangehorizon__g19-f-5-gong.wav',
'g5' => '582161__strangehorizon__g20-g-5-gong.wav',
);
%chime_scale = (
'c4' => 'chimes_C1.ogg',
'c#4' => 'chimes_C#1.ogg',
'd4' => 'chimes_D1.ogg',
'd#4' => 'chimes_D#1.ogg',
'e4' => 'chimes_E1.ogg',
'f4' => 'chimes_F1.ogg',
'f#4' => 'chimes_F#1.ogg',
'g4' => 'chimes_G1.ogg',
'g#4' => 'chimes_G#1.ogg',
'a4' => 'chimes_A1.ogg',
'a#4' => 'chimes_A#1.ogg',
'b4' => 'chimes_B1.ogg',
'c5' => 'chimes_C2.ogg',
'c#5' => 'chimes_C#2.ogg',
'd5' => 'chimes_D2.ogg',
'd#5' => 'chimes_D#2.ogg',
'e5' => 'chimes_E2.ogg',
'f5' => 'chimes_F2.ogg',
);
sub gensym () {
state $n;
return sprintf('g%d', $n++);
}
sub log_internal ($$;$$$) {
my($flag, $s, $prefix, $newline_p, $keep_p) = @_;
state $last_logged;
my $daemon_p = !-t STDERR;
$newline_p = 1 if $s =~ s/^\n+//s;
$newline_p = 0 unless defined $last_logged;
$newline_p = 1 if defined $last_logged && $last_logged->{'keep'};
$newline_p = 0 if $daemon_p;
my $cleol_p = !$daemon_p && !$newline_p;
$keep_p = 1 if $debug;
$prefix .= ': ' if defined $prefix && $prefix =~ /\S/s && $prefix !~ /: $/s;
chomp $s;
printf STDERR "%s%10.2f%s\t%s%s%s%s", ($newline_p? "\n": ''),
current_time, $flag, $prefix, $s, ($cleol_p? "\033[K": ''), ($daemon_p? "\n": "\r");
$last_logged->{'keep'} = $keep_p + 0;
}
sub log_output ($) { log_internal '>', $_[0] }
sub log_comment ($) { log_internal '#', $_[0] }
sub log_debug ($) { log_internal '#', $_[0], 'DEBUG', 1, 1 }
sub log_info ($) { log_internal '#', $_[0], undef, 0, 1 }
sub log_error ($) { log_internal '#', $_[0], 'ERROR', 1, 1 }
sub log_warning ($) { log_internal '#', $_[0], 'WARNING', 1, 1 }
sub log_command (@) { log_debug 'running: '. join(' ', map { s/([\\"])/\\\1/sg if /\s/; /\s|^$/? "\"$_\"": $_ } @_) }
=pod
=head2 Chime melodies
Each chime melody is internally represented as an array of
B<[>I<midi note name>, I<time in seconds>, I<percentage volume>, I<instrument>B<]> entries
(I<instrument> can be undef),
but written as calls to I<define_event> which takes 3 parameters –
the identifier for the mode,
the identifier for the melody,
a string containing any definitions (in the form S<I<var> = I<some definition>>) –
plus a list of key-value pairs.
Valid keys are B<q1> for first-quarter chimes,
B<q2> for second-quarter chimes,
B<q3> for third-quarter chimes,
B<q0> for fourth-quarter chimes,
and B<h> for the hour strike.
As many definitions as needed can be included, but each definition I<must> be of the form of either of
=over
I<var> = B<\relative> I<pitch> B<{> I<melody> B<}>
I<var> = B<\drums> B<{> I<melody> B<}>
I<var> B<{> I<tempo or some other initialization> B<}>
=back
The values are written in LilyPond notation
(in either relative pitch or drum mode, optionally including note lengths and basic expressive marks),
described in
=over
Relative Octave Entry. (n.d.). In I<LilyPond — Notation Reference v2.22.1 (stable-branch)>.
Retrieved August 18, 2021, from http://lilypond.org/doc/v2.22/Documentation/notation/writing-pitches#relative-octave-entry
Percussion notes. (n.d.). In I<LilyPond — Notation Reference v2.22.1 (stable-branch)>.
Retrieved August 20, 2021, from http://lilypond.org/doc/v2.22/Documentation/notation/percussion-notes
=back
For the hour strike, you should normally use B<%I> for represent the hour
so that you can strike the bell the correct number of times
(you should of course omit B<%I> for I<sysline> mode
or for ancient ting-tang quarters that always strike the hour strike once).
I<event_def> calls I<interpret_melody> to convert this notation into the internal representation described above,
but this conversion is just a simple pattern match and therefore can produce incorrect results.
If results are incorrect but the notation typesets correctly in LilyPond, the bug is in I<interpret_melody>.
The mapping between Lilypond expressive marks and MIDI velocities is based on
=over
Yamaha. (n.d.). I<Everything You've Ever Wanted to Know About Using MIDI with a Disklavier>.
Yamaha Disklavier Education Network.
Retrieved August 19, 2021, from https://www.yamahaden.com/easyblog/entry/everything-you-ve-ever-wanted-to-know-about-using-midi-with-a-disklavier
Vandenneucker, D.Z<Dominique> (2012). MIDI tutorial.
Retrieved September 5, 2021, from http://www.music-software-development.com/midi-tutorial.html
=back
The mapping between Lilypond percussion notes and MIDI percussion notes is based on
=over
General MIDI instrument codes. (n.d.).
Retrieved August 20, 2021, from http://www.ccarh.org/courses/253/handout/gminstruments/
=back
=cut
use vars qw( %ly_notes );
%ly_notes = (
'ces' => -1, 'c' => 0, 'cis' => 1,
'des' => 1, 'd' => 2, 'dis' => 3,
'ees' => 3, 'e' => 4, 'eis' => 5,
'fes' => 4, 'f' => 5, 'fis' => 6,
'ges' => 6, 'g' => 7, 'gis' => 8,
'aes' => 8, 'a' => 9, 'ais' => 10,
'bes' => 10, 'b' => 11, 'bis' => 12,
);
use vars qw( %percussion_note_to_midi_number );
%percussion_note_to_midi_number = (
'bassdrum' => 36, 'bd' => 36,
'acousticbassdrum' => 35, 'bda' => 35,
'snare' => 38, 'sn' => 38, # arbitrarily map to sna
'acousticsnare' => 38, 'sna' => 38,
'electricsnare' => 40, 'sne' => 40,
'lowfloortom' => 41, 'tomfl' => 41,
'highfloortom' => 43, 'tomfh' => 43,
'lowtom' => 45, 'toml' => 45,
'hightom' => 50, 'tomh' => 50,
'lowmidtom' => 47, 'tomml' => 47,
'himidtom' => 48, 'tommh' => 48,
'highhat' => 44, 'hh' => 44, # arbitrarily map to hhp
'closedhighhat' => 42, 'hhc' => 42,
'openhighhat' => 46, 'hho' => 46,
'halfopenhighhat' => undef, 'hhho' => undef, # don't know how to map
'pedalhighhat' => 44, 'hhp' => 44,
'crashcymbal' => 49, 'cymc' => 49, # arbitrarily map to cymca
'crashcymbala' => 49, 'cymca' => 49,
'crashcymbalb' => 57, 'cymcb' => 57,
'ridecymbal' => 51, 'cymr' => 51, # arbitrarily map to cymra
'ridecymbala' => 51, 'cymra' => 51,
'ridecymbalb' => 59, 'cymrb' => 59,
'chinesecymbal' => 52, 'cymch' => 52,
'splashcymbal' => 55, 'cyms' => 55,
'ridebell' => 53, 'rb' => 53,
'cowbell' => 56, 'cb' => 56,
'hibongo' => 60, 'boh' => 60,
'openhibongo' => undef, 'boho' => undef, # don't know how to map
'muteopenhibongo' => undef, 'bohm' => undef, # don't know how to map
'lobongo' => 61, 'bol' => 61,
'openlobongo' => undef, 'bolo' => undef, # don't know how to map
'muteopenlobongo' => undef, 'bolm' => undef, # don't know how to map
'hiconga' => 63, 'cgh' => 63, # arbitrarily map to cgho
'openhiconga' => 63, 'cgho' => 63,
'mutehiconga' => 62, 'cghm' => 62,
'loconga' => 64, 'cgl' => 64,
'openloconga' => undef, 'cglo' => undef, # don't know how to map
'muteloconga' => undef, 'cglm' => undef, # don't know how to map
'hitimbale' => 65, 'timh' => 65,
'lotimbale' => 66, 'timl' => 66,
'hiagogo' => 67, 'agh' => 67,
'loagogo' => 68, 'agl' => 68,
'sidestick' => 37, 'ss' => 37,
'hisidestick' => undef, 'ssh' => undef, # don't know how to map
'losidestick' => undef, 'ssl' => undef, # don't know how to map
'guiro' => 73, 'gui' => 73, # arbitrarily map to guis
'shortguiro' => 73, 'guis' => 73,
'longguiro' => 74, 'guil' => 74,
'cabasa' => 69, 'cab' => 69,
'maracas' => 70, 'mar' => 70,
'shortwhistle' => 71, 'whs' => 71,
'longwhistle' => 72, 'whl' => 72,
'handclap' => 39, 'hc' => 39,
'tambourine' => 54, 'tamb' => 54,
'vibraslap' => 58, 'vibs' => 58,
'tamtam' => undef, 'tt' => undef, # no way to map this
'claves' => 75, 'cl' => 75,
'hiwoodblock' => 76, 'wbh' => 76,
'lowoodblock' => 77, 'wbl' => 77,
'opencuica' => 79, 'cuio' => 79,
'mutecuica' => 78, 'cuim' => 78,
'triangle' => 81, 'tri' => 81, # arbitrarily map to trio
'opentriangle' => 81, 'trio' => 81,
'mutetriangle' => 80, 'trim' => 80,
'oneup' => undef, 'ua' => undef, # no idea what this is
'twoup' => undef, 'ub' => undef, # no idea what this is
'threeup' => undef, 'uc' => undef, # no idea what this is
'fourup' => undef, 'ud' => undef, # no idea what this is
'fiveup' => undef, 'ue' => undef, # no idea what this is
'onedown' => undef, 'da' => undef, # no idea what this is
'twodown' => undef, 'db' => undef, # no idea what this is
'threedown' => undef, 'dc' => undef, # no idea what this is
'fourdown' => undef, 'dd' => undef, # no idea what this is
'fivedown' => undef, 'de' => undef, # no idea what this is
);
use vars qw( %expressive_mark_to_midi_velocity );
%expressive_mark_to_midi_velocity = (
'ppppp' => 1,
'pppp' => 8, # this should be 8 according to Vandenneucker (2012)
'ppp' => 20, # this should be close to 20 according to Yamaha (n.d.), exactly 20 according to Vandenneucker (2012)
'pp' => 31,
'p' => 42,
'mp' => 53,
'mf' => 64,
'f' => 80,
'ff' => 96,
'fff' => 112, # this should be close to 110 according to Yamaha (n.d.), exactly 112 according to Vandenneucker (2012)
'ffff' => 119, # this should be 127 according to Vandenneucker (2012)
'fffff' => 127,
);
use vars qw( %interpretation );
use vars qw( %typesettable_version );
use vars qw( %mode_description );
use vars qw( %melody_description );
sub interpret_absolute_pitch ($) { # interpret c' as c4
my($s) = @_;
my $it;
if ($s =~ /^(\w+)(?:(,*)|('*))$/) {
$it = $ly_notes{$1} + 12*(3 - length($2) + length($3));
} else {
die "Can't interpret absolute pitch " . Debug::cvs($s);
}
return $it;
}
sub interpret_divisor ($) {
my($s) = @_;
no integer;
return !defined $s? $s: $s =~ /\x{5c}longa/? 0.25: $s =~ /\x{5c}breve/? 0.5: $s =~ /^\d+$/? $s + 0: $s; # XXX
}
sub calculate_beat_length ($$) {
my($divisor, $dots) = @_;
no integer;
my $it = 4 / $divisor;
for (my $i = $dots, my $adj = $it/2; $i; $i -= 1, $adj /= 2) {
$it += $adj;
}
return $it;
}
my $duration_re = q((?:(\s*\x{5c}longa|\s*\x{5c}breve|\d+)(\.+)?)); # NOTE: 2 captures: divisor, dots
sub interpret_melody ($) {
my($s0) = @_;
my $it;
my $typesettable_version;
no integer;
state $rest_re = sprintf('(?:r)');
state $percussion_instrument_re = sprintf('(?:%s)', join('|', keys %percussion_note_to_midi_number));
state $pitch_re = q(([a-g](?:[ei]s)?)?(?:(,*)|('*))); # NOTE: 3 captures: base pitch, commas, apostrophes
state $pitch_re_no_captures = ($pitch_re =~ s/\x28(?!\?)/\x28?:/sgr);
state $expressive_mark_re = sprintf("(?:%s)", join('|', keys %expressive_mark_to_midi_velocity));
state $end_re = q((?=[-\s\x{7d}\x{5e}~()\[\]]|$)); # - or space or braceright or caret or tilde or ()[] or eof
my $state = new Interpret_Melody_State;
my($last_pitch, $percussive_instrument);
my $main_instrument = 'Carillon';
my($tie_p);
my($note, $divisor, $dots, $volume) = (undef, 4, 0, $expressive_mark_to_midi_velocity{'mf'});
my($def_key, $def_value, $def_level, %def);
my($current_position, $position_at_end_of_last_recording);
my $grace_note_type;
my $voice;
for (my($s, @stack) = ($s0); $s =~ /\S/s; ) {
unless (defined $def_key) {
$s =~ s/^\s*//s;
$typesettable_version .= $&;
}
if ($s =~ /^\\([A-Za-z]+)\b/s && defined $def{$1}) { # expand variables
my($key) = $1; # we MUST store this in a variable for the substitution to work
$s =~ s/^\\$key/$def{$key}/s;
}
my $lhs;
my $directive;
log_debug sprintf 's=%s', Debug::cvs($s) if $debug > 2;
if ($s =~ s/^\%[^\n]*\n*//s) { # percent - comment to always discard
;
} elsif (!defined $def_key && $s =~ s/^([A-Za-z]+)\s*=\s*//s) {
($def_key, $def_value, $def_level) = ($1);
} elsif (defined $def_key) {
if ($s =~ s/^(\s+)//s) {
$def_value .= ' ';
} elsif ($s =~ s/^("[^""]*")//s) {
$def_value .= $1;
} elsif ($s =~ s/^((?:\x{7b}|<<))//s) { # braceleft
$def_value .= $1;
$def_level += 1;
} elsif ($s =~ s/^((?:\x{7d}|>>))//s) { # braceright
$def_value .= $1;
$def_level -= 1;
if ($def_level == 0) {
$def_value = $1 if $def_value =~ /^{\s*(.*?)\s*}$/s;
$def{$def_key} = $def_value;
($def_key, $def_value, $def_level) = ();
}
} elsif ($s =~ s/^(\S)//s) {
$def_value .= $1;
} else {
log_error "interpret_melody: defined \$def_key reached \"else\" case";
}
} elsif ($s =~ s/^\x{7b}\s*//s) { # braceleft
$typesettable_version .= $&;
$state->gsave();
} elsif ($s =~ s/^<>-\s*//s) { # ignore empty containers for expressive marks
$typesettable_version .= $&;
} elsif ($s =~ s/^<<\s*//s) { # FIXME
$typesettable_version .= $&;
$state->gsave();
} elsif ($s =~ s/^>>\s*//s) { # FIXME
$typesettable_version .= $&;
$state->grestore($s);
} elsif ($s =~ s/^[\^_]\\markup\s+//s) { # ignore markup
$typesettable_version .= $&;
} elsif ($s =~ s/^\\(?:halign\s+#\w+|markup|tiny)\s+//s) { # ignore markup
$typesettable_version .= $&;
} elsif ($s =~ s/^#\(\s*play-recording\s+"([^""]+)"\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)(?:\s+(\d+(?:\.\d+)?))?\s*\)\s+//s) { # pseudo-lisp
my($filename, $start, $end, $treat_as_this_many_beats) = ($1, $2, $3, $4);
# Generate pseudo-note directly instead of setting $directive ($directive needs an existing note to act on)
no integer;
my $duration = $end - $start;
my $unit = 4*$state->unit_beat();
my $unit_beats = $duration/$unit;
my $quantized_beats = int($unit_beats);
my @quantized_beats = (1) x $quantized_beats;
my $remainder = $unit_beats - $quantized_beats;
for (my $divisor = 2; $divisor < 32; $divisor *= 2) {
my $adjustment = 1/$divisor;
if (($remainder * $divisor) & 1) {
push @quantized_beats, $divisor;
$quantized_beats += $adjustment;
$remainder -= $adjustment;
}
}
my $fake_duration = $quantized_beats*$unit;
$fake_duration = $treat_as_this_many_beats*$state->unit_beat() if defined $treat_as_this_many_beats;
my $fake_note = ['ua', $fake_duration, $volume, undef, {
'directive' => ['play', $filename, $start, $end],
'durations' => [@quantized_beats],
}];
push @$voice, $fake_note;
# Generate a typesettable score that makes actual sense. We basically have two options: set it as a one-line percussion staff
# and show all the notes, or set it as a non-percussion staff (RhythmicStaff is perfect for this as it's one-line) and show
# a cluster that's just one black line. The good thing about separate notes is we can attach start and end times to the correct
# notes; we can't do this with clusters but separate notes are misleading given we're talking about recordings (no known notes).
# If we use a non-percussion staff b' (absolute) will look about right, otherwise ua is a good placeholder with no MIDI meaning.
#
# If Lilypond sees two consecutive clusters, it will merge them even though they are two separate clusters. The only way to
# prevent this is to insert a rest between them.
#
$typesettable_version .= sprintf('\set Staff.instrumentName = #"%s" \textLengthOn', $filename);
state $last_note_used;
my $use_clusters_p = !$state->drummode_p();
my $fmt0 = '_\markup{ \halign #%s \tiny "%s" }';
my($fmt1a, $fmt1b) = (sprintf($fmt0, 'LEFT', '%.2f'), sprintf($fmt0, 'RIGHT', '%.2f'));
my $clash_p = $use_clusters_p && defined $position_at_end_of_last_recording && $position_at_end_of_last_recording == $current_position;
my $note = !$use_clusters_p? 'da': !$clash_p? "c''": $last_note_used eq "c''"? "a'": "c''";
my $markup = sprintf($fmt1a, $start);
for my $pass (!$use_clusters_p? ('normal'): ('cluster', 'ghost')) {
my $last_duration;
my $tie = ' ';
$typesettable_version .= "<<\n" if $pass eq 'cluster';
$typesettable_version .= "\\\\\n" if $pass eq 'ghost';
$typesettable_version .= '\makeClusters ' if $pass eq 'cluster';
$typesettable_version .= "{\n\\absolute {\n" if $use_clusters_p;
$typesettable_version .= '\voiceOne ' if $pass eq 'ghost';
$typesettable_version .= sprintf("%s\n", join(' ', map {"\\hide $_"} ($pass eq 'ghost'? qw(NoteHead Rest Stem Dots Tie): qw(Rest))));
my($gap, @effective_quantized_beats) = (undef, @quantized_beats);
if ($pass eq 'cluster' && $clash_p) {
$gap = 128;
for (; $quantized_beats[$#quantized_beats] != $gap;) {
my $n = pop @quantized_beats;
$n *= 2;
push @quantized_beats, $n;
push @quantized_beats, $n unless $n == $gap;
}
}
$typesettable_version .= " r$gap" if defined $gap;
for my $duration (@quantized_beats) {
if (!$duration) {
;
} elsif (defined $last_duration && $last_duration == $duration/2) {
$typesettable_version .= '.';
} else {
$typesettable_version .= sprintf('%s%s%d', $tie, $note, $duration);
if ($pass ne 'cluster') {
$typesettable_version .= $markup;
$markup = undef;
}
}
$tie = '~';
$last_duration = $duration;
}
$typesettable_version .= $markup if $pass ne 'cluster' && defined $markup;
$typesettable_version .= sprintf($fmt1b, $end) if $pass ne 'cluster';
$typesettable_version .= "}\n" if $use_clusters_p; # close \absolute
$typesettable_version .= "}\n" if $use_clusters_p;
}
$typesettable_version .= ">>\n" if $use_clusters_p;
$last_note_used = $note;
# Update current position manually
$current_position += $duration;
$position_at_end_of_last_recording = $current_position;
} elsif ($s =~ s/^"((?:\\"|[^"])*)"//s) { # text
$typesettable_version .= $&;
my($s) = ($1);
} elsif ($s =~ s/^\\(laisserVibrer)\s+//s) { # ignore \laisserVibrer for now
$typesettable_version .= $&;
$directive = $1;
} elsif ($s =~ s/^\\(acciaccatura)\s+//s) { # ignore \acciaccatura for now
$typesettable_version .= $&;
$grace_note_type = $1;
} elsif ($s =~ s/^\\key\s+$pitch_re\s+\\(?:major|minor)\s+//s) { # ignore \key
$typesettable_version .= $&;
} elsif ($s =~ s/^\\partial\s+$duration_re\s+//s) { # ignore \partial
$typesettable_version .= $&;
} elsif ($s =~ s/^\\mark\s+(?:\\default|#\d+|"[^""]+")\s+//s) { # ignore \mark
$typesettable_version .= $&;
} elsif ($s =~ s/^\\set\s+Score\.markFormatter\s+=\s+#[-a-z]+\s+//s) { # ignore set mark formatter
$typesettable_version .= $&;
} elsif ($s =~ s/^\\textLengthOn\s+//s) { # ignore \textLengthOn
$typesettable_version .= $&;
} elsif ($s =~ s/^\\omit\s+[A-Z][A-Za-z]+(?:\.[A-Z][A-Za-z]+)+\s+//s) { # ignore \omit
$typesettable_version .= $&;
} elsif ($s =~ s/^\\new\s+(?:(?:(Drum)|Rhythmic)?Staff|Voice)\s+(?:\\with \{[^\{}]+})?//s || $s =~ s/^\\\\\s*//s) {
$typesettable_version .= $&;
# FIXME - do we need to gsave?
$state->drummode_p(1) if $1;
push @$it, $voice if $voice;
$voice = undef;
} elsif ($s =~ s/^\\voice(?:One|Two|Three|Four)\s+//s) {
$typesettable_version .= $&;
} elsif ($s =~ s/^\\score\s+\x{7b}\s*//s) {
$typesettable_version .= $&;
$state->gsave();
} elsif ($s =~ s/^\\(?:drums|drummode)\s*\x{7b}//s) {
$typesettable_version .= $&;
$state->gsave();
$state->drummode_p(1);
# FIXME - do we need to push voice?
} elsif ($s =~ s/^\\absolute\s*\x{7b}//s) {
$typesettable_version .= $&;
$state->gsave();
$state->relative_p(0);
} elsif ($s =~ s/^\\relative\s*\x{7b}//s) {
$typesettable_version .= $&;
$state->gsave();
$state->relative_p(1);
$last_pitch = undef;
} elsif ($s =~ s/^\\relative\s+($pitch_re)\s*\x{7b}//s) {
$typesettable_version .= $&;
$state->gsave();
$state->relative_p(1);
$last_pitch = interpret_absolute_pitch $1;
} elsif ($s =~ s/^\\transpose\s+($pitch_re)\s+($pitch_re)\s*\x{7b}//s) {
$typesettable_version .= $&;
my($from, $to) = (interpret_absolute_pitch $1, interpret_absolute_pitch $5);
$state->gsave();
$state->relative_p(0);
$state->transpose($state->transpose() + $to - $from);
} elsif ($s =~ s/^\\repeat\s+(?:volta|unfold|percent)\s+(\d+)\s*\x{7b}//s) {
$typesettable_version .= $&;
my $n = $1 + 0;
$state->gsave();
$state->repeat_stacklevel($state->stacklevel());
$state->repeat_count($n);
$state->repeat_start(defined $voice? scalar @$voice: 0);
} elsif ($s =~ s/^\x{7d}\s*//s) { # braceright
$typesettable_version .= $&;
if (defined $state->repeat_stacklevel() && $state->repeat_stacklevel() == $state->stacklevel()) {
my @A = @$voice;
my $i = $state->repeat_start();
my $n = $state->repeat_count();
$voice = [@A[0 .. $i - 1], (@A[$i .. $#A]) x $n];
}
$state->grestore($s);
} elsif ($s =~ s/^[\[\]]\s*//s) { # ignore bracketleft/bracketright = beam on/beam off
$typesettable_version .= $&;
} elsif ($s =~ s/^\(\s*//s) { # ignore parenleft = phrasing slur start
$typesettable_version .= $&;
} elsif ($s =~ s/^\)\s*//s) { # ignore parenright = phrasing slur end
$typesettable_version .= $&;
} elsif ($s =~ s/^\|\s*//s) { # ignore bar checks
$typesettable_version .= $&;
} elsif ($s =~ s/^\~\s*//s) { # tie
$typesettable_version .= $&;
$tie_p = 1;
} elsif ($s =~ s/^(?:\\accent\b|->)//s) {
$typesettable_version .= $&;
$directive = 'accent';
} elsif ($s =~ s/^(?:\\staccato\b|-\.)//s) {
$typesettable_version .= $&;
$directive = 'staccato';
} elsif ($s =~ s/^\x{5e}\s*\\(fermata)\b//s) { # pause
$typesettable_version .= $&;
$directive = $1;
} elsif ($s =~ s/^\\tempo(?:\s+"[^""]+")?\s+(\d+)\s+=\s+(\d+)\s+//s) {
$typesettable_version .= $&;
$state->tempo($1, $2);
} elsif ($s =~ s/^\\time\s+\d+\/\d+\s+//s) { # ignore time signature
$typesettable_version .= $&;
} elsif ($s =~ s/^\\clef\s+"[^""]+"\s*//s) { # ignore clef change
$typesettable_version .= $&;
} elsif ($s =~ s/^\\breathe\s+//s) { # ignore breath marks for now
$typesettable_version .= $&;
} elsif ($s =~ s/^\\tuplet\s+(\d+)\/(\d+)\s*\x{7b}//s) {
$typesettable_version .= $&;
$state->gsave();
$state->unit_beat($state->unit_beat() * $2 / $1);
} elsif ($s =~ s/^$duration_re$end_re//s) {
$typesettable_version .= $&;
($divisor, $dots) = (interpret_divisor $1, length $2);
log_debug "Duration \"$divisor$dots\" encountered before any rest, pitch, or percussion instrument" unless defined $note;
$lhs = $note;
} elsif ($s =~ s/^$rest_re(?:$duration_re)?$end_re//s) {
$typesettable_version .= $&;
my($new_divisor, $new_dots) = ($1, $2);
($divisor, $dots) = (interpret_divisor $new_divisor, length $new_dots) if defined $new_divisor;
$lhs = 'r';
} elsif ($s =~ s/^(?!$end_re)($pitch_re)(?:$duration_re)?$end_re//s # make sure SOMETHING is matched ($pitch_re can match nothing)
|| $s =~ s/^<\s*($pitch_re)(?:\s+$pitch_re_no_captures)+\s*>(?:$duration_re)?$end_re//s) { # discard lower notes in chords
my $what = $&;
$typesettable_version .= $&;
my($pitch_as_written, $base_pitch, $lower, $raise, $new_divisor, $new_dots)
= ($1, ($ly_notes{$2} + 12)%12, 0 + length $3, 0 + length $4, $5, $6);
my $pitch;
if ($state->relative_p()) {
($last_pitch, $lower, $raise) = (interpret_absolute_pitch $pitch_as_written, undef, undef) if !defined $last_pitch;
my $last_base_pitch = ($last_pitch + 12)%12;
for (my $i = 0; $i < 8; $i += 1) {
for my $dir (-1, 1) {
my $candidate = $last_pitch + $dir*$i;
$pitch = $candidate if $candidate%12 == $base_pitch;
last if defined $pitch;
}
last if defined $pitch;
}
$pitch += 12*($raise - $lower);
} else {
$pitch = interpret_absolute_pitch $pitch_as_written;
}
$pitch += $state->transpose() if defined $pitch;
($divisor, $dots) = (interpret_divisor $new_divisor, length $new_dots) if defined $new_divisor;
$lhs = $midi_number_to_note[$pitch];
die "interpret_melody error: note $pitch_as_written out of range\n" unless defined $lhs;
$last_pitch = $pitch;
} elsif ($s =~ s/^($percussion_instrument_re)(?:$duration_re)?$end_re//s) {
$typesettable_version .= $&;
($percussive_instrument, my $new_divisor, my $new_dots) = ($1, $2, $3);
($divisor, $dots) = (interpret_divisor $new_divisor, length $new_dots) if defined $new_divisor;
$lhs = $percussive_instrument;
} elsif ($s =~ s/^\\($expressive_mark_re)\b//s) {
$typesettable_version .= $&;
$volume = $expressive_mark_to_midi_velocity{$1};
} elsif ($s =~ s/^\\set\s+Staff\.instrumentName\s+=\s+#"([^""]+)"\s*//s) {
$typesettable_version .= $&;
$main_instrument = $1;
} elsif ($s =~ s/^(\S+)//s) {
$typesettable_version .= $&;
log_debug sprintf('Unknown expression "%s" near "%s" discarded', $1, $');
} else {
$typesettable_version .= $&;
log_debug "Internal error: \"else\" case reached in interpret_melody, s=($s)";
}
if (defined $lhs) {
my $rhs = $state->unit_beat() * calculate_beat_length($divisor, $dots);
if ($tie_p) {
if (!defined $note) {
$tie_p = 0;
log_error "Tie ignored because there is no note to tie to";
} elsif ($note ne $lhs) {
$tie_p = 0;
log_error "Tie ignored because $note and $lhs are different";
} else {
$voice->[+scalar @$voice - 1][1] += $rhs;
}
}
my $rest_p = $lhs eq 'r';
my $instrument = ($lhs eq $percussive_instrument || $rest_p)? undef: $main_instrument; # FIXME
my $node = [$lhs, $rhs, ($rest_p? undef: $volume), $instrument] unless $tie_p;
if (defined $grace_note_type) { # zero out the note's duration, in effect ignoring all grace notes for now
$node->[1] = 0;
$node->[4] = {'actual-duration' => $rhs};
}
push @$voice, $node if defined $node;
$note = $lhs;
$tie_p = 0;
$grace_note_type = undef;
no integer;
$current_position += $rhs;
} elsif (defined $directive) {
my $verb = ref $directive? $directive->[0]: $directive;
if (!defined $note) {
log_error "Directive $verb ignored because there is no note before it";
} elsif ($verb eq 'accent') {
my $volume = $voice->[+scalar @$voice - 1]->[2];
if (defined $volume) {
no integer;
$volume *= 1.44;
$volume = 127 if $volume > 127;
$voice->[+scalar @$voice - 1]->[2] = $volume;
}
} elsif ($verb eq 'staccato') {
my $node = $voice->[+scalar @$voice - 1];
no integer;
$node->[4]->{'actual-duration'} = $node->[1]/4;
} elsif ($verb eq 'fermata') {
$voice->[+scalar @$voice - 1]->[1] *= 2; # FIXME
} elsif ($verb eq 'laisserVibrer') {
my $node = $voice->[+scalar @$voice - 1];
$node->[4]->{'laisser-vibrer'} = 1;
} else {
log_error "interpret_melody: Unknown directive \"$verb\"";
}
}
}
push @$it, $voice if $voice;
log_debug sprintf "%s interpreted as %s", $s0,
join(" \\\\ ", map { join(' ', map { $_->[0] } @$_) } @$it) if $debug > 2;
return wantarray? ($it, $typesettable_version): $it;
}
sub event_id ($$;$) {
my($mode, $event, $melody) = @_;
return join('-', map { defined $_? s/[^\.\w]+/_/sgr: () } ($mode, $melody, $event));
}
sub define_event_internal_real ($$$$$$$%) {
my($mode, $melody, $description, $composer, $year, $source, $shared_defs, %event_defs) = @_;
my %it;
my($t0, $thing) = (eval { no integer; Time::HiRes::time },
(defined $melody? $melody: join(' ', ($mode, sort keys %event_defs))) =~ s/^\s+//sr);