]> git.xonotic.org Git - xonotic/xonotic.git/blob - misc/tools/midi2cfg-ng.pl
more midi2cfg stuff, mainly: we can now distinguish by MIDI program
[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] > $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
579                         my $noteofftime = busybot_cmd_bot_matchtime $bot, $time + $notetime + $mintime, $time, @$busy_cmds_off;
580                         next
581                                 if $noteofftime < $bot->{busytimer};
582                         next
583                                 if $noteofftime + $mintime < $bot->{timer};
584
585                         my $score = 0;
586                         # prefer turning off long notes
587                         $score +=  100 * ($noteofftime - $bot->{timer});
588                         # prefer turning off low notes
589                         $score +=    1 * (-$note);
590                         # prefer turning off notes that already play on another channel
591                         $score += 1000 * (grep { $_ != $busy_chan && $notechannelbots{$_}{$busy_note} && $notechannelbots{$_}{$busy_note}{busy} } keys %notechannelbots);
592
593                         push @candidates, [$bot, $score, $noteofftime];
594                 }
595
596                 # we found one?
597
598                 if(@candidates)
599                 {
600                         @candidates = sort { $a->[1] <=> $b->[1] } @candidates;
601                         my ($bot, $score, $offtime) = @{(pop @candidates)};
602                         my $oldchan = $bot->{busy}->[0];
603                         my $oldnote = $bot->{busy}->[1];
604                         busybot_note_off $offtime - $notetime, $oldchan, $oldnote;
605                         my $canplay = busybot_note_on_bot $bot, $time, $channel, $program, $note, 0, 1;
606                         die "Canplay but not?"
607                                 if $canplay <= 0;
608                         warn "Made $channel:$note play by stopping $oldchan:$oldnote";
609                         $notechannelbots{$channel}{$note} = $bot;
610                         return 1;
611                 }
612         }
613
614         die "noalloc\n"
615                 if $needalloc;
616
617         if(@epicfailbots)
618         {
619                 warn "Not enough bots to play this (when playing $channel:$note)";
620 #               for(@epicfailbots)
621 #               {
622 #                       my $b = $_->{busy};
623 #                       warn "$_->{classname} -> @{[$b ? qq{$b->[0]:$b->[1]} : 'none']} @{[$_->{timer} - $notetime]} ($time)\n";
624 #               }
625         }
626         else
627         {
628                 warn "Note $channel:$note cannot be played by any bot";
629         }
630
631         return 0;
632 }
633
634 sub Preallocate(@)
635 {
636         my (@preallocate) = @_;
637         busybots_reset();
638         for(@preallocate)
639         {
640                 die "Cannot preallocate any more $_ bots"
641                         if $busybots->{$_}->{count} <= 0;
642                 my $bot = Storable::dclone $busybots->{$_};
643                 $bot->{id} = @busybots_allocated + 1;
644                 $bot->{classname} = $_;
645                 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preinit];
646                 busybot_cmd_bot_execute $bot, 0, ['barrier'];
647                 busybot_cmd_bot_execute $bot, 0, @{$bot->{init}}
648                         if @{$bot->{init}};
649                 busybot_cmd_bot_execute $bot, 0, ['barrier'];
650                 --$busybots->{$_}->{count};
651                 push @busybots_allocated, $bot;
652         }
653 }
654
655 sub ConvertMIDI($$)
656 {
657         my ($filename, $trans) = @_;
658         $transpose = $trans;
659
660         my $opus = MIDI::Opus->new({from_file => $filename});
661         my $ticksperquarter = $opus->ticks();
662         my $tracks = $opus->tracks_r();
663         my @tempi = (); # list of start tick, time per tick pairs (calculated as seconds per quarter / ticks per quarter)
664         my $tick;
665
666         $tick = 0;
667         for($tracks->[0]->events())
668         {   
669                 $tick += $_->[1];
670                 if($_->[0] eq 'set_tempo')
671                 {   
672                         push @tempi, [$tick, $_->[2] * 0.000001 / $ticksperquarter];
673                 }
674         }
675         my $tick2sec = sub
676         {
677                 my ($tick) = @_;
678                 my $sec = 0;
679                 my $curtempo = [0, 0.5 / $ticksperquarter];
680                 for(@tempi)
681                 {
682                         if($_->[0] < $tick)
683                         {
684                                 # this event is in the past
685                                 # we add the full time since the last one then
686                                 $sec += ($_->[0] - $curtempo->[0]) * $curtempo->[1];
687                         }   
688                         else
689                         {
690                                 # if this event is in the future, we break
691                                 last;
692                         }
693                         $curtempo = $_;
694                 }
695                 $sec += ($tick - $curtempo->[0]) * $curtempo->[1];
696                 return $sec;
697         };
698
699         # merge all to a single track
700         my @allmidievents = ();
701         my $sequence = 0;
702         for my $track(0..@$tracks-1)
703         {
704                 $tick = 0;
705                 for($tracks->[$track]->events())
706                 {
707                         my ($command, $delta, @data) = @$_;
708                         $command = 'note_off' if $command eq 'note_on' and $data[2] == 0;
709                         $tick += $delta;
710                         push @allmidievents, [$command, $tick, $sequence++, $track, @data];
711                 }
712         }
713
714         if(open my $fh, "$filename.vocals")
715         {
716                 my $scale = 1;
717                 my $shift = 0;
718                 for(<$fh>)
719                 {
720                         chomp;
721                         my ($tick, $file) = split /\s+/, $_;
722                         if($tick eq 'scale')
723                         {
724                                 $scale = $file;
725                         }
726                         elsif($tick eq 'shift')
727                         {
728                                 $shift = $file;
729                         }
730                         else
731                         {
732                                 push @allmidievents, ['note_on', $tick * $scale + $shift, $sequence++, -1, -1, $file];
733                                 push @allmidievents, ['note_off', $tick * $scale + $shift, $sequence++, -1, -1, $file];
734                         }
735                 }
736         }
737
738         @allmidievents = sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2] } @allmidievents;
739
740         my %midinotes = ();
741         my $notes_stuck = 0;
742         my %notes_seen = ();
743         my %programs = ();
744         my $t = 0;
745         for(@allmidievents)
746         {
747                 $t = $tick2sec->($_->[1]);
748                 my $track = $_->[3];
749                 if($_->[0] eq 'note_on')
750                 {
751                         my $chan = $_->[4] + 1;
752                         ++$notes_seen{$chan}{$_->[5]}
753                                 if $chan != 10 and $chan > 0;
754                         if($midinotes{$chan}{$_->[5]})
755                         {
756                                 --$notes_stuck;
757                                 busybot_note_off($t - SYS_TICRATE, $chan, $_->[5]);
758                         }
759                         busybot_note_on($t, $chan, $programs{$chan} || 1, $_->[5]);
760                         ++$notes_stuck;
761                         $midinotes{$chan}{$_->[5]} = 1;
762                 }
763                 elsif($_->[0] eq 'note_off')
764                 {
765                         my $chan = $_->[4] + 1;
766                         if($midinotes{$chan}{$_->[5]})
767                         {
768                                 --$notes_stuck;
769                                 busybot_note_off($t - SYS_TICRATE, $chan, $_->[5]);
770                         }
771                         $midinotes{$chan}{$_->[5]} = 0;
772                 }
773                 elsif($_->[0] eq 'patch_change')
774                 {
775                         my $chan = $_->[4] + 1;
776                         my $program = $_->[5] + 1;
777                         $programs{$chan} = $program;
778                 }
779         }
780
781         print STDERR "For file $filename:\n";
782         print STDERR "  Stuck notes: $notes_stuck\n";
783
784         for my $testtranspose(-127..127)
785         {
786                 my $toohigh = 0;
787                 my $toolow = 0;
788                 my $good = 0;
789                 for my $channel(sort keys %notes_seen)
790                 {
791                         for my $note(sort keys %{$notes_seen{$channel}})
792                         {
793                                 my $cnt = $notes_seen{$channel}{$note};
794                                 my $votehigh = 0;
795                                 my $votelow = 0;
796                                 my $votegood = 0;
797                                 for(@busybots_allocated)
798                                 {
799                                         next # I won't play on this channel
800                                                 if defined $_->{channels} and not $_->{channels}->{$channel};
801 #                                       next # I won't play this program
802 #                                               if defined $bot->{programs} and not $bot->{programs}->{$program};
803                                         my $transposed = $note - ($_->{transpose} || 0) - $testtranspose;
804                                         if(exists $_->{notes_on}{$transposed})
805                                         {
806                                                 ++$votegood;
807                                         }
808                                         else
809                                         {
810                                                 ++$votehigh if $transposed >= 0;
811                                                 ++$votelow if $transposed < 0;
812                                         }
813                                 }
814                                 if($votegood)
815                                 {
816                                         $good += $cnt;
817                                 }
818                                 elsif($votelow >= $votehigh)
819                                 {
820                                         $toolow += $cnt;
821                                 }
822                                 else
823                                 {
824                                         $toohigh += $cnt;
825                                 }
826                         }
827                 }
828                 next if !$toohigh != !$toolow;
829                 print STDERR "  Transpose $testtranspose: $toohigh too high, $toolow too low, $good good\n";
830         }
831
832         while(my ($k1, $v1) = each %midinotes)
833         {
834                 while(my ($k2, $v2) = each %$v1)
835                 {
836                         busybot_note_off($t, $k1, $k2);
837                 }
838         }
839
840         for(@busybots_allocated)
841         {
842                 busybot_intermission_bot $_;
843         }
844         ++$intermissions;
845 }
846
847 sub Deallocate()
848 {
849         print STDERR "Bots allocated:\n";
850         my %notehash;
851         my %counthash;
852         for(@busybots_allocated)
853         {
854                 print STDERR "$_->{id} is a $_->{classname}\n";
855                 ++$counthash{$_->{classname}};
856                 while(my ($type, $notehash) = each %{$_->{seen}})
857                 {
858                         while(my ($k, $v) = each %$notehash)
859                         {
860                                 $notehash{$_->{classname}}{$type}{$k} += $v;
861                         }
862                 }
863         }
864         for my $cn(sort keys %counthash)
865         {
866                 print STDERR "$counthash{$cn} bots of $cn have played:\n";
867                 for my $type(sort keys %{$notehash{$cn}})
868                 {
869                         for my $note(sort { $a <=> $b } keys %{$notehash{$cn}{$type}})
870                         {
871                                 my $cnt = $notehash{$cn}{$type}{$note};
872                                 print STDERR "  $type $note ($cnt times)\n";
873                         }
874                 }
875         }
876         for(@busybots_allocated)
877         {
878                 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_predone];
879                 busybot_cmd_bot_execute $_, 0, ['barrier'];
880                 if($_->{done})
881                 {
882                         busybot_cmd_bot_execute $_, 0, @{$_->{done}};
883                 }
884                 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_postdone];
885                 busybot_cmd_bot_execute $_, 0, ['barrier'];
886         }
887 }
888
889 my @preallocate = ();
890 $noalloc = 0;
891 for(;;)
892 {
893         $commands = "";
894         eval
895         {
896                 Preallocate(@preallocate);
897                 my @l = @midilist;
898                 while(@l)
899                 {
900                         my $filename = shift @l;
901                         my $transpose = shift @l;
902                         ConvertMIDI($filename, $transpose);
903                 }
904                 Deallocate();
905                 my @preallocate_new = map { $_->{classname} } @busybots_allocated;
906                 if(@preallocate_new == @preallocate)
907                 {
908                         print "$precommands$commands";
909                         exit 0;
910                 }
911                 @preallocate = @preallocate_new;
912                 $noalloc = 1;
913                 1;
914         } or do {
915                 die "$@"
916                         unless $@ eq "noalloc\n";
917         };
918 }