]> git.xonotic.org Git - xonotic/xonotic.git/blob - misc/tools/midi2cfg-ng.pl
fixes in killing notes
[xonotic/xonotic.git] / misc / tools / midi2cfg-ng.pl
1 #!/usr/bin/perl
2
3 # converter from Type 1 MIDI files to CFG files that control bots with the Tuba and other weapons for percussion (requires g_weaponarena all)
4
5 use strict;
6 use warnings;
7 use MIDI;
8 use MIDI::Opus;
9 use Storable;
10
11 # workaround for possible refire time problems
12 use constant SYS_TICRATE => 0.033333;
13 #use constant SYS_TICRATE => 0;
14
15 use constant MIDI_FIRST_NONCHANNEL => 17;
16 use constant MIDI_DRUMS_CHANNEL => 10;
17
18 die "Usage: $0 filename.conf midifile1 transpose1 midifile2 transpose2 ..."
19         unless @ARGV > 1 and @ARGV % 2;
20
21 my $timeoffset_preinit = 2;
22 my $timeoffset_postinit = 2;
23 my $timeoffset_predone = 2;
24 my $timeoffset_postdone = 2;
25 my $timeoffset_preintermission = 2;
26 my $timeoffset_postintermission = 2;
27
28 my ($config, @midilist) = @ARGV;
29
30 sub unsort(@)
31 {
32         return map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, rand] } @_;
33 }
34
35 sub override($$);
36 sub override($$)
37 {
38         my ($dest, $src) = @_;
39         if(ref $src eq 'HASH')
40         {
41                 $dest = {}
42                         if not defined $dest;
43                 for(keys %$src)
44                 {
45                         $dest->{$_} = override $dest->{$_}, $src->{$_};
46                 }
47         }
48         elsif(ref $src eq 'ARRAY')
49         {
50                 $dest = []
51                         if not defined $dest;
52                 for(@$src)
53                 {
54                         push @$dest, override undef, $_;
55                 }
56         }
57         elsif(ref $src)
58         {
59                 $dest = Storable::dclone $src;
60         }
61         else
62         {
63                 $dest = $src;
64         }
65         return $dest;
66 }
67
68 my $precommands = "";
69 my $commands = "";
70 my $busybots;
71 my @busybots_allocated;
72 my %notechannelbots;
73 my $transpose = 0;
74 my $notetime = undef;
75 my $lowestnotestart = undef;
76 my $noalloc = 0;
77 sub botconfig_read($)
78 {
79         my ($fn) = @_;
80         my %bots = ();
81         open my $fh, "<", $fn
82                 or die "<$fn: $!";
83         
84         my $currentbot = undef;
85         my $appendref = undef;
86         my $super = undef;
87         while(<$fh>)
88         {
89                 chomp;
90                 s/\s*#.*//;
91                 next if /^$/;
92                 if(s/^\t\t//)
93                 {
94                         my @cmd = split /\s+/, $_;
95                         if($cmd[0] eq 'super')
96                         {
97                                 push @$appendref, @$super
98                                         if $super;
99                         }
100                         elsif($cmd[0] eq 'percussion') # simple import
101                         {
102                                 push @$appendref, @{$currentbot->{percussion}->{$cmd[1]}};
103                         }
104                         else
105                         {
106                                 push @$appendref, \@cmd;
107                         }
108                 }
109                 elsif(s/^\t//)
110                 {
111                         if(/^include (.*)/)
112                         {
113                                 my $base = $bots{$1};
114                                 $currentbot = override $currentbot, $base;
115                         }
116                         elsif(/^count (\d+)/)
117                         {
118                                 $currentbot->{count} = $1;
119                         }
120                         elsif(/^transpose (\d+)/)
121                         {
122                                 $currentbot->{transpose} ||= 0;
123                                 $currentbot->{transpose} += $1;
124                         }
125                         elsif(/^channels (.*)/)
126                         {
127                                 $currentbot->{channels} = { map { $_ => 1 } split /\s+/, $1 };
128                         }
129                         elsif(/^programs (.*)/)
130                         {
131                                 $currentbot->{programs} = { map { $_ => 1 } split /\s+/, $1 };
132                         }
133                         elsif(/^init$/)
134                         {
135                                 $super = $currentbot->{init};
136                                 $currentbot->{init} = $appendref = [];
137                         }
138                         elsif(/^intermission$/)
139                         {
140                                 $super = $currentbot->{intermission};
141                                 $currentbot->{intermission} = $appendref = [];
142                         }
143                         elsif(/^done$/)
144                         {
145                                 $super = $currentbot->{done};
146                                 $currentbot->{done} = $appendref = [];
147                         }
148                         elsif(/^note on (-?\d+)/)
149                         {
150                                 $super = $currentbot->{notes_on}->{$1};
151                                 $currentbot->{notes_on}->{$1} = $appendref = [];
152                         }
153                         elsif(/^note off (-?\d+)/)
154                         {
155                                 $super = $currentbot->{notes_off}->{$1};
156                                 $currentbot->{notes_off}->{$1} = $appendref = [];
157                         }
158                         elsif(/^percussion (\d+)/)
159                         {
160                                 $super = $currentbot->{percussion}->{$1};
161                                 $currentbot->{percussion}->{$1} = $appendref = [];
162                         }
163                         elsif(/^vocals$/)
164                         {
165                                 $super = $currentbot->{vocals};
166                                 $currentbot->{vocals} = $appendref = [];
167                         }
168                         else
169                         {
170                                 print "unknown command: $_\n";
171                         }
172                 }
173                 elsif(/^bot (.*)/)
174                 {
175                         $currentbot = ($bots{$1} ||= {count => 0});
176                 }
177                 elsif(/^raw (.*)/)
178                 {
179                         $precommands .= "$1\n";
180                 }
181                 elsif(/^timeoffset_preinit (.*)/)
182                 {
183                         $timeoffset_preinit = $1;
184                 }
185                 elsif(/^timeoffset_postinit (.*)/)
186                 {
187                         $timeoffset_postinit = $1;
188                 }
189                 elsif(/^timeoffset_predone (.*)/)
190                 {
191                         $timeoffset_predone = $1;
192                 }
193                 elsif(/^timeoffset_postdone (.*)/)
194                 {
195                         $timeoffset_postdone = $1;
196                 }
197                 elsif(/^timeoffset_preintermission (.*)/)
198                 {
199                         $timeoffset_preintermission = $1;
200                 }
201                 elsif(/^timeoffset_postintermission (.*)/)
202                 {
203                         $timeoffset_postintermission = $1;
204                 }
205                 else
206                 {
207                         print "unknown command: $_\n";
208                 }
209         }
210
211         for(values %bots)
212         {
213                 for(values %{$_->{notes_on}}, values %{$_->{percussion}})
214                 {
215                         my $t = $_->[0]->[0] eq 'time' ? $_->[0]->[1] : 0;
216                         $lowestnotestart = $t if not defined $lowestnotestart or $t < $lowestnotestart;
217                 }
218         }
219
220         return \%bots;
221 }
222 my $busybots_orig = botconfig_read $config;
223
224
225 # returns: ($mintime, $maxtime, $busytime)
226 sub busybot_cmd_bot_cmdinfo(@)
227 {
228         my (@commands) = @_;
229
230         my $mintime = undef;
231         my $maxtime = undef;
232         my $busytime = undef;
233
234         for(@commands)
235         {
236                 if($_->[0] eq 'time')
237                 {
238                         $mintime = $_->[1]
239                                 if not defined $mintime or $_->[1] < $mintime;
240                         $maxtime = $_->[1] + SYS_TICRATE
241                                 if not defined $maxtime or $_->[1] + SYS_TICRATE > $maxtime;
242                 }
243                 elsif($_->[0] eq 'busy')
244                 {
245                         $busytime = $_->[1] + SYS_TICRATE;
246                 }
247         }
248
249         return ($mintime, $maxtime, $busytime);
250 }
251
252 sub busybot_cmd_bot_matchtime($$$@)
253 {
254         my ($bot, $targettime, $targetbusytime, @commands) = @_;
255
256         # I want to execute @commands so that I am free on $targettime and $targetbusytime
257         # when do I execute it then?
258
259         my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @commands;
260
261         my $tstart_max = defined $maxtime ? $targettime - $maxtime : $targettime;
262         my $tstart_busy = defined $busytime ? $targetbusytime - $busytime : $targettime;
263
264         return $tstart_max < $tstart_busy ? $tstart_max : $tstart_busy;
265 }
266
267 # TODO function to find out whether, and when, to insert a command before another command to make it possible
268 # (note-off before note-on)
269
270 sub busybot_cmd_bot_test($$$@)
271 {
272         my ($bot, $time, $force, @commands) = @_;
273
274         my $bottime = defined $bot->{timer} ? $bot->{timer} : -1;
275         my $botbusytime = defined $bot->{busytimer} ? $bot->{busytimer} : -1;
276
277         my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @commands;
278
279         if($time < $botbusytime)
280         {
281                 warn "FORCE: $time < $botbusytime"
282                         if $force;
283                 return $force;
284         }
285         
286         if(defined $mintime and $time + $mintime < $bottime)
287         {
288                 warn "FORCE: $time + $mintime < $bottime"
289                         if $force;
290                 return $force;
291         }
292         
293         return 1;
294 }
295
296 sub busybot_cmd_bot_execute($$@)
297 {
298         my ($bot, $time, @commands) = @_;
299
300         for(@commands)
301         {
302                 if($_->[0] eq 'time')
303                 {
304                         $commands .= sprintf "sv_cmd bot_cmd %d wait_until %f\n", $bot->{id}, $time + $_->[1];
305                         if($bot->{timer} > $time + $_->[1] + SYS_TICRATE)
306                         {
307                                 #use Carp; carp "Negative wait: $bot->{timer} <= @{[$time + $_->[1] + SYS_TICRATE]}";
308                         }
309                         $bot->{timer} = $time + $_->[1] + SYS_TICRATE;
310                 }
311                 elsif($_->[0] eq 'busy')
312                 {
313                         $bot->{busytimer} = $time + $_->[1] + SYS_TICRATE;
314                 }
315                 elsif($_->[0] eq 'buttons')
316                 {
317                         my %buttons_release = %{$bot->{buttons} ||= {}};
318                         for(@{$_}[1..@$_-1])
319                         {
320                                 /(.*)\??/ or next;
321                                 delete $buttons_release{$1};
322                         }
323                         for(keys %buttons_release)
324                         {
325                                 $commands .= sprintf "sv_cmd bot_cmd %d releasekey %s\n", $bot->{id}, $_;
326                                 delete $bot->{buttons}->{$_};
327                         }
328                         for(@{$_}[1..@$_-1])
329                         {
330                                 /(.*)(\?)?/ or next;
331                                 defined $2 and next;
332                                 $commands .= sprintf "sv_cmd bot_cmd %d presskey %s\n", $bot->{id}, $_;
333                                 $bot->{buttons}->{$_} = 1;
334                         }
335                 }
336                 elsif($_->[0] eq 'cmd')
337                 {
338                         $commands .= sprintf "sv_cmd bot_cmd %d %s\n", $bot->{id}, join " ", @{$_}[1..@$_-1];
339                 }
340                 elsif($_->[0] eq 'barrier')
341                 {
342                         $commands .= sprintf "sv_cmd bot_cmd %d barrier\n", $bot->{id};
343                         $bot->{timer} = $bot->{busytimer} = 0;
344                 }
345                 elsif($_->[0] eq 'raw')
346                 {
347                         $commands .= sprintf "%s\n", join " ", @{$_}[1..@$_-1];
348                 }
349         }
350
351         return 1;
352 }
353
354 my $intermissions = 0;
355
356 sub busybot_intermission_bot($)
357 {
358         my ($bot) = @_;
359         busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preintermission];
360         busybot_cmd_bot_execute $bot, 0, ['barrier'];
361         if($bot->{intermission})
362         {
363                 busybot_cmd_bot_execute $bot, 0, @{$bot->{intermission}};
364         }
365         busybot_cmd_bot_execute $bot, 0, ['barrier'];
366         $notetime = $timeoffset_postintermission - $lowestnotestart;
367 }
368
369 #my $busy = 0;
370 sub busybot_note_off_bot($$$$)
371 {
372         my ($bot, $time, $channel, $note) = @_;
373         #print STDERR "note off $bot:$time:$channel:$note\n";
374         my ($busychannel, $busynote, $cmds) = @{$bot->{busy}};
375         return 1
376                 if not defined $cmds; # note off cannot fail
377         die "Wrong note-off?!?"
378                 if $busychannel != $channel || $busynote ne $note;
379         $bot->{busy} = undef;
380
381         my $t = $time + $notetime;
382         my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @$cmds;
383
384         # perform note-off "as soon as we can"
385         $t = $bot->{busytimer}
386                 if $t < $bot->{busytimer};
387         $t = $bot->{timer} - $mintime
388                 if $t < $bot->{timer} - $mintime;
389
390         busybot_cmd_bot_execute $bot, $t, @$cmds; 
391         return 1;
392 }
393
394 sub busybot_get_cmds_bot($$$)
395 {
396         my ($bot, $channel, $note) = @_;
397         my ($k0, $k1, $cmds, $cmds_off) = (undef, undef, undef, undef);
398         if($channel <= 0)
399         {
400                 # vocals
401                 $cmds = $bot->{vocals};
402                 if(defined $cmds)
403                 {
404                         $cmds = [ map { [ map { $_ eq '%s' ? $note : $_ } @$_ ] } @$cmds ];
405                 }
406                 $k0 = "vocals";
407                 $k1 = $channel;
408         }
409         elsif($channel == 10)
410         {
411                 # percussion
412                 $cmds = $bot->{percussion}->{$note};
413                 $k0 = "percussion";
414                 $k1 = $note;
415         }
416         else
417         {
418                 # music
419                 $cmds = $bot->{notes_on}->{$note - ($bot->{transpose} || 0) - $transpose};
420                 $cmds_off = $bot->{notes_off}->{$note - ($bot->{transpose} || 0) - $transpose};
421                 $k0 = "note";
422                 $k1 = $note - ($bot->{transpose} || 0) - $transpose;
423         }
424         return ($cmds, $cmds_off, $k0, $k1);
425 }
426
427 sub busybot_note_on_bot($$$$$$$)
428 {
429         my ($bot, $time, $channel, $program, $note, $init, $force) = @_;
430         return -1 # I won't play on this channel
431                 if defined $bot->{channels} and not $bot->{channels}->{$channel};
432         return -1 # I won't play this program
433                 if defined $bot->{programs} and not $bot->{programs}->{$program};
434
435         my ($cmds, $cmds_off, $k0, $k1) = busybot_get_cmds_bot($bot, $channel, $note);
436
437         return -1 # I won't play this note
438                 if not defined $cmds;
439         return 0
440                 if $bot->{busy};
441         #print STDERR "note on $bot:$time:$channel:$note\n";
442         if($init)
443         {
444                 return 0
445                         if not busybot_cmd_bot_test $bot, $time + $notetime, $force, @$cmds; 
446                 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preinit];
447                 busybot_cmd_bot_execute $bot, 0, ['barrier'];
448                 busybot_cmd_bot_execute $bot, 0, @{$bot->{init}}
449                         if @{$bot->{init}};
450                 busybot_cmd_bot_execute $bot, 0, ['barrier'];
451                 for(1..$intermissions)
452                 {
453                         busybot_intermission_bot $bot;
454                 }
455                 # we always did a barrier, so we know this works
456                 busybot_cmd_bot_execute $bot, $time + $notetime, @$cmds; 
457         }
458         else
459         {
460                 return 0
461                         if not busybot_cmd_bot_test $bot, $time + $notetime, $force, @$cmds; 
462                 busybot_cmd_bot_execute $bot, $time + $notetime, @$cmds; 
463         }
464         if(defined $cmds and defined $cmds_off)
465         {
466                 $bot->{busy} = [$channel, $note, $cmds_off];
467         }
468         ++$bot->{seen}{$k0}{$k1};
469         return 1;
470 }
471
472 sub busybots_reset()
473 {
474         $busybots = Storable::dclone $busybots_orig;
475         @busybots_allocated = ();
476         %notechannelbots = ();
477         $transpose = 0;
478         $notetime = $timeoffset_postinit - $lowestnotestart;
479 }
480
481 sub busybot_note_off($$$)
482 {
483         my ($time, $channel, $note) = @_;
484
485 #       print STDERR "note off $time:$channel:$note\n";
486
487         return 0
488                 if $channel <= 0;
489         return 0
490                 if $channel == 10;
491
492         if(my $bot = $notechannelbots{$channel}{$note})
493         {
494                 busybot_note_off_bot $bot, $time, $channel, $note;
495                 delete $notechannelbots{$channel}{$note};
496                 return 1;
497         }
498
499         return 0;
500 }
501
502 sub busybot_note_on($$$$)
503 {
504         my ($time, $channel, $program, $note) = @_;
505
506         if($notechannelbots{$channel}{$note})
507         {
508                 busybot_note_off $time, $channel, $note;
509         }
510
511 #       print STDERR "note on $time:$channel:$note\n";
512
513         my $overflow = 0;
514
515         my @epicfailbots = ();
516
517         for(unsort @busybots_allocated)
518         {
519                 my $canplay = busybot_note_on_bot $_, $time, $channel, $program, $note, 0, 0;
520                 if($canplay > 0)
521                 {
522                         $notechannelbots{$channel}{$note} = $_;
523                         return 1;
524                 }
525                 push @epicfailbots, $_
526                         if $canplay == 0;
527                 # wrong
528         }
529
530         my $needalloc = 0;
531
532         for(unsort keys %$busybots)
533         {
534                 next if $busybots->{$_}->{count} <= 0;
535                 my $bot = Storable::dclone $busybots->{$_};
536                 $bot->{id} = @busybots_allocated + 1;
537                 $bot->{classname} = $_;
538                 my $canplay = busybot_note_on_bot $bot, $time, $channel, $program, $note, 1, 0;
539                 if($canplay > 0)
540                 {
541                         if($noalloc)
542                         {
543                                 $needalloc = 1;
544                         }
545                         else
546                         {
547                                 --$busybots->{$_}->{count};
548                                 $notechannelbots{$channel}{$note} = $bot;
549                                 push @busybots_allocated, $bot;
550                                 return 1;
551                         }
552                 }
553                 die "Fresh bot cannot play stuff"
554                         if $canplay == 0;
555         }
556
557         if(@epicfailbots)
558         {
559                 # we cannot add a new bot to play this
560                 # we could try finding a bot that could play this, and force him to stop the note!
561
562                 my @candidates = (); # contains: [$bot, $score, $offtime]
563
564                 # put in all currently busy bots that COULD play this, if they did a note-off first
565                 for my $bot(@epicfailbots)
566                 {
567                         next
568                                 if $busybots->{$bot->{classname}}->{count} != 0;
569                         next
570                                 unless $bot->{busy};
571                         my ($busy_chan, $busy_note, $busy_cmds_off) = @{$bot->{busy}};
572                         next
573                                 unless $busy_cmds_off;
574                         my ($cmds, $cmds_off, $k0, $k1) = busybot_get_cmds_bot $bot, $channel, $note;
575                         next
576                                 unless $cmds;
577                         my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @$cmds;
578                         my ($mintime_off, $maxtime_off, $busytime_off) = busybot_cmd_bot_cmdinfo @$busy_cmds_off;
579
580                         my $noteofftime = busybot_cmd_bot_matchtime $bot, $time + $notetime + $mintime, $time + $notetime, @$busy_cmds_off;
581                         next
582                                 if $noteofftime < $bot->{busytimer};
583                         next
584                                 if $noteofftime + $mintime_off < $bot->{timer};
585
586                         my $score = 0;
587                         # prefer turning off long notes
588                         $score +=  100 * ($noteofftime - $bot->{timer});
589                         # prefer turning off low notes
590                         $score +=    1 * (-$note);
591                         # prefer turning off notes that already play on another channel
592                         $score += 1000 * (grep { $_ != $busy_chan && $notechannelbots{$_}{$busy_note} && $notechannelbots{$_}{$busy_note}{busy} } keys %notechannelbots);
593
594                         push @candidates, [$bot, $score, $noteofftime];
595                 }
596
597                 # we found one?
598
599                 if(@candidates)
600                 {
601                         @candidates = sort { $a->[1] <=> $b->[1] } @candidates;
602                         my ($bot, $score, $offtime) = @{(pop @candidates)};
603                         my $oldchan = $bot->{busy}->[0];
604                         my $oldnote = $bot->{busy}->[1];
605                         busybot_note_off $offtime - $notetime, $oldchan, $oldnote;
606                         my $canplay = busybot_note_on_bot $bot, $time, $channel, $program, $note, 0, 1;
607                         die "Canplay but not?"
608                                 if $canplay <= 0;
609                         warn "Made $channel:$note play by stopping $oldchan:$oldnote";
610                         $notechannelbots{$channel}{$note} = $bot;
611                         return 1;
612                 }
613         }
614
615         die "noalloc\n"
616                 if $needalloc;
617
618         if(@epicfailbots)
619         {
620                 warn "Not enough bots to play this (when playing $channel:$note)";
621 #               for(@epicfailbots)
622 #               {
623 #                       my $b = $_->{busy};
624 #                       warn "$_->{classname} -> @{[$b ? qq{$b->[0]:$b->[1]} : 'none']} @{[$_->{timer} - $notetime]} ($time)\n";
625 #               }
626         }
627         else
628         {
629                 warn "Note $channel:$note cannot be played by any bot";
630         }
631
632         return 0;
633 }
634
635 sub Preallocate(@)
636 {
637         my (@preallocate) = @_;
638         busybots_reset();
639         for(@preallocate)
640         {
641                 die "Cannot preallocate any more $_ bots"
642                         if $busybots->{$_}->{count} <= 0;
643                 my $bot = Storable::dclone $busybots->{$_};
644                 $bot->{id} = @busybots_allocated + 1;
645                 $bot->{classname} = $_;
646                 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preinit];
647                 busybot_cmd_bot_execute $bot, 0, ['barrier'];
648                 busybot_cmd_bot_execute $bot, 0, @{$bot->{init}}
649                         if @{$bot->{init}};
650                 busybot_cmd_bot_execute $bot, 0, ['barrier'];
651                 --$busybots->{$_}->{count};
652                 push @busybots_allocated, $bot;
653         }
654 }
655
656 sub ConvertMIDI($$)
657 {
658         my ($filename, $trans) = @_;
659         $transpose = $trans;
660
661         my $opus = MIDI::Opus->new({from_file => $filename});
662         my $ticksperquarter = $opus->ticks();
663         my $tracks = $opus->tracks_r();
664         my @tempi = (); # list of start tick, time per tick pairs (calculated as seconds per quarter / ticks per quarter)
665         my $tick;
666
667         $tick = 0;
668         for($tracks->[0]->events())
669         {   
670                 $tick += $_->[1];
671                 if($_->[0] eq 'set_tempo')
672                 {   
673                         push @tempi, [$tick, $_->[2] * 0.000001 / $ticksperquarter];
674                 }
675         }
676         my $tick2sec = sub
677         {
678                 my ($tick) = @_;
679                 my $sec = 0;
680                 my $curtempo = [0, 0.5 / $ticksperquarter];
681                 for(@tempi)
682                 {
683                         if($_->[0] < $tick)
684                         {
685                                 # this event is in the past
686                                 # we add the full time since the last one then
687                                 $sec += ($_->[0] - $curtempo->[0]) * $curtempo->[1];
688                         }   
689                         else
690                         {
691                                 # if this event is in the future, we break
692                                 last;
693                         }
694                         $curtempo = $_;
695                 }
696                 $sec += ($tick - $curtempo->[0]) * $curtempo->[1];
697                 return $sec;
698         };
699
700         # merge all to a single track
701         my @allmidievents = ();
702         my $sequence = 0;
703         for my $track(0..@$tracks-1)
704         {
705                 $tick = 0;
706                 for($tracks->[$track]->events())
707                 {
708                         my ($command, $delta, @data) = @$_;
709                         $command = 'note_off' if $command eq 'note_on' and $data[2] == 0;
710                         $tick += $delta;
711                         push @allmidievents, [$command, $tick, $sequence++, $track, @data];
712                 }
713         }
714
715         if(open my $fh, "$filename.vocals")
716         {
717                 my $scale = 1;
718                 my $shift = 0;
719                 for(<$fh>)
720                 {
721                         chomp;
722                         my ($tick, $file) = split /\s+/, $_;
723                         if($tick eq 'scale')
724                         {
725                                 $scale = $file;
726                         }
727                         elsif($tick eq 'shift')
728                         {
729                                 $shift = $file;
730                         }
731                         else
732                         {
733                                 push @allmidievents, ['note_on', $tick * $scale + $shift, $sequence++, -1, -1, $file];
734                                 push @allmidievents, ['note_off', $tick * $scale + $shift, $sequence++, -1, -1, $file];
735                         }
736                 }
737         }
738
739         @allmidievents = sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2] } @allmidievents;
740
741         my %midinotes = ();
742         my $notes_stuck = 0;
743         my %notes_seen = ();
744         my %programs = ();
745         my $t = 0;
746         for(@allmidievents)
747         {
748                 $t = $tick2sec->($_->[1]);
749                 my $track = $_->[3];
750                 if($_->[0] eq 'note_on')
751                 {
752                         my $chan = $_->[4] + 1;
753                         ++$notes_seen{$chan}{($programs{$chan} || 1)}{$_->[5]}
754                                 if $chan != 10 and $chan > 0;
755                         if($midinotes{$chan}{$_->[5]})
756                         {
757                                 --$notes_stuck;
758                                 busybot_note_off($t - SYS_TICRATE, $chan, $_->[5]);
759                         }
760                         busybot_note_on($t, $chan, $programs{$chan} || 1, $_->[5]);
761                         ++$notes_stuck;
762                         $midinotes{$chan}{$_->[5]} = 1;
763                 }
764                 elsif($_->[0] eq 'note_off')
765                 {
766                         my $chan = $_->[4] + 1;
767                         if($midinotes{$chan}{$_->[5]})
768                         {
769                                 --$notes_stuck;
770                                 busybot_note_off($t - SYS_TICRATE, $chan, $_->[5]);
771                         }
772                         $midinotes{$chan}{$_->[5]} = 0;
773                 }
774                 elsif($_->[0] eq 'patch_change')
775                 {
776                         my $chan = $_->[4] + 1;
777                         my $program = $_->[5] + 1;
778                         $programs{$chan} = $program;
779                 }
780         }
781
782         print STDERR "For file $filename:\n";
783         print STDERR "  Stuck notes: $notes_stuck\n";
784
785         for my $testtranspose(-127..127)
786         {
787                 my $toohigh = 0;
788                 my $toolow = 0;
789                 my $good = 0;
790                 for my $channel(sort keys %notes_seen)
791                 {
792                         for my $program(sort keys %{$notes_seen{$channel}})
793                         {
794                                 for my $note(sort keys %{$notes_seen{$channel}{$program}})
795                                 {
796                                         my $cnt = $notes_seen{$channel}{$program}{$note};
797                                         my $votehigh = 0;
798                                         my $votelow = 0;
799                                         my $votegood = 0;
800                                         for(@busybots_allocated)
801                                         {
802                                                 next # I won't play on this channel
803                                                         if defined $_->{channels} and not $_->{channels}->{$channel};
804                                                 next # I won't play this program
805                                                         if defined $_->{programs} and not $_->{programs}->{$program};
806                                                 my $transposed = $note - ($_->{transpose} || 0) - $testtranspose;
807                                                 if(exists $_->{notes_on}{$transposed})
808                                                 {
809                                                         ++$votegood;
810                                                 }
811                                                 else
812                                                 {
813                                                         ++$votehigh if $transposed >= 0;
814                                                         ++$votelow if $transposed < 0;
815                                                 }
816                                         }
817                                         if($votegood)
818                                         {
819                                                 $good += $cnt;
820                                         }
821                                         elsif($votelow >= $votehigh)
822                                         {
823                                                 $toolow += $cnt;
824                                         }
825                                         else
826                                         {
827                                                 $toohigh += $cnt;
828                                         }
829                                 }
830                         }
831                 }
832                 next if !$toohigh != !$toolow;
833                 print STDERR "  Transpose $testtranspose: $toohigh too high, $toolow too low, $good good\n";
834         }
835
836         while(my ($k1, $v1) = each %midinotes)
837         {
838                 while(my ($k2, $v2) = each %$v1)
839                 {
840                         busybot_note_off($t, $k1, $k2);
841                 }
842         }
843
844         for(@busybots_allocated)
845         {
846                 busybot_intermission_bot $_;
847         }
848         ++$intermissions;
849 }
850
851 sub Deallocate()
852 {
853         print STDERR "Bots allocated:\n";
854         my %notehash;
855         my %counthash;
856         for(@busybots_allocated)
857         {
858                 print STDERR "$_->{id} is a $_->{classname}\n";
859                 ++$counthash{$_->{classname}};
860                 while(my ($type, $notehash) = each %{$_->{seen}})
861                 {
862                         while(my ($k, $v) = each %$notehash)
863                         {
864                                 $notehash{$_->{classname}}{$type}{$k} += $v;
865                         }
866                 }
867         }
868         for my $cn(sort keys %counthash)
869         {
870                 print STDERR "$counthash{$cn} bots of $cn have played:\n";
871                 for my $type(sort keys %{$notehash{$cn}})
872                 {
873                         for my $note(sort { $a <=> $b } keys %{$notehash{$cn}{$type}})
874                         {
875                                 my $cnt = $notehash{$cn}{$type}{$note};
876                                 print STDERR "  $type $note ($cnt times)\n";
877                         }
878                 }
879         }
880         for(@busybots_allocated)
881         {
882                 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_predone];
883                 busybot_cmd_bot_execute $_, 0, ['barrier'];
884                 if($_->{done})
885                 {
886                         busybot_cmd_bot_execute $_, 0, @{$_->{done}};
887                 }
888                 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_postdone];
889                 busybot_cmd_bot_execute $_, 0, ['barrier'];
890         }
891 }
892
893 my @preallocate = ();
894 $noalloc = 0;
895 for(;;)
896 {
897         $commands = "";
898         eval
899         {
900                 Preallocate(@preallocate);
901                 my @l = @midilist;
902                 while(@l)
903                 {
904                         my $filename = shift @l;
905                         my $transpose = shift @l;
906                         ConvertMIDI($filename, $transpose);
907                 }
908                 Deallocate();
909                 my @preallocate_new = map { $_->{classname} } @busybots_allocated;
910                 if(@preallocate_new == @preallocate)
911                 {
912                         print "$precommands$commands";
913                         exit 0;
914                 }
915                 @preallocate = @preallocate_new;
916                 $noalloc = 1;
917                 1;
918         } or do {
919                 die "$@"
920                         unless $@ eq "noalloc\n";
921         };
922 }