]> git.xonotic.org Git - xonotic/xonotic.git/blob - misc/tools/midi2cfg-ng.pl
if you must take a bot from another channel - pick the one which played least on it
[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} && $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(($_->{lastuse} // -666) >= $time - $time_forgetfulness)
543                         {
544                                 if($channel == $_->{lastchannel})
545                                 {
546                                         $q += $_->{lastchannelsequence};
547                                 }
548                                 else
549                                 {
550                                         # better leave this one alone
551                                         $q -= $_->{lastchannelsequence};
552                                 }
553                         }
554                         [$_, $q, rand]
555                 }
556                 @bots;
557 }
558
559 sub busybot_note_on($$$$)
560 {
561         my ($time, $channel, $program, $note) = @_;
562
563         if($notechannelbots{$channel}{$note})
564         {
565                 busybot_note_off $time, $channel, $note;
566         }
567
568 #       print STDERR "note on $time:$channel:$note\n";
569
570         my $overflow = 0;
571
572         my @epicfailbots = ();
573
574         for(botsort $time, $channel, $program, $note, @busybots_allocated)
575         {
576                 my $canplay = busybot_note_on_bot $_, $time, $channel, $program, $note, 0, 0;
577                 if($canplay > 0)
578                 {
579                         $notechannelbots{$channel}{$note} = $_;
580                         return 1;
581                 }
582                 push @epicfailbots, $_
583                         if $canplay == 0;
584                 # wrong
585         }
586
587         my $needalloc = 0;
588
589         for(unsort keys %$busybots)
590         {
591                 next if $busybots->{$_}->{count} <= 0;
592                 my $bot = Storable::dclone $busybots->{$_};
593                 $bot->{id} = @busybots_allocated + 1;
594                 $bot->{classname} = $_;
595                 my $canplay = busybot_note_on_bot $bot, $time, $channel, $program, $note, 1, 0;
596                 if($canplay > 0)
597                 {
598                         if($noalloc)
599                         {
600                                 $needalloc = 1;
601                         }
602                         else
603                         {
604                                 --$busybots->{$_}->{count};
605                                 $notechannelbots{$channel}{$note} = $bot;
606                                 push @busybots_allocated, $bot;
607                                 return 1;
608                         }
609                 }
610                 die "Fresh bot cannot play stuff"
611                         if $canplay == 0;
612         }
613
614         if(@epicfailbots)
615         {
616                 # we cannot add a new bot to play this
617                 # we could try finding a bot that could play this, and force him to stop the note!
618
619                 my @candidates = (); # contains: [$bot, $score, $offtime]
620
621                 # put in all currently busy bots that COULD play this, if they did a note-off first
622                 for my $bot(@epicfailbots)
623                 {
624                         next
625                                 if $busybots->{$bot->{classname}}->{count} != 0;
626                         next
627                                 unless $bot->{busy};
628                         my ($busy_chan, $busy_note, $busy_cmds_off) = @{$bot->{busy}};
629                         next
630                                 unless $busy_cmds_off;
631                         my ($cmds, $cmds_off, $k0, $k1) = busybot_get_cmds_bot $bot, $channel, $note;
632                         next
633                                 unless $cmds;
634                         my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @$cmds;
635                         my ($mintime_off, $maxtime_off, $busytime_off) = busybot_cmd_bot_cmdinfo @$busy_cmds_off;
636
637                         my $noteofftime = busybot_cmd_bot_matchtime $bot, $time + $notetime + $mintime, $time + $notetime, @$busy_cmds_off;
638                         next
639                                 if $noteofftime < $bot->{busytimer};
640                         next
641                                 if $noteofftime + $mintime_off < $bot->{timer};
642
643                         my $score = 0;
644                         # prefer turning off long notes
645                         $score +=  100 * ($noteofftime - $bot->{timer});
646                         # prefer turning off low notes
647                         $score +=    1 * (-$note);
648                         # prefer turning off notes that already play on another channel
649                         $score += 1000 * (grep { $_ != $busy_chan && $notechannelbots{$_}{$busy_note} && $notechannelbots{$_}{$busy_note}{busy} } keys %notechannelbots);
650
651                         push @candidates, [$bot, $score, $noteofftime];
652                 }
653
654                 # we found one?
655
656                 if(@candidates)
657                 {
658                         @candidates = sort { $a->[1] <=> $b->[1] } @candidates;
659                         my ($bot, $score, $offtime) = @{(pop @candidates)};
660                         my $oldchan = $bot->{busy}->[0];
661                         my $oldnote = $bot->{busy}->[1];
662                         busybot_note_off $offtime - $notetime, $oldchan, $oldnote;
663                         my $canplay = busybot_note_on_bot $bot, $time, $channel, $program, $note, 0, 1;
664                         die "Canplay but not?"
665                                 if $canplay <= 0;
666                         warn "Made $channel:$note play by stopping $oldchan:$oldnote";
667                         $notechannelbots{$channel}{$note} = $bot;
668                         return 1;
669                 }
670         }
671
672         die "noalloc\n"
673                 if $needalloc;
674
675         if(@epicfailbots)
676         {
677                 warn "Not enough bots to play this (when playing $channel:$note)";
678 #               for(@epicfailbots)
679 #               {
680 #                       my $b = $_->{busy};
681 #                       warn "$_->{classname} -> @{[$b ? qq{$b->[0]:$b->[1]} : 'none']} @{[$_->{timer} - $notetime]} ($time)\n";
682 #               }
683         }
684         else
685         {
686                 warn "Note $channel:$note cannot be played by any bot";
687         }
688
689         return 0;
690 }
691
692 sub Preallocate(@)
693 {
694         my (@preallocate) = @_;
695         busybots_reset();
696         for(@preallocate)
697         {
698                 die "Cannot preallocate any more $_ bots"
699                         if $busybots->{$_}->{count} <= 0;
700                 my $bot = Storable::dclone $busybots->{$_};
701                 $bot->{id} = @busybots_allocated + 1;
702                 $bot->{classname} = $_;
703                 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preinit];
704                 busybot_cmd_bot_execute $bot, 0, ['barrier'];
705                 busybot_cmd_bot_execute $bot, 0, @{$bot->{init}}
706                         if @{$bot->{init}};
707                 busybot_cmd_bot_execute $bot, 0, ['barrier'];
708                 --$busybots->{$_}->{count};
709                 push @busybots_allocated, $bot;
710         }
711 }
712
713 sub ConvertMIDI($$)
714 {
715         my ($filename, $trans) = @_;
716         $transpose = $trans;
717
718         my $opus = MIDI::Opus->new({from_file => $filename});
719         my $ticksperquarter = $opus->ticks();
720         my $tracks = $opus->tracks_r();
721         my @tempi = (); # list of start tick, time per tick pairs (calculated as seconds per quarter / ticks per quarter)
722         my $tick;
723
724         $tick = 0;
725         for($tracks->[0]->events())
726         {   
727                 $tick += $_->[1];
728                 if($_->[0] eq 'set_tempo')
729                 {   
730                         push @tempi, [$tick, $_->[2] * 0.000001 / $ticksperquarter];
731                 }
732         }
733         my $tick2sec = sub
734         {
735                 my ($tick) = @_;
736                 my $sec = 0;
737                 my $curtempo = [0, 0.5 / $ticksperquarter];
738                 for(@tempi)
739                 {
740                         if($_->[0] < $tick)
741                         {
742                                 # this event is in the past
743                                 # we add the full time since the last one then
744                                 $sec += ($_->[0] - $curtempo->[0]) * $curtempo->[1];
745                         }   
746                         else
747                         {
748                                 # if this event is in the future, we break
749                                 last;
750                         }
751                         $curtempo = $_;
752                 }
753                 $sec += ($tick - $curtempo->[0]) * $curtempo->[1];
754                 return $sec;
755         };
756
757         # merge all to a single track
758         my @allmidievents = ();
759         my $sequence = 0;
760         for my $track(0..@$tracks-1)
761         {
762                 $tick = 0;
763                 for($tracks->[$track]->events())
764                 {
765                         my ($command, $delta, @data) = @$_;
766                         $command = 'note_off' if $command eq 'note_on' and $data[2] == 0;
767                         $tick += $delta;
768                         push @allmidievents, [$command, $tick, $sequence++, $track, @data];
769                 }
770         }
771
772         if(open my $fh, "$filename.vocals")
773         {
774                 my $scale = 1;
775                 my $shift = 0;
776                 for(<$fh>)
777                 {
778                         chomp;
779                         my ($tick, $file) = split /\s+/, $_;
780                         if($tick eq 'scale')
781                         {
782                                 $scale = $file;
783                         }
784                         elsif($tick eq 'shift')
785                         {
786                                 $shift = $file;
787                         }
788                         else
789                         {
790                                 push @allmidievents, ['note_on', $tick * $scale + $shift, $sequence++, -1, -1, $file];
791                                 push @allmidievents, ['note_off', $tick * $scale + $shift, $sequence++, -1, -1, $file];
792                         }
793                 }
794         }
795
796         @allmidievents = sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2] } @allmidievents;
797
798         my %midinotes = ();
799         my $notes_stuck = 0;
800         my %notes_seen = ();
801         my %programs = ();
802         my $t = 0;
803         for(@allmidievents)
804         {
805                 $t = $tick2sec->($_->[1]);
806                 my $track = $_->[3];
807                 if($_->[0] eq 'note_on')
808                 {
809                         my $chan = $_->[4] + 1;
810                         ++$notes_seen{$chan}{($programs{$chan} || 1)}{$_->[5]};
811                         if($midinotes{$chan}{$_->[5]})
812                         {
813                                 --$notes_stuck;
814                                 busybot_note_off($t - SYS_TICRATE - 0.001, $chan, $_->[5]);
815                         }
816                         busybot_note_on($t, $chan, $programs{$chan} || 1, $_->[5]);
817                         ++$notes_stuck;
818                         $midinotes{$chan}{$_->[5]} = 1;
819                 }
820                 elsif($_->[0] eq 'note_off')
821                 {
822                         my $chan = $_->[4] + 1;
823                         if($midinotes{$chan}{$_->[5]})
824                         {
825                                 --$notes_stuck;
826                                 busybot_note_off($t - SYS_TICRATE - 0.001, $chan, $_->[5]);
827                         }
828                         $midinotes{$chan}{$_->[5]} = 0;
829                 }
830                 elsif($_->[0] eq 'patch_change')
831                 {
832                         my $chan = $_->[4] + 1;
833                         my $program = $_->[5] + 1;
834                         $programs{$chan} = $program;
835                 }
836         }
837
838         print STDERR "For file $filename:\n";
839         print STDERR "  Stuck notes: $notes_stuck\n";
840
841         for my $testtranspose(-127..127)
842         {
843                 my $toohigh = 0;
844                 my $toolow = 0;
845                 my $good = 0;
846                 for my $channel(sort keys %notes_seen)
847                 {
848                         next if $channel == 10 or $channel < 0;
849                         for my $program(sort keys %{$notes_seen{$channel}})
850                         {
851                                 for my $note(sort keys %{$notes_seen{$channel}{$program}})
852                                 {
853                                         my $cnt = $notes_seen{$channel}{$program}{$note};
854                                         my $votehigh = 0;
855                                         my $votelow = 0;
856                                         my $votegood = 0;
857                                         for(@busybots_allocated)
858                                         {
859                                                 next # I won't play on this channel
860                                                         if defined $_->{channels} and not $_->{channels}->{$channel};
861                                                 next # I won't play this program
862                                                         if defined $_->{programs} and not $_->{programs}->{$program};
863                                                 my $transposed = $note - ($_->{transpose} || 0) - $testtranspose;
864                                                 if(exists $_->{notes_on}{$transposed})
865                                                 {
866                                                         ++$votegood;
867                                                 }
868                                                 else
869                                                 {
870                                                         ++$votehigh if $transposed >= 0;
871                                                         ++$votelow if $transposed < 0;
872                                                 }
873                                         }
874                                         if($votegood)
875                                         {
876                                                 $good += $cnt;
877                                         }
878                                         elsif($votelow >= $votehigh)
879                                         {
880                                                 $toolow += $cnt;
881                                         }
882                                         else
883                                         {
884                                                 $toohigh += $cnt;
885                                         }
886                                 }
887                         }
888                 }
889                 next if !$toohigh != !$toolow;
890                 print STDERR "  Transpose $testtranspose: $toohigh too high, $toolow too low, $good good\n";
891         }
892
893         for my $program(sort keys %{$notes_seen{10}})
894         {
895                 for my $note(sort keys %{$notes_seen{10}{$program}})
896                 {
897                         my $cnt = $notes_seen{10}{$program}{$note};
898                         my $votegood = 0;
899                         for(@busybots_allocated)
900                         {
901                                 next # I won't play on this channel
902                                         if defined $_->{channels} and not $_->{channels}->{10};
903                                 next # I won't play this program
904                                         if defined $_->{programs} and not $_->{programs}->{$program};
905                                 if(exists $_->{percussion}{$note})
906                                 {
907                                         ++$votegood;
908                                 }
909                         }
910                         if(!$votegood)
911                         {
912                                 print STDERR "Failed percussion $note ($cnt times)\n";
913                         }
914                 }
915         }
916
917         while(my ($k1, $v1) = each %midinotes)
918         {
919                 while(my ($k2, $v2) = each %$v1)
920                 {
921                         busybot_note_off($t, $k1, $k2);
922                 }
923         }
924
925         for(@busybots_allocated)
926         {
927                 busybot_intermission_bot $_;
928         }
929         ++$intermissions;
930 }
931
932 sub Deallocate()
933 {
934         print STDERR "Bots allocated:\n";
935         my %notehash;
936         my %counthash;
937         for(@busybots_allocated)
938         {
939                 print STDERR "$_->{id} is a $_->{classname}\n";
940                 ++$counthash{$_->{classname}};
941                 while(my ($type, $notehash) = each %{$_->{seen}})
942                 {
943                         while(my ($k, $v) = each %$notehash)
944                         {
945                                 $notehash{$_->{classname}}{$type}{$k} += $v;
946                         }
947                 }
948         }
949         for my $cn(sort keys %counthash)
950         {
951                 print STDERR "$counthash{$cn} bots of $cn have played:\n";
952                 for my $type(sort keys %{$notehash{$cn}})
953                 {
954                         for my $note(sort { $a <=> $b } keys %{$notehash{$cn}{$type}})
955                         {
956                                 my $cnt = $notehash{$cn}{$type}{$note};
957                                 print STDERR "  $type $note ($cnt times)\n";
958                         }
959                 }
960         }
961         for(@busybots_allocated)
962         {
963                 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_predone];
964                 busybot_cmd_bot_execute $_, 0, ['barrier'];
965                 if($_->{done})
966                 {
967                         busybot_cmd_bot_execute $_, 0, @{$_->{done}};
968                 }
969                 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_postdone];
970                 busybot_cmd_bot_execute $_, 0, ['barrier'];
971         }
972 }
973
974 my @preallocate = ();
975 $noalloc = 0;
976 for(;;)
977 {
978         $commands = "";
979         eval
980         {
981                 Preallocate(@preallocate);
982                 my @l = @midilist;
983                 while(@l)
984                 {
985                         my $filename = shift @l;
986                         my $transpose = shift @l;
987                         ConvertMIDI($filename, $transpose);
988                 }
989                 Deallocate();
990                 my @preallocate_new = map { $_->{classname} } @busybots_allocated;
991                 if(@preallocate_new == @preallocate)
992                 {
993                         print "$precommands$commands";
994                         exit 0;
995                 }
996                 @preallocate = @preallocate_new;
997                 $noalloc = 1;
998                 1;
999         } or do {
1000                 die "$@"
1001                         unless $@ eq "noalloc\n";
1002         };
1003 }