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