Debian Codegraph @

examples/midiedit

raw
1 #! /usr/bin/perl
2 #########################################################################
3 # This Perl script is Copyright (c) 2006, Peter J Billam #
4 # c/o P J B Computing, GPO Box 669, Hobart TAS 7001, Australia #
5 # #
6 # This script is free software; you can redistribute it and/or #
7 # modify it under the same terms as Perl itself. #
8 #########################################################################
9 # 20151106
10 # 1) Sometimes after 'w' the w remains displayed at the end of the current line
11 # 2) introduce a Buffer: ry=range-yank or rd=range-delete, then p=paste
12 # 3) could display the patch of the current event, if there's room somewhere;
13 # perhaps lower right, at the end of the hline()
14 # 4) do we _need_ to store Now? und_do,re_do $Now=$Track[$Ievent][$[+1]+1;
15 #
16 # Could do:
17 # Option -R = ReadOnly ?
18 # When editing a note-pitch, midi-keyboard input could be accepted, perhaps
19 # even without a p=pitch first. Should it also edit the v=velocity ?
20 # u=undo seems to mess up deltatimes ? :-(
21
22 # Not convincing, because of 'z' = all sounds off ...
23 # It should be possible to choose, when moving times (arrows,page):
24 # terminate on-notes, or not terminate on-notes.
25 # Perhaps HJKL could mean do-not-terminate,
26 # and the Page keys could follow the previous u/l case of the hjkl keys ?
27
28 # 20140303
29 # midiedit could display pitches mapped left-to-right like a miniature piano
30 # C ab | Eb
31 # C | Eb f~
32 # | Eb b f~
33 # If possible at least 3 characters per octave, plus '| ' unmoving;
34 # bass is 3.3 octaves, treble 4 octaves = 22 chars; plus '| ' makes 24
35 # If less than 15 are available, revert to 'treble f~##' which uses 11.
36 # Could also display the sounding chord, eg 'c233' or 'eb26'
37 # see sub note2str !
38
39 # 20140622 To avoid having to type rw filename then fi filename,
40 # we should have either ri=range-insert, or ir=insert-range,
41 # or introduce a Buffer: ry=range-yank and rd=range-delete and p=paste
42
43 # use Data::Dumper; $Data::Dumper::Indent = 0; $Data::Dumper::Sortkeys = 1;
44
45 use Time::HiRes; # 5.3
46
47 my $Version = '7.8'; # -d on multi-track files resets ticks to 0 each track
48 my $VersionDate = '20160701';
49 my $UseCurses = 1;
50 my $TopKeystrokesLine; # set by display_keystrokes
51 my $OutputPort = $ENV{'ALSA_OUTPUT_PORTS'};
52
53 while ($ARGV[$[] =~ /^-(\w)/) {
54 if ($1 eq 'd') { $UseCurses = 0; shift;
55 } elsif ($1 eq 'o') { shift; $OutputPort = shift;
56 } else {
57 my $n = $0; $n =~ s#^.*/([^/]+)$#$1#;
58 print <<EOT; exit 0;
59 Usage:
60 $n filename.mid # new specialised Curses and ALSA mode
61 $n -d filename.mid # older dump and text-editor mode
62 perldoc $n # read the real Documentation !
63 Version $Version $VersionDate http://www.pjb.com.au/midi
64 EOT
65 }
66 }
67
68 eval 'require MIDI'; if ($@) {
69 die "you need to install the MIDI::Perl module from www.cpan.org\n";
70 }
71 import MIDI;
72 if ($UseCurses) {
73 eval 'require Curses'; if ($@) {
74 die "you need to install the Curses module from www.cpan.org\n";
75 }
76 import Curses;
77 eval 'require MIDI::ALSA'; if ($@) {
78 die "you need to install the MIDI::ALSA module from www.cpan.org\n";
79 }
80 import MIDI::ALSA;
81 } else {
82 eval 'require Term::Clui'; if ($@) {
83 die "you need to install the Term::Clui module from www.cpan.org\n";
84 }
85 import Term::Clui;
86 }
87
88 my @note2letter=split / /,'C C D E E F F G G A B B c c d e e f f g g a b b';
89 my @note2acc = ('','#','','b','','','#','','#','','b','');
90 my %sysex2str = ( # 3.6
91 "\x7E\x7F\x09\x01\xF7" => 'gm 1',
92 # "\x7E\x7F\x09\x01\xF7" => 'gm on',
93 "\x7E\x7F\x09\x02\xF7" => 'gm off',
94 "\x7E\x7F\x09\x03\xF7" => 'gm 2',
95 );
96 my %Number2controller = (
97 0=>'Bank Select (MSB)',
98 1=>'Modulation (MSB)',
99 2=>'Breath Control (MSB)',
100 4=>'Foot Control (MSB)',
101 5=>'Portamento Time MSB',
102 6=>'Data Entry (MSB)',
103 7=>'Channel Volume MSB',
104 8=>'Balance (MSB)',
105 10=>'Pan (MSB)',
106 11=>'Expression (MSB)',
107 12=>'Effects Controller 1',
108 13=>'Effects Controller 2',
109 16=>'Gen Purpose 1 (MSB)',
110 17=>'Gen Purpose 2 (MSB)',
111 18=>'Gen Purpose 3 (MSB)',
112 19=>'Gen Purpose 4 (MSB)',
113 32=>'Bank Select (LSB)',
114 33=>'Modulation (LSB)',
115 34=>'Breath Control (LSB)',
116 36=>'Foot Control (LSB)',
117 37=>'Portamento Time LSB',
118 38=>'Data Entry (LSB)',
119 39=>'Channel Volume LSB',
120 40=>'Balance (LSB)',
121 42=>'Pan (LSB)',
122 43=>'Expression (LSB)',
123 48=>'Gen Purpose 1 (LSB)',
124 49=>'Gen Purpose 2 (LSB)',
125 50=>'Gen Purpose 3 (LSB)',
126 51=>'Gen Purpose 4 (LSB)',
127 64=>'Sustain Pedal',
128 65=>'Portamento on/off',
129 66=>'Sostenuto Pedal',
130 67=>'Soft Pedal',
131 68=>'Legato Pedal',
132 69=>'Hold 2',
133 70=>'Sound Variation',
134 71=>'Resonance',
135 72=>'Release Time',
136 73=>'Attack Time',
137 74=>'Cut-off Frequency',
138 75=>'Decay Time',
139 76=>'Vibrato Rate',
140 77=>'Vibrato Depth',
141 78=>'Vibrato Delay',
142 80=>'Gen Purpose 5',
143 81=>'Gen Purpose 6',
144 82=>'Gen Purpose 7',
145 83=>'Gen Purpose 8',
146 84=>'Portamento Control',
147 91=>'Reverb Depth',
148 92=>'Tremolo Depth',
149 93=>'Chorus Depth',
150 94=>'Celeste (De-tune)',
151 95=>'Phaser Depth',
152 96=>'Data Increment',
153 97=>'Data Decrement',
154 98=>'non-reg param lsb',
155 99=>'non-reg param msb',
156 100=>'Reg-Param (LSB)',
157 101=>'Reg-Param (MSB)',
158 120=>'All Sound Off',
159 121=>'Reset All Controllers',
160 122=>'Local Control',
161 123=>'All Notes Off',
162 124=>'Omni Off',
163 125=>'Omni On',
164 126=>'Mono On (Poly Off)',
165 127=>'Poly On (Mono Off)',
166 );
167
168 if (! $UseCurses) {
169 use bytes; # 20150526 because of sysexes that need to end with \xF7
170 my $opus = MIDI::Opus->new({ 'from_file' => $ARGV[$[]});
171 open(SAVEOUT, ">&STDOUT") || die "couldn't dup STDOUT: $!";
172 close STDOUT;
173 my $text;
174 if (!open(STDOUT,'>',\$text)) { die "can't open STDOUT in-memory: $!\n"; }
175 print "# see perldoc MIDI::Event\n\$newopus = ";
176 $opus->dump({'dump_tracks'=>1});
177 close STDOUT;
178 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT: $!";
179 my @text = split(/\n/, $text);
180 my $tmp = "/tmp/midiedit.$$";
181 if (! open(T, '>', $tmp)) { die "can't open $tmp: $!\n"; }
182 local $ticks = 0; # 7.8 line2comment resets ticks with each new Track
183 foreach my $line (@text) { print T $line.line2comment($line)."\n"; }
184 close T;
185 while (1) {
186 Term::Clui::edit($tmp);
187 unless ($return = do $tmp) {
188 warn "couldn't parse $tmp: $@\n" if $@;
189 warn "couldn't do $tmp: $!\n" unless defined $return;
190 warn "couldn't run $tmp\n" unless $return;
191 }
192 last if $newopus;
193 if (!Term::Clui::confirm("MIDI::Opus syntax error. OK to re-edit ?")) {
194 unlink $tmp; exit 1;
195 }
196 }
197 unlink $tmp;
198 $Debug=0; if ($Debug) { $newopus->dump({'dump_tracks'=>1}); exit; }
199 $newopus->write_to_file( $ARGV[$[] );
200 exit 0;
201 }
202
203 # ----- the Curses app...
204 my $File = $ARGV[$[];
205 my @score = file2ms_score($File); # 1.7
206 # foreach my $e (@Track) { if (! defined $e->[$[]) { debug("UNDEF 1"); } }
207 my @buggyTrack = sort {$$a[$[+1] <=> $$b[$[+1]} @{$score[1]}; # 7.2
208 my @Track = ();
209 # 7.2 ARGGghhh... the sort introduces extra events with undefined types :-(
210 foreach my $e (@buggyTrack) { if (defined $e->[$[]) { push @Track, $e; } }
211 my $Now = 0; # ticks? secs?
212 my $Ievent = $[; # perhaps $[-1 should mean before_the_first_event ?
213 my $Paused = 1;
214 my $Editing = 0; # 1.4
215 my $I_LastRefreshed = 0; # 6.7 stores when the display was last refreshed
216 my @EditEvent = (); # 2.9 if event-type matches then '.' imposes the rest
217 my @FindEvent = ();
218 my $FindForwards = 1;
219 my $FindSubstring = 1; # 7.6 currently not changed by anything; could be later
220 my $NowBeforeFind = undef;
221 my $Message = '';
222 my @History = (); # (\@score,$ievent,$now, \@score,$ievent,$now, ...);
223 my $Ihistory = -1;
224 my $IncrementalTimes = 1;
225 my $RangeSettingState = 0; # 4.5
226 my $RangeStart = $[; # 4.5
227 my $RangeEnd = $[-1; # 4.5
228 my $ReplaySpeed = 1.0; # 3.1 varied by [ and ]
229 my $RS = '1.0'; # 3.1 3-char sprintf of $ReplaySpeed
230 my %c2s; # should set it here really; it's set by sub cc2str
231 initscr(); cbreak(); noecho(); nonl(); clear();
232 # http://docstore.mik.ua/orelly/perl/cookbook/ch15_13.htm BUT:
233 keypad(stdscr(),1);
234 $SIG{'INT'} = sub {exit 0;}; $SIG{'TERM'} = sub {exit 0;};
235 add_to_history();
236 my $FileIsChanged = 0;
237 if (! MIDI::ALSA::client( "midiedit pid=$$", 0, 1, 1 )) {
238 die "can't start up the ALSA client\n";
239 }
240 my $ID = MIDI::ALSA::id().":0";
241 display_screen($Now, $Ievent, @Track);
242
243 # 2.0 shouldn't attempt to connect if $OutputPort is undefined or "0"
244 if (! defined $OutputPort) {
245 display_message(
246 "no -o option, and no ALSA_OUTPUT_PORTS environment variable");
247 } elsif ($OutputPort eq '0') {
248 display_message("not connecting to any ALSA client");
249 } else {
250 foreach my $cl_po (split /,/, $OutputPort) { # 2.4
251 #$cl_po =~ /^(\d+):?(\d*)$/;
252 #my $cl = $1; my $po = $2 or 0;
253 #if ($cl == MIDI::ALSA::id()) {
254 # display_message("can't connect to $cl_po, which is myself");
255 #}
256 if (! MIDI::ALSA::connectto( 1, $cl_po )) { #
257 display_message("can't connect to ALSA client $cl_po");
258 }
259 }
260 }
261 if (! MIDI::ALSA::start()) {
262 die "can't start the ALSA client queue\n";
263 }
264 # mustn't create call to endwin in nonCurses mode
265 eval 'sub END {all_sounds_off(); endwin();}';
266 while (1) { # the loop
267 my $c = getch();
268 # debug("\$c = $c = decimal ".unpack('C*',$c));
269 # could use my $c = getchar(); returns either $c or (undef, $keyc)
270 # debug('$c = '.join(" ",unpack('C*',$c)));
271 if ($c == ERR()) {
272 # debug("\$c = ERR()");
273 if ($Paused) {
274 # see man ncurses ==> man inopts
275 timeout(-1); # Shouldn't happen. Anyway, block next read
276 # but could use this for a Message which vanishes after 2 sec
277 } else {
278 if ($Ievent < $#Track) { # output next event
279 $Ievent += 1; $Now = $Track[$Ievent][$[+1] + 1;
280 # 6.7 If Playing, and next event is <10ms away, don't refresh
281 if ($Ievent == $#Track) {
282 display_screen();
283 } elsif (($Track[$Ievent+1][$[+1] - $I_LastRefreshed)
284 > (10.0/$ReplaySpeed)) {
285 display_screen();
286 }
287 # 7.7: could loop through _all_ such events within 10mS ?
288 play_current_event();
289 }
290 set_timeout_for_next_note();
291 }
292 } elsif ($c eq 'w') {
293 score2file($File, 1000,\@Track);
294 display_message("Saved to $File");
295 $FileIsChanged = 0;
296 } elsif ($c eq 'Q' or $c eq 'q') {
297 if ($Paused) { quit(); }
298 $Paused = 1; timeout(-1); display_screen();
299 } elsif ($c eq 'D' or $c == KEY_DL() or $c == KEY_DC()) {
300 set_before_last_change($Ievent); # 7.5
301 if ($IncrementalTimes) {
302 my $dt = delta_t($Ievent);
303 foreach my $ie ($Ievent+1..$#Track) { $Track[$ie][$[+1] -= $dt; }
304 }
305 splice @Track, $Ievent, 1;
306 if ($Ievent > $#Track) { $Ievent = $#Track; }
307 if ($RangeStart >= $Ievent) { $RangeStart -= 1; } # 4.5
308 if ($RangeEnd >= $Ievent) { $RangeEnd -= 1; }
309 add_to_history(); display_screen();
310 } elsif ($c eq 'e') {
311 $Paused = 1; edit_event(); play_current_event(); display_screen();
312 } elsif ($c eq '.') {
313 set_before_last_change($Ievent); # 7.5
314 edit_again(); display_screen(); # 2.9
315 } elsif ($c eq 'i') {
316 set_before_last_change($Ievent); # 7.5
317 insert_event(); display_screen();
318 } elsif ($c eq ']' or $c eq '}') {
319 $ReplaySpeed *= 1.41421356; $RS = sprintf('%.1f',$ReplaySpeed);
320 display_screen(); #3.1
321 } elsif ($c eq '[' or $c eq '{') {
322 $ReplaySpeed *= 0.70710678; $RS = sprintf('%.1f',$ReplaySpeed);
323 display_screen(); #3.1
324 } elsif ($c eq 'R') { set_range(); display_screen();
325 } elsif ($c eq 'f') { file_menu(); display_screen();
326 } elsif ($c eq 'r') { range(); display_screen();
327 } elsif ($c eq 'u') { un_do(); display_screen();
328 } elsif ($c eq "\cR") { re_do(); display_screen();
329 } elsif ($c eq '+') { $IncrementalTimes = 1; display_screen();
330 } elsif ($c eq '-' or $c eq '=') { $IncrementalTimes = 0; display_screen();
331 #} elsif ($c eq 'B' or $c eq 'b') { # 20120916 this is deprecated.
332 # metronome_event($c); display_screen();
333 } elsif ($c eq '/') { # f added 4.1, removed again 4.7
334 if (! $Paused) { $Paused = 1; timeout(-1); display_screen(); }
335 $FindForwards = 1; find(); display_screen();
336 } elsif ($c eq '?') {
337 if (! $Paused) { $Paused = 1; timeout(-1); display_screen(); }
338 $FindForwards = 0; find(); display_screen();
339 } elsif ($c eq 'n') {
340 if (! $Paused) { $Paused = 1; timeout(-1); display_screen(); }
341 find_next($FindForwards); display_screen();
342 } elsif ($c eq 'N') {
343 if (! $Paused) { $Paused = 1; timeout(-1); display_screen(); }
344 find_next(! $FindForwards); display_screen();
345 } elsif ($c eq "\x08" or $c eq KEY_BACKSPACE()) { # 7.7 back to before find
346 if (defined $NowBeforeFind) {
347 time_travel($NowBeforeFind - $Now); display_screen();
348 }
349 } elsif ($c eq ' ') {
350 if ($Paused) { $Paused = 0; set_timeout_for_next_note();
351 } else { $Paused = 1; timeout(-1);
352 }
353 display_screen();
354 } elsif ($c eq 'z') { all_sounds_off();
355 } elsif ($c == KEY_UP() or $c eq 'k') {
356 if ($Ievent > $[) {
357 event_travel(-1); display_screen(); # 5.2
358 }
359 } elsif ($c == KEY_DOWN() or $c eq 'j') {
360 if ($Ievent < $#Track) {
361 event_travel(1); display_screen(); # 5.2
362 }
363 } elsif ($c == KEY_LEFT() or $c eq 'K') {
364 time_travel(-1000); display_screen();
365 } elsif ($c == KEY_RIGHT() or $c eq 'J') {
366 time_travel(1000); display_screen();
367 } elsif ($c == KEY_PPAGE()) { time_travel(-10000); display_screen();
368 } elsif ($c == KEY_NPAGE()) { time_travel(10000); display_screen();
369 } elsif ($c == KEY_HOME()) {
370 $Ievent = $[; $Now = $Track[$Ievent][$[+1];
371 $Paused = 1; display_screen(); timeout(-1);
372 } elsif ($c == KEY_END()) {
373 $Ievent = $#Track; $Now = $Track[$Ievent][$[+1];
374 $Paused = 1; display_screen(); timeout(-1);
375 }
376 }
377
378 #-------------- Infrastructure for the Curses version -------------
379 sub addl { my ($lin,$col,$str) = @_;
380 if ($col < 2) { $col = 2; $str = substr($str, $[, $[+$COLS-4); } # 4.8
381 move($lin,$col); addstr($str); clrtoeol();
382 }
383 sub set_before_last_change { my $i_event = $_[$[]; # 7.5
384 $History[$Ihistory-1] = $i_event;
385 $History[$Ihistory] = $Track[$i_event][$[+1] + 1;
386 # so should we really store Now ? why not just restore it from Ievent ?
387 }
388 sub add_to_history {
389 #debug("add_to_h1: Ihistory=$Ihistory #History=$#History History=@History");
390 my @copy_track = deepcopy(@Track);
391 if ((1+$Ihistory) % 3) { # check that 1+Ihistory is a multiple of 3
392 _warn("add_to_history: Ihistory should be 3*n - 1, not $Ihistory");
393 $Ihistory -= ((1+$Ihistory)%3);
394 if ($Ihistory < 0) { $Ihistory = -1; }
395 }
396 if ((scalar @History) % 3) {
397 _warn("add_to_history: History should be multiple of 3, not "
398 .scalar @History);
399 # if ($Ihistory < $[) { $Ihistory = $[; }
400 }
401 if ($#History > $Ihistory) { $#History = $Ihistory; } # truncate here
402 push @History, \@copy_track, $Ievent, $Now;
403 # hardly space-efficient :-(
404 # could dump into text-format and use diff, or use a direct diff module:
405 # Diff::LibXDiff Algorithm::Diff in Lua: Diff ltdiff
406 # http://search.cpan.org/~tyemq/Algorithm-Diff-1.1903/lib/Algorithm/Diff.pm
407 $Ihistory = $#History;
408 $FileIsChanged = 1;
409 $NowBeforeFind = undef; # 7.7
410 #debug("add_to_h2: Ihistory=$Ihistory History=$#History History=@History");
411 }
412 sub all_sounds_off { # 2.2
413 foreach my $c (0..15) {
414 MIDI::ALSA::output(MIDI::ALSA::controllerevent($c,120,0));
415 MIDI::ALSA::output(MIDI::ALSA::controllerevent($c,123,0)); # 6.9
416 }
417 }
418
419 sub cc2str { my $m = $_[$[];
420 if (! %c2s) { %c2s = (
421 0, 'Bank Select (MSB)',
422 32, 'Bank Select (LSB)',
423 64, 'Sustain Pedal',
424 96, 'Data Increment',
425 1, 'Modulation (MSB)',
426 33, 'Modulation (LSB)',
427 65, 'Portamento on/off',
428 97, 'Data Decrement',
429 2, 'Breath Control (MSB)',
430 34, 'Breath Control (LSB)',
431 66, 'Sostenuto Pedal',
432 98, 'non-reg param lsb',
433 67, 'Soft Pedal',
434 99, 'non-reg param msb',
435 4, 'Foot Control (MSB)',
436 36, 'Foot Control (LSB)',
437 68, 'Legato Pedal',
438 100, 'Reg Param (LSB)',
439 5, 'Portamento Time (MSB)',
440 37, 'Portamento Time (LSB)',
441 69, 'Hold 2',
442 101, 'Reg Param (MSB)',
443 6, 'Data Entry (MSB)',
444 38, 'Data Entry (LSB)',
445 70, 'Sound Variation',
446 7, 'Channel Volume (MSB)',
447 39, 'Channel Volume (LSB)',
448 71, 'Resonance, Q',
449 8, 'Balance (MSB)',
450 40, 'Balance (LSB)',
451 72, 'Release Time',
452 73, 'Attack Time',
453 10, 'Pan (MSB)',
454 42, 'Pan (LSB)',
455 74, 'Cut-off Frequency',
456 11, 'Expression (MSB)',
457 43, 'Expression (LSB)',
458 75, 'Decay Time',
459 12, 'Effects Controller 1',
460 76, 'Vibrato Rate',
461 13, 'Effects Controller 2',
462 77, 'Vibrato Depth',
463 78, 'Vibrato Delay',
464 84, 'Portamento Control',
465 120, 'All Sound Off',
466 121, 'Reset All Controllers',
467 122, 'Local Control',
468 91, 'Reverb Depth',
469 123, 'All Notes Off',
470 92, 'Tremolo Depth',
471 124, 'Omni Off',
472 93, 'Chorus Depth',
473 125, 'Omni On',
474 94, 'Celeste (De-tune)',
475 126, 'Mono On (Poly off)',
476 95, 'Phaser Depth', # 1.9
477 127, 'Poly On (Mono off)', # 1.9, 5.1
478 );
479 }
480 return $c2s{$_[$[]} || '';
481 }
482
483 sub debug {
484 open (T, '>>', '/tmp/debug');
485 print T $_[$[],"\n";
486 close T;
487 }
488
489 sub delta_t { my $ie = $_[$[];
490 my $dt;
491 if ($ie == $[) { $dt = $Track[$ie][$[+1];
492 } else { $dt = $Track[$ie][$[+1] - $Track[$ie-1][$[+1];
493 }
494 return $dt;
495 }
496
497 sub display_events {
498 my ($i_top, $i_now, $i_bot) = row_nums();
499 my %seen_a_ped = (); # 6.0 remember by channel
500 my %seen_a_endped = ();
501 my %seen_a_cc = (); # 6.5 remember by channel and cc
502 my $note_str = '';
503 my $iline=$i_now-1; while ($iline >= $i_top) {
504 # go upwards to show the most recent Ped and * only; more elegant
505 my $now = $Ievent-$i_now+$iline;
506 my $note_str = note2str(@{$Track[$now]});
507 addl($iline, 0, event2str($now));
508 if ($Track[$now][$[] =~ /note/) {
509 if (($Track[$now][$[+1] + $Track[$now][$[+2]) > $Now) {
510 addl($iline, 57, note2str(@{$Track[$now]}));
511 if ($note_str) { # 4.1
512 attrset(A_BOLD());
513 move($iline,31); # "31" depends on event2str # 4.8
514 addstr(sprintf('%5d %5d',
515 $Track[$now][$[+3],$Track[$now][$[+4]));
516 attrset(A_NORMAL());
517 }
518 }
519 } elsif ($Track[$now][$[] =~ /control_change/) {
520 my $cha = $Track[$now][$[+2];
521 if ($Track[$now][$[+3] == 64) {
522 if ($Track[$now][$[+4] >= 64) {
523 if (! $seen_a_ped{$cha}) { addl($iline, 57, 'Ped'); } # 6.0
524 $seen_a_ped{$cha} = 1;
525 } else {
526 if (! $seen_a_endped{$cha}) { addl($iline, 57, '*'); } # 6.0
527 $seen_a_endped{$cha} = 1;
528 }
529 } else { # 6.5
530 my $cc = $Track[$now][$[+3];
531 if (! $seen_a_cc{$cha}{$cc}) { addl($iline, 57, cc2str($cc)); }
532 $seen_a_cc{$cha}{$cc} = 1;
533 }
534 } elsif ($Track[$now][$[] =~ /patch_change/) {
535 my $patch = $MIDI::number2patch{$Track[$now][$[+3]};
536 addl($iline, 57, $patch); # 6.4
537 } elsif ($Track[$now][$[] =~ /^sysex/) {
538 if ($sysex2str{$Track[$now][$[+2]}) { # 3.6
539 addl($iline, 57, $sysex2str{$Track[$now][$[+2]});
540 }
541 }
542 $iline -= 1;
543 }
544 refresh();
545 foreach my $iline (($i_now+1)..$i_bot) {
546 my $iev = $Ievent-$i_now+$iline;
547 addl($iline, 0, event2str($iev)); # 4.7
548 }
549 attrset(A_BOLD());
550 addl($i_now, 0, event2str($Ievent));
551 my $notestr = ''; # 2.1
552 if ($Track[$Ievent][$[] eq 'note') {
553 $notestr = note2str(@{$Track[$Ievent]});
554 } elsif ($Track[$Ievent][$[] eq 'patch_change') { # 6.4
555 $notestr = $MIDI::number2patch{$Track[$Ievent][$[+3]}
556 } elsif ($Track[$Ievent][$[] eq 'control_change') { # 6.5
557 # ideally, I'd like this to set $seen_a_cc{$cha}{$cc}, see 28 lines up
558 $notestr = cc2str($Track[$Ievent][$[+3])
559 }
560 if ($Editing) { addl($i_now,49, "EDITING $notestr "); # 1.4
561 } elsif ($Paused) { addl($i_now,49, "PAUSED $notestr "); # 2.1
562 } else { addl($i_now,49, "PLAYING $notestr "); # 2.1
563 }
564 attrset(A_NORMAL());
565 refresh();
566 }
567
568 sub display_keystrokes {
569 $TopKeystrokesLine = $LINES-4;
570 # addstr("Ievent=$Ievent KEY_UP=".KEY_UP()." stdscr=$stdscr");
571 if ($Message) {
572 move($LINES-4,2); clrtoeol();
573 addl($LINES-4, round(0.4*($COLS - length $Message)) ,$Message);
574 move($LINES-3,2); clrtoeol();
575 $Message = '';
576 } else {
577 my $dot = '';
578 if ((@EditEvent>1) and $EditEvent[$[] eq $Track[$Ievent][$[]) {
579 $dot = ' .=again';
580 }
581 my $ran = 'f=file R=set_range';
582 if ($RangeStart < $RangeEnd) { $ran .= ' r=range'; }
583 my $tim = '+=incrementaltimes';
584 if ($IncrementalTimes) { $tim = '-=absolutetimes'; }
585 addl($LINES-4,2, "$tim $ran i=insert e=edit$dot"); # 6.6
586 addl($LINES-3,2, 'k/Up/j/Down=+-1event '
587 . 'Right/Left=+-1sec PageDown/PageUp=+-10sec'); # 4.3
588 }
589 # p=paste y=yank ? dd ? 4dd ? 4j etc ?
590 my $s = 'D=Delete u=undo ^R=redo /=find ';
591 if (defined $NowBeforeFind) { # 7.7
592 $s = $s . '?=reverse n=next N=previous Backspace ';
593 } else {
594 $s = $s . '?=reversefind n=findnext N=findprevious ';
595 }
596 addl($LINES-2,2, $s);
597 if ($Paused) { # if event is editable, then t,d,c,n,v and Space=play
598 addl($LINES-1,2,
599 'Space=play ]/[=speed Home=start End=end z=allsoundsoff w=write q=quit');
600 } else {
601 addl($LINES-1,2,
602 'Space=pause ]/[=speed Home=start End=end z=allsoundsoff w=write q=quit');
603 }
604 refresh();
605 }
606
607 sub display_fields { # 4.4
608 my $event_type = $Track[$Ievent][$[];
609 if ($RangeSettingState == 1) { # 4.5
610 attrset(A_BOLD());
611 addl(0,5,' move to other end of range and press R');
612 attrset(A_NORMAL());
613 } elsif ($NewFileState == 1) { # 4.9
614 attrset(A_BOLD());
615 my $f = $File; # if filename too long use basename; 41=24+12+5; 5.0
616 if (length($f) > ($COLS-length($ID)-41)) { $f =~ s/^.*\///; }
617 addl(0,5,"now editing $f");
618 attrset(A_NORMAL());
619 } elsif ($event_type eq 'note') {
620 addl(0,5,' Event Ticks Dura Chan Pitch Vol');
621 } elsif ($event_type eq 'control_change') {
622 addl(0,5,' Event Ticks Chan Contrlr Value');
623 } elsif ($event_type eq 'patch_change') {
624 addl(0,5,' Event Ticks Chan Patch');
625 } else {
626 addl(0,5,' Event Ticks Data');
627 }
628 move(0,$COLS-length($ID)-24); addstr("ReplaySpeed=$RS"); # 3.1
629 move(0,$COLS-length($ID)-8); addstr("Output=$ID");
630 }
631
632 sub display_screen {
633 display_fields();
634 move(1,1); hline($ACS_HLINE,$COLS-2);
635 my $last = $Track[$#Track][$[+1];
636 move(1,$COLS-length($ID)-25); addstr(" Now at $Now / $last mS "); # 3.1
637 move($LINES-5,1); hline($ACS_HLINE,$COLS-2);
638 if ($Ievent == $#Track) { $Paused = 1; } # 4.1
639 display_keystrokes();
640 display_events();
641 refresh();
642 $I_LastRefreshed = $Now; # 6.7
643 }
644
645 sub display_message {
646 my ($y,$x); getyx($y,$x);
647 $Message = $_[$[]; display_keystrokes();
648 move($y,$x);
649 refresh();
650 }
651
652 sub edit_event { my $initial_ch = $_[$[];
653 # 2.9 must keep @EditEvent updated...
654 $Editing = 1;
655 my $prompt_y;
656 my $prompt_x;
657 sub time_prompt_to { my ($y, $x, $clr) = @_;
658 if ($IncrementalTimes) { addstr($y,$x-6,'time=+'.delta_t($Ievent));
659 } else { addstr($y,$x-5,'time='.$Track[$Ievent][$[+1]);
660 }
661 if ($clr) { clrtoeol(); }
662 }
663 sub keystroke_prompt { my $k = $_[$[];
664 if ($IncrementalTimes) { $k .= " -=absolutetimes";
665 } else { $k .= " +=incrementaltimes";
666 }
667 if ($Ievent == $[) { $k .= ' Down ';
668 } elsif ($Ievent == $#Track) { $k .= ' Up ';
669 } else { $k .= ' Up/Down ';
670 }
671 $k .= 'Space=Paused ';
672 addl($LINES-1,round(0.45*($COLS-length($k))),$k);
673 refresh();
674 getyx($prompt_y,$prompt_x); # why ?
675 }
676 sub display_this_event { my @event = @_; # 1.4
677 my $k;
678 move($LINES-4,1); clrtobot();
679 if ($event[$[] eq 'note') {
680 time_prompt_to($LINES-4,13,1);
681 addl($LINES-3,15,'duration='.$event[$[+2]);
682 addl($LINES-4,26,'channel='.$event[$[+3]);
683 addl($LINES-3,35,'pitch='.$event[$[+4]); # 5.0
684 addl($LINES-3,46,note2str(@event));
685 addl($LINES-4,43,'volume='.$event[$[+5]);
686 $k = 't=time d=duration c=chan p=pitch v=vol';
687 } elsif ($event[$[] eq 'control_change') {
688 time_prompt_to($LINES-4,14,1);
689 addl($LINES-3,19,'channel='.$event[$[+2]);
690 addl($LINES-4,29,'midi-controller='.$event[$[+3]);
691 addl($LINES-4,49,cc2str($Track[$Ievent][$[+3]));
692 addl($LINES-3,41,'value='.$event[$[+4]);
693 $k = 't=time c=chan m=midicontroller v=value';
694 } elsif ($event[$[] eq 'patch_change') {
695 time_prompt_to($LINES-4,14,1);
696 addl($LINES-4,25,'channel='.$event[$[+2]);
697 addl($LINES-4,44,'patch='.$event[$[+3]);
698 addl($LINES-4,55,$MIDI::number2patch{$Track[$Ievent][$[+3]});
699 $k = 't=time c=channel p=patch';
700 } elsif ($event[$[] =~ /^marker|^text|^sysex_f0/) {
701 time_prompt_to($LINES-4,14,1);
702 addl($LINES-4,25,'message='.$event[$[+2]);
703 $k = 't=time m=message';
704 }
705 # 3.8 offer edit_again if applicable
706 # (perhaps if Ievent != LastEditedIevent)
707 if ((@EditEvent>1) and $EditEvent[$[] eq $Track[$Ievent][$[]) {
708 $k .= ' .=again';
709 }
710 display_events();
711 keystroke_prompt($k); move($prompt_y,$prompt_x); refresh();
712 }
713
714 my @event = @{$Track[$Ievent]};
715 @EditEvent = ($event[$[]); # 2.9 remember the event_type
716 my $changed = 0;
717 timeout(-1);
718 my $i_before_edit = $Ievent;
719 while (1) {
720 display_this_event(@event);
721 if ($event[$[] eq 'note') {
722 while (1) {
723 my $c = getch();
724 if ($c eq 't') { get_n($LINES-4,13,6,1); $changed=1;
725 } elsif ($c eq 'd') { get_n($LINES-3,24,6,2); $changed=1;
726 } elsif ($c eq 'c') { get_n($LINES-4,34,3,3); $changed=1;
727 addl($LINES-3,46,note2str(@{$Track[$Ievent]}));
728 } elsif ($c eq 'p') { get_n($LINES-3,41,5,4); $changed=1; #5.0
729 addl($LINES-3,46,note2str(@{$Track[$Ievent]}));
730 } elsif ($c eq 'v') { get_n($LINES-4,50,6,5); $changed=1;
731 } elsif ($c eq '+' and !$IncrementalTimes) {
732 $IncrementalTimes = 1; display_this_event(@event);
733 } elsif (($c eq '-' || $c eq '=') and $IncrementalTimes) {
734 $IncrementalTimes = 0; display_this_event(@event);
735 } elsif ($c == KEY_UP() or $c eq 'k') { # 1.4, 4.0
736 if ($Ievent > $[) {
737 event_travel(-1); # 5.2
738 @event = @{$Track[$Ievent]};
739 display_this_event(@event);
740 display_fields(); # 4.4
741 last; # 1.5
742 }
743 } elsif ($c == KEY_DOWN() or $c eq 'j') { # 1.4, 4.0
744 if ($Ievent < $#Track) {
745 event_travel(1); # 5.2
746 @event = @{$Track[$Ievent]};
747 display_this_event(@event);
748 display_fields(); # 4.4
749 last; # 1.5
750 }
751 } elsif ($c eq 'e') { next; # 1.4
752 } elsif ($c eq '.') {
753 set_before_last_change($i_before_edit); # 7.5
754 edit_again(); # 3.8 display_screen();
755 } else {
756 if ($changed) {
757 set_before_last_change($i_before_edit); # 7.5
758 add_to_history();
759 }
760 $Editing = 0;
761 # press / ? n N during Editing should Pause, call ind_event and exit
762 return;
763 }
764 # display_events(); move($prompt_y,$prompt_x); refresh();
765 @event = @{$Track[$Ievent]}; # 2.7
766 display_this_event(@event);
767 }
768 } elsif ($event[$[] eq 'control_change') {
769 while (1) {
770 my $c = getch();
771 if ($c eq 't') { get_n($LINES-4,14,6,1); $changed=1;
772 } elsif ($c eq 'c') { get_n($LINES-3,27,2,2); $changed=1;
773 } elsif ($c eq 'm') { get_n($LINES-4,45,3,3); $changed=1;
774 addl($LINES-4,49,cc2str($Track[$Ievent][$[+3]));
775 } elsif ($c eq 'v') { get_n($LINES-3,47,3,4); $changed=1;
776 } elsif ($c eq '+' and !$IncrementalTimes) {
777 $IncrementalTimes = 1; display_this_event(@event);
778 } elsif (($c eq '-' || $c eq '=') and $IncrementalTimes) {
779 $IncrementalTimes = 0; display_this_event(@event);
780 } elsif ($c == KEY_UP() or $c eq 'k') { # 1.4, 4.0
781 if ($Ievent > $[) {
782 if ($Now - $Track[$Ievent-1][$[+1] < 2) { # 4.8
783 $Track[$Ievent-1][$[+1] -= 1;
784 }
785 time_travel($Track[$Ievent-1][$[+1] + 1 - $Now);
786 @event = @{$Track[$Ievent]};
787 display_this_event(@event);
788 play_current_event(); last; # 1.5
789 }
790 } elsif ($c == KEY_DOWN() or $c eq 'j') { # 1.4, 4.0
791 if ($Ievent < $#Track) {
792 $Ievent += 1; $Now = $Track[$Ievent][$[+1] + 1;
793 @event = @{$Track[$Ievent]};
794 display_this_event(@event);
795 play_current_event(); last; # 1.5
796 }
797 } elsif ($c eq 'e') { next; # 1.4
798 } elsif ($c eq '.') { edit_again(); # 3.8 display_screen();
799 } else {
800 if ($changed) {
801 set_before_last_change($i_before_edit); # 7.5
802 add_to_history();
803 }
804 $Editing = 0; return;
805 }
806 # display_events(); move($prompt_y,$prompt_x); refresh();
807 @event = @{$Track[$Ievent]}; # 1.6
808 display_this_event(@event);
809 }
810 } elsif ($event[$[] eq 'patch_change') {
811 while (1) {
812 #get_n($LINES-4,50,3,3); $changed=1; # XXX
813 #addl($LINES-4,55,$MIDI::number2patch{$Track[$Ievent][$[+3]});
814 my $c;
815 if ($initial_ch) { $c = $initial_ch; $initial_ch = undef;
816 } else { $c = getch();
817 }
818 if ($c eq 't') { get_n($LINES-4,14,6,1); $changed=1;
819 } elsif ($c eq 'c') { get_n($LINES-4,33,3,2); $changed=1;
820 } elsif ($c eq 'p') { get_n($LINES-4,50,3,3); $changed=1;
821 addl($LINES-4,55,$MIDI::number2patch{$Track[$Ievent][$[+3]});
822 } elsif ($c eq '+' and !$IncrementalTimes) {
823 $IncrementalTimes = 1; display_this_event(@event);
824 } elsif (($c eq '-' || $c eq '=') and $IncrementalTimes) {
825 $IncrementalTimes = 0; display_this_event(@event);
826 } elsif ($c == KEY_UP() or $c eq 'k') { # 1.4, 4.0
827 if ($Ievent > $[) {
828 if ($Now - $Track[$Ievent-1][$[+1] < 2) { # 4.8
829 $Track[$Ievent-1][$[+1] -= 1;
830 }
831 time_travel($Track[$Ievent-1][$[+1] + 1 - $Now); # 4.8
832 @event = @{$Track[$Ievent]};
833 display_this_event(@event);
834 play_current_event(); last; # 1.5
835 }
836 } elsif ($c == KEY_DOWN() or $c eq 'j') { # 1.4, 4.0
837 if ($Ievent < $#Track) {
838 $Ievent += 1; $Now = $Track[$Ievent][$[+1] + 1;
839 @event = @{$Track[$Ievent]};
840 display_this_event(@event);
841 play_current_event(); last; # 1.5
842 }
843 } elsif ($c eq 'e') { next; # 1.4
844 } elsif ($c eq '.') { edit_again(); # 3.8 display_screen();
845 } else {
846 if ($changed) {
847 set_before_last_change($i_before_edit); # 7.5
848 add_to_history();
849 }
850 $Editing = 0; return;
851 }
852 @event = @{$Track[$Ievent]}; # 2.7
853 display_this_event(@event);
854 }
855 } elsif ($event[$[] =~ /^marker|^text|^sysex_f0/) {
856 while (1) {
857 my $c;
858 if ($initial_ch) { $c = $initial_ch; $initial_ch = undef;
859 } else { $c = getch();
860 }
861 if ($c eq 't') { get_n($LINES-4,14,6,1); $changed=1;
862 } elsif ($c eq 'm') {
863 my $s='';
864 move($LINES-4,33); clrtoeol();
865 echo(); getnstr($s,52); noecho();
866 $changed=1; $Track[$Ievent][$[+2] = $s;
867 $EditEvent[$[+2] = $s; # 7.3
868 } elsif ($c eq '+' and !$IncrementalTimes) {
869 $IncrementalTimes = 1; display_events();
870 time_prompt_to($LINES-4,14,0); keystroke_prompt($k);
871 refresh();
872 } elsif (($c eq '-' || $c eq '=') and $IncrementalTimes) {
873 $IncrementalTimes = 0; display_events();
874 time_prompt_to($LINES-4,14,0); keystroke_prompt($k);
875 refresh();
876 } elsif ($c == KEY_UP() or $c eq 'k') { # 1.4, 4.0
877 if ($Ievent > $[) {
878 $Ievent -= 1; $Now = $Track[$Ievent][$[+1] + 1;
879 @event = @{$Track[$Ievent]};
880 display_this_event(@event); last;
881 }
882 } elsif ($c == KEY_DOWN() or $c eq 'j') { # 1.4, 4.0
883 if ($Ievent < $#Track) {
884 $Ievent += 1; $Now = $Track[$Ievent][$[+1] + 1;
885 @event = @{$Track[$Ievent]};
886 display_this_event(@event); last;
887 }
888 } elsif ($c eq 'e') { next; # 1.4
889 } elsif ($c eq '.') { edit_again(); # 3.8 display_screen();
890 } else {
891 if ($changed) {
892 set_before_last_change($i_before_edit); # 7.5
893 add_to_history();
894 }
895 $Editing = 0; return;
896 }
897 # display_events(); move($prompt_y,$prompt_x); refresh();
898 @event = @{$Track[$Ievent]}; # 2.7
899 display_this_event(@event);
900 }
901 } else {
902 time_prompt_to($LINES-4,14,1);
903 my $k = 't=time, ';
904 keystroke_prompt($k); refresh();
905 while (1) {
906 my $c = getch();
907 if ($c eq 't') { get_n($LINES-4,14,6,1); $changed=1;
908 } elsif ($c eq '+' and !$IncrementalTimes) {
909 $IncrementalTimes = 1; display_events();
910 time_prompt_to($LINES-4,14,0); keystroke_prompt($k);
911 refresh();
912 } elsif (($c eq '-' || $c eq '=') and $IncrementalTimes) {
913 $IncrementalTimes = 0; display_events();
914 time_prompt_to($LINES-4,14,0); keystroke_prompt($k);
915 refresh();
916 } elsif ($c == KEY_UP() or $c eq 'k') { # 1.4, 4.0
917 if ($Ievent > $[) {
918 $Ievent -= 1; $Now = $Track[$Ievent][$[+1] + 1;
919 @event = @{$Track[$Ievent]};
920 display_this_event(@event); last;
921 }
922 } elsif ($c == KEY_DOWN() or $c eq 'j') { # 1.4, 4.0
923 if ($Ievent < $#Track) {
924 $Ievent += 1; $Now = $Track[$Ievent][$[+1] + 1;
925 @event = @{$Track[$Ievent]};
926 display_this_event(@event); last;
927 }
928 } elsif ($c eq 'e') { next; # 1.4
929 } elsif ($c eq '.') { edit_again(); # 3.8 display_screen();
930 } else {
931 if ($changed or $called_from_insert_event) { # 4.3
932 play_current_event(); # 4.4
933 set_before_last_change($i_before_edit); # 7.5
934 add_to_history();
935 }
936 $Editing = 0; return;
937 }
938 # display_events(); move($prompt_y,$prompt_x); refresh();
939 @event = @{$Track[$Ievent]}; # 2.7
940 display_this_event(@event);
941 # !!! should play the event !!!
942 }
943 }
944 }
945 }
946
947 sub sanitise_event_text { my @event = @_; # 7.2
948 $event[$[+2] =~ tr/][A-Za-z0-9 _'"`.+:\/@&)(=*^%$#!?}{|\\~-//cd; # 7.1
949 $event[$[+2] =~ s/\s+/ /g;
950 $event[$[+2] =~ s/^\s+//;
951 return @event;
952 }
953
954 sub event2str { my ($ie) = @_;
955 if ($ie > $#Track) { return ''; } # 4.7 needed after a big range_delete
956 if ($ie < $[) { debug("event2str($ie)"); }
957 my @event = @{$Track[$ie]};
958 my $str = ' ';
959 if ($IncrementalTimes) {
960 if ($ie > $[) { $event[$[+1] -= $Track[$ie-1][$[+1]; }
961 $event[$[+1] = "+".$event[$[+1];
962 if ($event[$[] =~ /marker|sysex|text|track_name/) { # 7.2 track_name
963 $str = sprintf(' %14s %6s %s', sanitise_event_text(@event));
964 } elsif (6 == scalar @event) {
965 $str = sprintf(' %14s %6s %5d %5d %5d %5d', @event);
966 } elsif (5 == scalar @event) {
967 $str = sprintf(' %14s %6s %5d %5d %5d', @event);
968 } elsif ($event[$[] eq 'pitch_wheel_change') {
969 $str = sprintf('%s %5s %4d %6d', @event);
970 } elsif (! defined $event[$[]) {
971 } elsif (4 == scalar @event) {
972 if ($event[$[] eq 'channel_after_touch') { # 6.8
973 $event[$[] = 'cha_aftertouch';
974 }
975 $str = sprintf(' %14s %6s %5d %5d', @event);
976 } elsif (3 == scalar @event) {
977 $str = sprintf(' %14s %6s %5d', @event);
978 }
979 } else {
980 if ($event[$[] =~ /marker|sysex|text|track_name/) { # 7.2 track_name
981 $str = sprintf(' %14s %6s %s', sanitise_event_text(@event));
982 } elsif (6 == scalar @event) {
983 $str = sprintf(' %14s %6d %5d %5d %5d %5d', @event);
984 } elsif (5 == scalar @event) {
985 $str = sprintf(' %14s %6d %5d %5d %5d', @event);
986 } elsif ($event[$[] eq 'pitch_wheel_change') {
987 $str = sprintf('%s %5s %4d %6d', @event);
988 } elsif (! defined $event[$[]) {
989 } elsif (4 == scalar @event) {
990 if ($event[$[] eq 'channel_after_touch') { # 6.8
991 $event[$[] = 'cha_aftertouch';
992 }
993 $str = sprintf(' %14s %6d %5d %5d', @event);
994 } elsif (3 == scalar @event) {
995 $str = sprintf(' %14s %6d %5d', @event);
996 }
997 }
998 if (($ie == $RangeStart) || ($ie == $RangeEnd)) {
999 $str =~ s/^./-/; # 4.5
1000 # $str =~ s/^./\e[31m-/; # Nope, this just gets displayed in ascii
1001 # $str .= "\e[39m"; # and perl Curses doesn't support any color
1002 # man color; perldoc Curses | grep color
1003 } elsif (($ie > $RangeStart) && ($ie < $RangeEnd)) {
1004 $str =~ s/^./|/;
1005 # $str =~ s/^./\e[31m|/; # Nope, this just gets displayed in ascii
1006 # $str .= "\e[39m"; # and perl Curses doesn't support any color
1007 }
1008 return $str;
1009 }
1010
1011 sub event_type { # this dialogue is used by insert_event();
1012 if (! $Paused) { $Paused = 1; timeout(-1); display_events(); }
1013 move($LINES-4,2); clrtobot(); addstr('Insert event type ? ');
1014 my $s
1015 = 'n=note, c=control_change, p=patch_change, m=marker, b=bank_change ';
1016 addl($LINES-2, round(0.4*($COLS - length $s)) ,$s);
1017 move($LINES-4,22);
1018 refresh();
1019 my %c2event_type = qw{
1020 b bank_change n note c control_change p patch_change m marker
1021 };
1022 return $c2event_type{getch()};
1023 }
1024
1025 sub file_menu { # 4.8
1026 if (! $Paused) { $Paused = 1; timeout(-1); display_events(); }
1027 move($LINES-4,0); clrtobot();
1028 my $x=13;
1029 # addl($LINES-2,$x,'f=fork n=new s=save w=write q=quit');
1030 addl($LINES-2,$x,'f=fork i=insert n=new s=save w=write q=quit');
1031 addl($LINES-3,4,'which file operation ? '); my $x=27;
1032 my $c = getch(); clrtobot(); echo();
1033 if ($c eq 'f') {
1034 addl($LINES-3,$x,'fork');
1035 if ($FileIsChanged) {
1036 addl($LINES-2,4,"save $File first (y/n) ? ");
1037 my $c = getch();
1038 if ($c eq 'y' or $c eq 'w') { score2file($File, 1000,\@Track); }
1039 }
1040 my $new_filename = $File;
1041 foreach $s ('a'..'z') {
1042 $new_filename = $File;
1043 $new_filename =~ s/(_[a-z][a-z])?\.mid$/$s$1.mid/i;
1044 if (! -e $new_filename) { last ; }
1045 }
1046 $File = $new_filename;
1047 $NewFileState = 1;
1048 $FileIsChanged = 0;
1049 } elsif ($c eq 'i') { # 6.2
1050 my $filename = ask_filename($LINES-2, 'insert which file ? ');
1051 if (! $filename) { return; }
1052 if (! -e $filename) { _warn("$filename does not exist"); return; }
1053 my @new_score = file2ms_score($filename);
1054 my @new_track = @{$new_score[$[+1]};
1055 if ($new_track[$[][$[] eq 'set_tempo') { shift @new_track; }
1056 if (! @new_track) { _warn("$filename contains no events"); return; }
1057 # evolved from range_repeat ...
1058 @new_track = sort { $a->[$[+1] <=> $b->[$[+1] } @new_track;
1059 my $delta = $new_track[$#new_track][$[+1]; # one note short?
1060 my $start_time = $Track[$Ievent][$[+1];
1061 my $k = $[;
1062 while ($k <= $#new_track) { $new_track[$k][$[+1]+=$start_time; $k+=1; }
1063 $k = $Ievent;
1064 while ($k <= $#Track) { $Track[$k][$[+1] += $delta; $k += 1; }
1065 # XXX should insert a marker at the start "inserted from $filename"
1066 splice @Track, $Ievent, 0, @new_track;
1067 # time_travel($delta); No: leave Ievent at the start (to edit patches)
1068 $RangeStart = $Ievent;
1069 $RangeEnd = $Ievent - 1 + scalar @new_track;
1070 $Message = sprintf("%d new events", scalar @new_track);
1071 set_before_last_change($Ievent); # 7.5
1072 add_to_history();
1073
1074 } elsif ($c eq 'n') {
1075 new_file();
1076 my $filename = ask_filename($LINES-2,'new filename ? ');
1077 if (! $filename) { return; } # 6.2
1078 if (! -e $filename) { _warn("$filename does not exist"); return; }
1079 $File = $filename;
1080 @score = file2ms_score($File); # 1.7
1081 @Track = sort {$$a[$[+1] <=> $$b[$[+1]} @{$score[1]};
1082 $Now = 0;
1083 $Ievent = $[;
1084 $Paused = 1;
1085 $Editing = 0;
1086 $NewFileState = 1;
1087 all_sounds_off();
1088 } elsif ($c eq 's' or $c eq 'w') {
1089 addl($LINES-3,$x,'save file'); # same as 'w' = write
1090 score2file($File, 1000,\@Track);
1091 _warn("Saved to $File");
1092 $FileIsChanged = 0;
1093 } elsif ($c eq 'q') { # same as 'q' = quit
1094 if ($Paused) { quit(); }
1095 $Paused = 1; timeout(-1); # display_screen();
1096 }
1097 }
1098
1099 sub find_type { # used by find(); since 3.7 different from event_type
1100 if (! $Paused) { $Paused = 1; timeout(-1); display_events(); }
1101 move($LINES-4,2); clrtobot(); addstr('Find event type ? ');
1102 my $s
1103 = 'n=note, c=control_change, p=patch_change, m=marker, b=bank_change ';
1104 addl($LINES-2, round(0.4*($COLS - length $s)) ,$s);
1105 $s = 'l=long_gap, s=short_gap, t=time';
1106 my %c2event_type = qw{
1107 b bank_change n note c control_change p patch_change m marker
1108 l long_gap s short_gap t time
1109 };
1110 if ($RangeStart < $RangeEnd) {
1111 $s .= ', r=range_start R=range_end';
1112 $c2event_type{'r'} = 'range_start'; # 7.6 only if a range is defined!
1113 $c2event_type{'R'} = 'range_end'; # 7.6
1114 }
1115 addl($LINES-1, round(0.4*($COLS - length $s)) ,$s);
1116 move($LINES-4,20);
1117 refresh();
1118 return $c2event_type{getch()};
1119 }
1120
1121 sub find {
1122 my $event_type = find_type();
1123 if (! $event_type) { return; }
1124 addl($LINES-4,20,$event_type);
1125 if ($event_type eq 'time') { go_to(); return; } # 3.7
1126 if ($event_type =~ /_gap$/) { find_gap($event_type); return; } # 4.2
1127 if ($event_type ne 'marker') {
1128 my $help = 'e.g. 64, >63, <65, !=93, >47&<73'; # 3.1
1129 addl($LINES-4,$COLS-length($help)-2,$help);
1130 }
1131 if ($event_type eq 'range_start') { # 4.5
1132 time_travel($Track[$RangeStart][$[+1]-$Track[$Ievent][$[+1]); return;
1133 }
1134 if ($event_type eq 'range_end') { # 4.5
1135 time_travel($Track[$RangeEnd][$[+1]-$Track[$Ievent][$[+1]); return;
1136 }
1137 refresh;
1138 @FindEvent = ($event_type);
1139 if ($event_type eq 'note') {
1140 addl($LINES-3,2,' Duration ?');
1141 addl($LINES-2,2,' Channel (0..15) ?');
1142 addl($LINES-1,2,' Pitch (0..127) ?');
1143 # shame about Volume not fitting on the screen...
1144 refresh();
1145 my $iline = 3;
1146 while ($iline > 0) {
1147 move($LINES-$iline,24);
1148 my $str; my $n;
1149 echo(); getnstr($str,20); noecho();
1150 if (length $str) { $FindEvent[$[+5-$iline] = $str; } # 2.8, 3.0
1151 $iline -= 1;
1152 }
1153 #warn "FindEvent = ".join(', ',@FindEvent)."\r\n";
1154 } elsif ($event_type eq 'control_change') {
1155 addl($LINES-3,2,' Channel (0..15) ?');
1156 addl($LINES-2,2,'Controller (0..127) ?');
1157 addl($LINES-1,2,' Value (0..127) ?');
1158 refresh();
1159 my $iline = 3;
1160 while ($iline > 0) {
1161 move($LINES-$iline,24);
1162 my $str; my $n;
1163 echo(); getnstr($str,20); noecho();
1164 if (length $str) { $FindEvent[$[+5-$iline] = $str; } # 2.8
1165 $iline -= 1;
1166 }
1167 # warn "FindEvent = ".join(', ',@FindEvent)."\r\n"; sleep 5;
1168 } elsif ($event_type eq 'patch_change') {
1169 addl($LINES-3,2,' Channel (0..15) ?');
1170 addl($LINES-2,2,' Patch (0..127) ?');
1171 clrtobot(); refresh();
1172 my $iline = 3;
1173 while ($iline > 1) {
1174 move($LINES-$iline,24);
1175 my $str; my $n;
1176 echo(); getnstr($str,20); noecho();
1177 if (length $str) { $FindEvent[$[+5-$iline] = $str; } # 2.8
1178 $iline -= 1;
1179 }
1180 } elsif ($event_type eq 'marker') {
1181 addl($LINES-3,2,' Text ? ');
1182 clrtobot(); refresh();
1183 my $str; my $n;
1184 echo(); $n = getnstr($str,50); noecho();
1185 if ($str) { $FindEvent[$[+2] = $str; } # 5.9
1186 } else {
1187 return;
1188 }
1189 find_next($FindForwards);
1190 }
1191
1192 sub find_gap { my $event_type = $_[$[]; # 4.2
1193 # we roll the search into find_next(), so that 'n' or 'N' work
1194 if ($event_type eq 'long_gap') {
1195 addl($LINES-3,2,'gap longer than (mS) ? ');
1196 } elsif ($event_type eq 'short_gap') {
1197 addl($LINES-3,2,'gap shorter than (mS) ? ');
1198 } else {
1199 return;
1200 }
1201 clrtobot(); refresh(); echo(); $n = getnstr($str,50); noecho();
1202 if (! defined $str) { return; }
1203 @FindEvent = ($event_type,0+$str);
1204 find_next($FindForwards);
1205 }
1206
1207 sub find_match { my ($search_str, $num) = @_; # 3.0
1208 if (! defined $search_str) { return 1; }
1209 if ($str =~ /^\d+$/) {
1210 if ((0+$num)==(0+$search_str)) { return 1; } else { return 0; }
1211 }
1212 foreach my $str (split /&/, $search_str) {
1213 if ($str =~ /^>(\d+)$/) { if (!((0+$num)> (0+$1))) { return 0; }
1214 } elsif ($str =~ /^<(\d+)$/) { if (!((0+$num)< (0+$1))) { return 0; }
1215 } elsif ($str =~ /^>=(\d+)$/) { if (!((0+$num)>=(0+$1))) { return 0; }
1216 } elsif ($str =~ /^<=(\d+)$/) { if (!((0+$num)<=(0+$1))) { return 0; }
1217 } elsif ($str =~ /^!=(\d+)$/) { if (!((0+$num)!=(0+$1))) { return 0; }
1218 } else { if (!($num eq $str)) { return 0; }
1219 }
1220 }
1221 return 1;
1222 }
1223
1224 sub event_matches { my ($f, $e) = @_; my @fe = @$f; my @ev = @$e;
1225 # factored out as a subroutine, 7.6
1226 if ($FindSubstring and $fe[$[] eq 'marker') { # 7.6
1227 if (! defined $fe[$[+2]) { return 1; } # blank text finds all markers
1228 if (index($ev[$[+2], $fe[$[+2]) < $[) { return 0; }
1229 } else {
1230 foreach my $i ($[+1 .. $#fe) {
1231 if (defined $fe[$i] and !find_match($fe[$i],$ev[$i])) { return 0; }
1232 }
1233 }
1234 return 1;
1235 }
1236 sub find_next { my $find_forwards = $_[$[];
1237 #warn "FindEvent=@FindEvent\n"; sleep 3;
1238 my $iev = $Ievent;
1239 my $found = 0;
1240 if ($find_forwards) {
1241 while ($iev < $#Track) {
1242 $iev += 1;
1243 if ($FindEvent[$[] eq $Track[$iev]->[$[]) {
1244 if (event_matches(\@FindEvent,$Track[$iev])) {$found=1; last;}
1245 } elsif ($FindEvent[$[] eq 'long_gap') {
1246 if (delta_t($iev) > $FindEvent[$[+1]) { $found = 1; last; }
1247 } elsif ($FindEvent[$[] eq 'short_gap') {
1248 if (delta_t($iev) < $FindEvent[$[+1]) { $found = 1; last; }
1249 }
1250 }
1251 } else {
1252 while ($iev > $[) {
1253 $iev -= 1;
1254 if ($FindEvent[$[] eq $Track[$iev]->[$[]) {
1255 if (event_matches(\@FindEvent,$Track[$iev])) {$found=1; last;}
1256 } elsif ($FindEvent[$[] eq 'long_gap') {
1257 if (delta_t($iev) > $FindEvent[$[+1]) { $found = 1; last; }
1258 } elsif ($FindEvent[$[] eq 'short_gap') {
1259 if (delta_t($iev) < $FindEvent[$[+1]) { $found = 1; last; }
1260 }
1261 }
1262 }
1263 if ($found) {
1264 $NowBeforeFind = $Now; # 7.7
1265 time_travel($Track[$iev][$[+1] - $Now); # 4.3
1266 $Ievent = $iev; # in case there are following events with zero dt
1267 display_screen();
1268 } else {
1269 $Message = "Event (".join(', ',@FindEvent).") not found";
1270 }
1271 }
1272
1273 sub get_n { my ($y, $x, $l, $i) = @_;
1274 move($y,$x); addstr(' 'x$l); move($y,$x); refresh();
1275 my $t; echo(); getnstr($t, $l); noecho();
1276 if ($t =~ /^\d+$/) {
1277 if ($i == 1 and $IncrementalTimes and $Ievent>$[) {
1278 my $dt = $t - delta_t($Ievent);
1279 $Track[$Ievent][$[+1] = $Track[$Ievent-1][$[+1]+$t;
1280 foreach my $ie ($Ievent+1..$#Track) { $Track[$ie][$[+1] += $dt; }
1281 $EditEvent[$[+$i] = $t; # 3.7 BUG if IncrementalTimes has changed
1282 } elsif ($i == 1 and ! $IncrementalTimes) {
1283 $Track[$Ievent][$[+1] = 0+$t; # it might have changed order :-(
1284 @Track = sort {$$a[$[+1] <=> $$b[$[+1]} @Track;
1285 } else {
1286 $Track[$Ievent][$[+$i] = 0+$t;
1287 $EditEvent[$[+$i] = $t; # 2.9
1288 }
1289 } elsif ($t =~ /^[-+]\d+$/) { # 3.0 increments, e.g +10 or -15
1290 if ($i > 1) {
1291 $Track[$Ievent][$[+$i] += 0+$t;
1292 $EditEvent[$[+$i] = $t; # it's still a string
1293 }
1294 }
1295 }
1296
1297 sub go_to {
1298 if (! $Paused) { $Paused = 1; timeout(-1); display_events(); }
1299 my $q = ' Go to time (ms) ? ';
1300 addl($LINES-3,2,$q); clrtobot(); refresh();
1301 my $str; my $n; echo(); $n = getnstr($str,10); noecho();
1302 time_travel($str-$Now); play_current_event();
1303 return;
1304 }
1305
1306 sub insert_event {
1307 my $event_type = event_type();
1308 if (! $event_type) { return; }
1309 # 4.8 patch_change must be earlier than just 1 tick before
1310 my $gap_to_previous_event = $Track[$Ievent][$[+1]-$Track[$Ievent-1][$[+1];
1311 my $gap_to_inserted_event = round(0.5 * $gap_to_previous_event);
1312 if ($gap_to_inserted_event < 1) { $gap_to_inserted_event = 1; }
1313 my $t = $Track[$Ievent][$[+1] - $gap_to_inserted_event; # 4.8
1314 if ($t < 0) { $t = 0; }
1315 my @InsertEvent = ($event_type, $t);
1316 if ($event_type eq 'note') { push @InsertEvent, 200,0,60,100; # 5.4
1317 } elsif ($event_type eq 'patch_change') { push @InsertEvent, 0, 0;
1318 } elsif ($event_type eq 'control_change') { push @InsertEvent, 0, 10, 64;
1319 } elsif ($event_type eq 'marker') { push @InsertEvent, 'NEW SECTION';
1320 } elsif ($event_type eq 'bank_change') {
1321 $InsertEvent[$[] = 'control_change';
1322 my @msb = (@InsertEvent, 0, 0, 5);
1323 splice @Track, $Ievent, 0, \@msb;
1324 $Ievent += 1;
1325 push @InsertEvent, 0, 32, 5;
1326 }
1327 splice @Track, $Ievent, 0, \@InsertEvent;
1328 $FileIsChanged = 1; # could add_to_history, but normally it will be edited
1329 if ($RangeStart >= $Ievent) { $RangeStart += 1; } # 4.5
1330 if ($RangeEnd >= $Ievent) { $RangeEnd += 1; }
1331 local $called_from_insert_event = 1; # 4.3
1332 # after ip we could often go straight to the patch number 'p',
1333 # (so ip4 not ipp4) but it's a drag if you only want to edit the channel.
1334 edit_event();
1335 play_current_event();
1336 # should play_current_event perhaps here, perhaps in edit_event ...
1337 # in edit_event there are many returns, and there are only two calls
1338 }
1339
1340 sub metronome_event { my $c = $_[$[]; # must work in Play mode
1341 # how do we set whether to insert a click or insert a marker or both ?
1342 # Is this really necessary anyway ?
1343 # it was just part of a crazy scheme to make midi2muscript easier...
1344 my $pitch = 33;
1345 my $text = 'NEW BEAT';
1346 if ($c eq 'B') { $pitch = 34; $text = 'NEW BAR'; }
1347 # In Play mode, we want to insert just before the note currently playing.
1348 # But Ievent doesn't necessarily point there; it might be pointing
1349 # to a control_change event that has been output subsequently.
1350 my $ievent = $Ievent;
1351 my $time = $Track[$ievent][$[+1] - 1; # just before the current event
1352 if ($time < 0) { $time = 0; }
1353 # my @event = ('note',$time, 500,9,$pitch,80);
1354 my @event = ('marker',$time, $text);
1355 splice @Track, $ievent, 0, \@event;
1356 $Ievent += 1; $FileIsChanged = 1;
1357 }
1358
1359 sub note2str { my ($s,$t,$dt,$cha,$note,$vol) = @_;
1360 if ($s eq "control_change") {
1361 if ($dt==64) { # cc=
1362 if ($note > 63) { return "Ped"; } else { return "*"; }
1363 }
1364 return '';
1365 }
1366 if (0+$cha == 9) {
1367 if ($note == 33) { return 'Metronome Click'; } # 7.0
1368 if ($note == 34) { return 'Metronome Bell'; } # 7.0
1369 return $MIDI::notenum2percussion{$note};
1370 }
1371 # XXX By default, midiedit should display pitches
1372 # mapped left-to-right like a miniature piano:
1373 # C ab | Eb
1374 # C | Eb f~
1375 # | Eb b f~
1376 # If possible at least 3 characters per octave, plus '| ' unmoving;
1377 # bass is 3.3 octaves, treble 4 octaves = 22 chars; plus '| ' makes 24
1378 # If less than 15 are available, revert to 'treble f~##' which uses 11.
1379 # Could also display the sounding chord, eg 'c233' or 'eb26' or 'Eb F B'
1380 my $clef = 'bass'; if ($note >= 60) { $clef = 'treble'; $note -= 24; }
1381 my $octave = '';
1382 if ($note < 36) {
1383 my $o = int((47-$note)/12);
1384 $octave = '_' x $o;
1385 $note += 12 * $o; # 1.8
1386 } elsif ($note >= 60) {
1387 my $o = int(($note-48)/12);
1388 $octave = '~' x $o;
1389 $note -= 12 * $o; # 1.8
1390 }
1391 $note -= 36;
1392 return "$clef $note2letter[$note%24]$octave$note2acc[$note%12]";
1393 }
1394
1395 sub play_current_event {
1396 my @event = @{$Track[$Ievent]};
1397 if ($event[$[] eq 'note') { # 3.1 and 5.1 adjust the duration
1398 $event[$[+2] = round($event[$[+2] / $ReplaySpeed); # millisec
1399 }
1400 my @alsaevent = MIDI::ALSA::scoreevent2alsa(@event);
1401 my ($status, $time,$events) = MIDI::ALSA::status();
1402 $alsaevent[$[+4] = $time+0.005;
1403 MIDI::ALSA::output(@alsaevent);
1404 }
1405
1406 sub edit_again {
1407 if (@EditEvent < 2) { return; }
1408 my @event = @{$Track[$Ievent]};
1409 # if only ticks is involved, .=again should work even on different-types
1410 if (($EditEvent[$[] ne $event[$[]) and (2 < @EditEvent)) {
1411 $Message = "can't apply a (" . join(',',@EditEvent)
1412 . ") edit to a $event[$[] event"; # 4.3
1413 return;
1414 }
1415 my $i = $[+1; if (defined $EditEvent[$i]) { # 3.7
1416 my $t = $EditEvent[$i];
1417 if ($IncrementalTimes and $Ievent>$[) { # similar to sub get_n above
1418 my $dt = $t - delta_t($Ievent);
1419 $event[$i] = $Track[$Ievent-1][$i] + $t;
1420 foreach my $ie ($Ievent+1..$#Track) { $Track[$ie][$i] += $dt; }
1421 }
1422 }
1423 for $i ($[+2 .. $#EditEvent) {
1424 if (defined $EditEvent[$i]) {
1425 if ($EditEvent[$i] =~ /^\d+$/) {
1426 $event[$i] = 0+$EditEvent[$i];
1427 } elsif ($EditEvent[$i] =~ /^[-+]\d+$/) {
1428 $event[$i] += 0+$EditEvent[$i];
1429 } elsif ($event[$[] =~ /^(marker|text)/) { # 7.3
1430 $event[$i] = $EditEvent[$i];
1431 }
1432 }
1433 }
1434 $Track[$Ievent] = \@event;
1435 set_before_last_change($Ievent); # 7.5
1436 add_to_history();
1437 }
1438
1439 sub new_file {
1440 $Paused = 1;
1441 if (! $FileIsChanged) { return; }
1442 move($LINES-4,2); clrtobot();
1443 addl($LINES-2,10,
1444 "y = yes, save n = no, don't save");
1445 my $s = "Save $File first (y/n) ? ";
1446 addl($LINES-4,round(0.4*($COLS-length($s))),$s);
1447 timeout(-1);
1448 my $c = getch();
1449 if ($c eq 'y' or $c eq 'w') { score2file($File, 1000,\@Track); }
1450 # move($LINES-4,0); clrtobot();
1451 }
1452
1453 sub quit {
1454 $Paused = 1;
1455 if (! $FileIsChanged) { exit 0; }
1456 move($LINES-4,2); clrtobot();
1457 addl($LINES-2,10,"y = save file, n=just quit, anything else cancels.");
1458 my $s = "Save $File first (y/n) ? ";
1459 addl($LINES-4,round(0.4*($COLS-length($s))),$s);
1460 timeout(-1);
1461 my $c = getch();
1462 if ($c eq 'y' or $c eq 'w') { score2file($File, 1000,\@Track); exit 0;
1463 } elsif ($c eq 'n') { exit 0;
1464 }
1465 display_keystrokes();
1466 }
1467
1468 sub replay_setup { my ($from, $to) = @_;
1469 # The arguments are _times_ in millisec.
1470 # If going forwards, we seek patches and ccs from $from to $to;
1471 # else we seek patches and ccs from $[ to $to.
1472 my $ievent = $[;
1473 if ($to > $from) { # 5.3
1474 while ($ievent < $#Track) { # skip from beginning to $from
1475 if ($Track[$ievent][$[+1] >= $from) { last; }
1476 $ievent = $ievent + 1;
1477 }
1478 }
1479 my %cha2latest_patch = ();
1480 my %cha_cc2latest_val = ();
1481 while ($ievent < $#Track) { # scan to $to, looking for patch and cc
1482 if ($Track[$ievent][$[+1] >= $to) { last; }
1483 if ($Track[$ievent][$[] eq 'patch_change') {
1484 $cha2latest_patch{$Track[$ievent][$[+2]} = $Track[$ievent][$[+3];
1485 } elsif ($Track[$ievent][$[] eq 'control_change') {
1486 $cha_cc2latest_val{"$Track[$ievent][$[+2],$Track[$ievent][$[+3]"}
1487 = $Track[$ievent][$[+4];
1488 }
1489 $ievent = $ievent + 1;
1490 }
1491 # output the latest of each
1492 my ($cha,$pat);
1493 while (($cha,$pat) = each %cha2latest_patch) {
1494 my ($status, $time,$events) = MIDI::ALSA::status();
1495 my @alsaevent = MIDI::ALSA::pgmchangeevent($cha,$pat,$time+0.001);
1496 MIDI::ALSA::output(@alsaevent);
1497 }
1498 # 20121018
1499 while (my ($cha_cc,$val) = each %cha_cc2latest_val) {
1500 my ($cha,$cc) = split /,/, $cha_cc, 2;
1501 my ($status, $time,$events) = MIDI::ALSA::status();
1502 # the bank-change events must come _before_ the patch-change !
1503 # the other controller-events must come after the patch-change ...
1504 if (($cc != 0) and ($cc != 32)) { $time = $time + 0.002; } # 5.4
1505 my @alsaevent = MIDI::ALSA::controllerevent($cha,$cc,$val,$time);
1506 MIDI::ALSA::output(@alsaevent);
1507 }
1508 if (%cha2latest_patch) {
1509 Time::HiRes::usleep(5000); # wait for the synth to load the patches
1510 }
1511 }
1512
1513 sub range {
1514 $Paused = 1;
1515 # the effect (or write-to-file, or global edit, or delete etc)
1516 # there will typically be one set_range then several operations on it
1517 # forget pan (ic), pad (+et)
1518 if ($RangeStart >= $RangeEnd) {
1519 $Message = "sorry, no range is set; try R"; return;
1520 }
1521 move($LINES-4,0); clrtobot();
1522 addl($LINES-4,4,"range is ".range_string()); # 4.6
1523 my $x=19;
1524 addl($LINES-2,$x,'c=compand d=delete f=fade m=mixer p=pitch');
1525 addl($LINES-1,$x,'q=quantise r=repeat t=tempo v=vol w=write_to_file');
1526 addl($LINES-3,4,'apply effect ? '); my $x=19;
1527 my $c = getch(); clrtobot(); echo();
1528 if ($c eq 'c') {
1529 addl($LINES-3,$x,'compand');
1530 addl($LINES-2,4,'compand gradient ? ');
1531 # should display help about the 0.7 3:0.2 per-channel possibility
1532 $n = getnstr(my $params,6);
1533 range_compand(split(' ',$params));
1534 } elsif ($c eq 'd') {
1535 range_delete();
1536 } elsif ($c eq 'p') {
1537 addl($LINES-3,$x,'pitch');
1538 addl($LINES-2,4,'pitch-change (cents) ? ');
1539 $n = getnstr(my $cents,20);
1540 range_pitch(split(' ',$cents));
1541 } elsif ($c eq 'q') {
1542 addl($LINES-3,$x,'quantise');
1543 addl($LINES-2,4,'quantise interval (mS) ? ');
1544 $n = getnstr(my $quan,6);
1545 range_quantise(0+$quan);
1546 } elsif ($c eq 'r') {
1547 addl($LINES-3,$x,'repeat');
1548 addl($LINES-2,4,'how many times altogether ? ');
1549 $n = getnstr(my $times,6);
1550 range_repeat(0+$times);
1551 } elsif ($c eq 't') {
1552 addl($LINES-3,$x,'tempo');
1553 addl($LINES-2,4,'tempo speed-ratio ? ');
1554 $n = getnstr(my $tempo,6);
1555 range_tempo(0+$tempo);
1556 } elsif ($c eq 'v') {
1557 addl($LINES-3,$x,'volume');
1558 addl($LINES-2,4,'volume increment ? ');
1559 $n = getnstr(my $volume,6);
1560 range_volume(split(' ',$volume));
1561 } elsif ($c eq 'w') { # 4.6
1562 my $filename = ask_filename($LINES-3,'write to which filename ? ');
1563 return unless $filename;
1564 if ($filename !~ /\./) { $filename .= '.mid'; }
1565 if (-e $filename) { _warn("$filename exists already"); return; }
1566 range_write($filename);
1567 }
1568 }
1569
1570 sub ask_filename { my ($y, $prompt) = @_; # 6.3
1571 my $filename;
1572 addl($y,0,''); # from 0 to COLS-1, apparently
1573 refresh();
1574 eval 'require Term::ReadLine'; if ($@) {
1575 _warn("you should install Term::ReadLine::Gnu from www.cpan.org");
1576 echo(); getnstr($filename,52); noecho();
1577 } else {
1578 system 'stty echo'; # Rough :-(
1579 $term = new Term::ReadLine 'midiedit'; # ugly underline, but backspace
1580 $filename = $term->readline(" $prompt");
1581 system 'stty -echo'; # must be a better way than this...
1582 print STDERR "\e[A\r\e[0K"; # very ugly, asking for trouble :-(
1583 if ($filename) { $term->addhistory($filename); }
1584 $filename =~ s/ $//; # 6.2 no trailing space after completion
1585 }
1586 return $filename;
1587 }
1588
1589 # 20120616
1590 # in Edit mode, / should go PAUSED and then propose the find dialogue
1591 # after Inserting, the field labels at the top should get updated
1592
1593 sub range_delete { # 4.5 should defend against $RangeEnd == $#Track
1594 set_before_last_change($Ievent); # 7.5
1595 my $delta = $Track[$RangeEnd+1][$[+1] - $Track[$RangeStart][$[+1];
1596 my $n_deleted = $RangeEnd-$RangeStart+1;
1597 splice @Track, $RangeStart, $n_deleted;
1598 $Message = "$n_deleted events deleted";
1599 my $k = $RangeStart;
1600 while ($k <= $#Track) { $Track[$k][$[+1] -= $delta; $k += 1; }
1601 if ($Ievent > $#Track) { $Ievent = $#Track; # 4.7
1602 } elsif ($Ievent > $RangeEnd) { $Ievent -= $n_deleted; # 5.6
1603 } elsif ($Ievent > $RangeStart) { $Ievent = $RangeStart; # 5.6
1604 }
1605 time_travel($Track[$Ievent][$[+1] - $Now); # 5.6
1606 $RangeEnd = $[-1;
1607 add_to_history();
1608 }
1609
1610 sub range_pitch { my @params = @_; # 4.5; borrowed from midisox_pl
1611 set_before_last_change($Ievent); # 7.5
1612 my $h = ', see midisox --help-effect=pitch';
1613 if (! @params) { return; }
1614 my $default_incr;
1615 my %channel_incr = ();
1616 foreach my $param (@params) {
1617 if ($param =~ /^[-+]?\d+$/) {
1618 $default_incr = round($param/100);
1619 } else {
1620 if ($param =~ /^(\d+):([-+]?\d+)$/) {
1621 $channel_incr{0+$1} = round($2/100);
1622 } else {
1623 $Message = "pitch: strange parameter $param$h\n";
1624 }
1625 }
1626 }
1627 if (not $default_incr) {
1628 if (%channel_incr) { $default_incr = 0; } else { return; }
1629 }
1630 my $k = $RangeStart; while ($k <= $RangeEnd) {
1631 if ($Track[$k][$[] eq 'note' and $Track[$k][$[+3] != 9) {
1632 my $incr = $default_incr; # don't shift drumkit
1633 if ($channel_incr{$Track[$k][$[+3]}) {
1634 $incr = $channel_incr{$Track[$k][$[+3]};
1635 }
1636 $Track[$k][4] += $incr;
1637 if ($Track[$k][$[+4] > 127) { $Track[$k][$[+4] = 127;
1638 } elsif ($Track[$k][$[+4] < 0) { $Track[$k][$[+4] = 0;
1639 }
1640 }
1641 $k += 1;
1642 }
1643 set_before_last_change($Ievent); # 7.5
1644 add_to_history();
1645 }
1646
1647 sub range_compand { my @params = @_; # 4.5; borrowed from midisox_pl
1648 set_before_last_change($Ievent); # 7.5
1649 if (@params < 1) { $params[$[] = '0.5' }
1650 my $default_gradient;
1651 my %channel_gradient = ();
1652 my $iparam = $[;
1653 while ($iparam <= $#params) {
1654 my $param = $params[$iparam];
1655 if ($param =~ /^-?\.?\d+$|^-?\d+\.\d*$/) {
1656 $default_gradient = 0 + $param;
1657 } elsif ($param =~ '^(\d+):(-?[.\d]+)$') {
1658 $channel_gradient{0+$1} = 0+$2;
1659 } else {
1660 _warn("compand: strange parameter $param$h"); return;
1661 }
1662 $iparam = $iparam + 1;
1663 }
1664 if (! defined $default_gradient) {
1665 if (%channel_gradient) { # test for empty table
1666 $default_gradient = 1.0;
1667 } else {
1668 $default_gradient = 0.5;
1669 }
1670 }
1671 # warn("channel_gradient=".Dumper(\%channel_gradient));
1672 my $previous_note_time = 0;
1673 my $k = $RangeStart; while ($k <= $RangeEnd) {
1674 my $event_ref = $Track[$k];
1675 if ($$event_ref[$[] eq 'note') {
1676 my $gradient = $default_gradient;
1677 if ($channel_gradient{$$event_ref[$[+3]}) {
1678 $gradient = $channel_gradient{$$event_ref[$[+3]};
1679 }
1680 $$event_ref[$[+5]=100+round($gradient*($$event_ref[$[+5]-100));
1681 if ($$event_ref[$[+5] > 127) {
1682 $$event_ref[$[+5] = 127;
1683 } elsif ($$event_ref[$[+5] < 1) {
1684 $$event_ref[$[+5] = 1; # v=0 sometimes means v=default
1685 }
1686 }
1687 $k += 1;
1688 }
1689 }
1690
1691 sub range_quantise { my $quantum = $_[$[]; # 4.5; borrowed from midisox_pl
1692 set_before_last_change($Ievent); # 7.5
1693 if ($quantum <= 0) {
1694 $Message = "the quantise interval must be positive"; return;
1695 }
1696 my $old_previous_note_time = $Track[$RangeStart][$[+1];
1697 my $new_previous_note_time = $Track[$RangeStart][$[+1];
1698 my $k = $RangeStart+1; while ($k <= $RangeEnd) {
1699 if ($Track[$k][$[] eq 'note') {
1700 my $old_this_note_time = $Track[$k][$[+1];
1701 my $dt = $old_this_note_time - $old_previous_note_time;
1702 my $dn = round($dt/$quantum); # quantum must not be zero
1703 $Track[$k][$[+1] = $new_previous_note_time + $quantum*$dn;
1704 my $new_this_note_time = $Track[$k][$[+1];
1705 # readjust non-note events to lie between the adjusted times
1706 # in the same proportion as they lay between the old times
1707 my $k2 = $k - 1;
1708 while ($k2 >= $[ and $Track[$k2][$[] ne 'note') {
1709 my $old_non_note_time = $Track[$k2][$[+1];
1710 if ($old_this_note_time > $old_previous_note_time) {
1711 $Track[$k2][$[+1] = round($new_previous_note_time +
1712 ($old_non_note_time - $old_previous_note_time) *
1713 ($new_this_note_time - $new_previous_note_time) /
1714 ($old_this_note_time - $old_previous_note_time) );
1715 } else {
1716 $Track[$k2][$[+1] = $new_previous_note_time;
1717 }
1718 $k2 = $k2 - 1;
1719 }
1720 if ($dn > 0) { # 5.8, see midisox* versions 5.4
1721 $old_previous_note_time = $old_this_note_time;
1722 $new_previous_note_time = $new_this_note_time;
1723 }
1724 }
1725 $k += 1;
1726 }
1727 # now timeshift from $RangeEnd to $#Track ...
1728 my $delta = $new_previous_note_time - $old_previous_note_time;
1729 while ($k <= $#Track) { $Track[$k][$[+1] += $delta; $k += 1; }
1730 add_to_history();
1731 }
1732
1733 sub range_repeat { my $times = round($_[$[]);
1734 set_before_last_change($Ievent); # 7.5
1735 if ($times == 0) {
1736 $Message = "to repeat zero times, just use delete"; return;
1737 }
1738 if ($times == 1) {
1739 $Message = "repeat once leaves the file unchanged"; return;
1740 }
1741 my $r_end = $RangeEnd; if ($RangeEnd == $#Track) { $r_end = $RangeEnd-1; }
1742 my $delta = $Track[$r_end+1][$[+1] - $Track[$RangeStart][$[+1];
1743 my $n_in_range = $r_end-$RangeStart+1;
1744 # debug("r_end=$r_end delta=$delta n_in_range=$n_in_range");
1745 my $k = $r_end;
1746 foreach my $time (2 .. $times) {
1747 splice @Track, $k+1, 0, deepcopy(@Track[$RangeStart..$r_end]);
1748 foreach my $i (1 .. $n_in_range) {
1749 $k += 1;
1750 $Track[$k][$[+1] += $delta*($time-1);
1751 }
1752 }
1753 $k += 1;
1754 while ($k <= $#Track) {
1755 $Track[$k][$[+1] += $delta*($times-1);
1756 $k += 1;
1757 }
1758 # 5.7 move cursor, if it lay after RangeEnd (see range_delete 5.6)
1759 if ($Ievent > $RangeEnd) { # 5.7
1760 my $t = ($times-1)*$delta;
1761 # debug("times=$times delta=$delta t=$t");
1762 time_travel(($times-1)*$delta);
1763 }
1764 $Message = sprintf("%d new events", $n_in_range*($times-1));
1765 add_to_history();
1766 }
1767
1768 sub range_tempo { my $tempo = $_[$[]; # 4.5
1769 set_before_last_change($Ievent); # 7.5
1770 if ($tempo == 1.0) { return; }
1771 if ($tempo <= 0) { $tempo = 0.1; } # following midisox_pl usage
1772 my $range_start_time = $Track[$RangeStart][$[+1];
1773 my $old_range_end_time = $Track[$RangeEnd][$[+1];
1774 my $k = $RangeStart+1; while ($k <= $RangeEnd) {
1775 $Track[$k][$[+1] = $range_start_time
1776 + round(($Track[$k][$[+1]-$range_start_time)/$tempo);
1777 if ($Track[$k][$[] eq 'note') { # fix the duration
1778 $Track[$k][$[+2] = round($Track[$k][$[+2]/$tempo);
1779 }
1780 $k += 1;
1781 }
1782 my $new_range_end_time = $Track[$RangeEnd][$[+1];
1783 # now timeshift from $RangeEnd to $#Track ...
1784 my $delta = $new_range_end_time - $old_range_end_time;
1785 while ($k <= $#Track) { $Track[$k][$[+1] += $delta; $k += 1; }
1786 add_to_history();
1787 }
1788
1789 sub range_volume { my @params = @_; # 4.5
1790 set_before_last_change($Ievent); # 7.5
1791 my $h = ', see midisox --help-effect=vol';
1792 if (! @params) { return; }
1793 my $default_incr;
1794 my %channel_incr = ();
1795 foreach my $param (@params) {
1796 if ($param =~ /^[-+]?\d+$/) {
1797 $default_incr = 0 + $param;
1798 } else {
1799 if ($param =~ /^(\d+):([-+]?\d+)$/) {
1800 $channel_incr{0+$1} = 0+$2;
1801 } else {
1802 die "vol: strange parameter $param$h\n";
1803 }
1804 }
1805 }
1806 if (not $default_incr) {
1807 if (%channel_incr) { $default_incr = 0; } else { return; }
1808 }
1809 my $k = $RangeStart; while ($k <= $RangeEnd) {
1810 if ($Track[$k][$[] eq 'note') {
1811 my $incr = $default_incr;
1812 if ($channel_incr{$Track[$k][$[+3]}) {
1813 $incr = $channel_incr{$Track[$k][$[+3]};
1814 }
1815 $Track[$k][5] += $incr;
1816 if ($Track[$k][$[+5] > 127) { $Track[$k][$[+5] = 127;
1817 } elsif ($Track[$k][$[+5] < 0) { $Track[$k][$[+5] = 0;
1818 }
1819 }
1820 $k += 1;
1821 }
1822 add_to_history();
1823 }
1824
1825 sub range_write { my $filename = $_[$[]; # 4.6, 6.1
1826 return unless $filename;
1827 my @range_score = ( 1000, [ ['set_tempo', 1, 1000000], ] );
1828 # 6.1 a score uses absolute times; must subtract first t1 from all events
1829 my $t1 = $Track[$RangeStart][$[+1];
1830 my $k = $RangeStart; while ($k <= $RangeEnd) {
1831 my @event = @{$Track[$k]};
1832 $event[$[+1] -= $t1; # 6.1
1833 push @{$range_score[$[+1]}, \@event;
1834 $k += 1;
1835 }
1836 # 6.2 append a marker to represent the time-to-next-note
1837 # XXX should iterate to find a NOTE !
1838 my $time_next_note = $Track[$RangeEnd+1][$[+1];
1839 if ($time_next_note) {
1840 my $file = $File; # 6.3 give filename it came from, and $t1
1841 if (20 < length $file) { $file =~ s#^.*/([^/]+)$#$1#; }
1842 my $s = "from $file at $t1 mS";
1843 push @{$range_score[$[+1]}, ['marker', $time_next_note-$t1, $s];
1844 }
1845 score2file($filename, @range_score);
1846 _warn("range written to $filename");
1847 }
1848
1849 sub re_do {
1850 set_before_last_change($Ievent); # 7.5
1851 #debug("re_do1: Ihistory=$Ihistory #History=$#History History=@History");
1852 if ($Ihistory > ($#History-3)) {
1853 $Message="Already at newest change"; return;
1854 }
1855 $Ihistory += 1; my $r = $History[$Ihistory];
1856 if (ref $r ne ARRAY) { $Message="ref r was ".ref $r; }
1857 @Track = deepcopy(@$r);
1858 $Ihistory += 1; $Ievent = $History[$Ihistory];
1859 $Ihistory += 1; $Now = $History[$Ihistory];
1860 #debug("re_do2: Ihistory=$Ihistory #History=$#History History=@History");
1861 }
1862
1863 sub row_nums {
1864 my $i_top = 2; # row-number
1865 if (!$TopKeystrokesLine) { display_keystrokes(); }
1866 my $i_bot = $TopKeystrokesLine - 2; # row-number
1867 if ($i_top > ($i_bot-4)) { die "not enough rows on screen\n"; }
1868 my $i_now; # row-number
1869 if ((scalar @Track) <= ($i_bot-$i_top+1)) {
1870 $i_now = $i_top + $Ievent -$[;
1871 } elsif ($Ievent < 0.5*($i_bot-$i_top+1)) {
1872 $i_now = $i_top + $Ievent -$[;
1873 } elsif (($#Track-$Ievent) < 0.5*($i_bot-$i_top+1)) {
1874 $i_now = $i_bot + $Ievent - $#Track;
1875 } else {
1876 $i_now = round(0.5*($i_top+$i_bot));
1877 }
1878 return ($i_top, $i_now, $i_bot);
1879 }
1880
1881 sub set_range { # 4.5
1882 if ($RangeSettingState == 0) {
1883 $RangeStart = $Ievent;
1884 $RangeEnd = $[-1;
1885 $RangeSettingState = 1;
1886 } elsif ($RangeStart == $Ievent) {
1887 $RangeEnd = $[-1;
1888 $Message = "empty range";
1889 $RangeSettingState = 0;
1890 } else {
1891 $RangeEnd = $Ievent;
1892 if ($RangeEnd < $RangeStart) {
1893 my $t=$RangeStart; $RangeStart=$RangeEnd; $RangeEnd=$t;
1894 }
1895 _warn("new range ".range_string());
1896 $RangeSettingState = 0;
1897 }
1898 }
1899
1900 sub range_string {
1901 my $start_ms = $Track[$RangeStart][$[+1];
1902 my $end_ms = $Track[$RangeEnd][$[+1];
1903 return "from $start_ms to $end_ms mS";
1904 }
1905
1906 sub set_timeout_for_next_note {
1907 if ($Ievent < $#Track) { # set the timeout for the one after
1908 my $delay_ms = $Track[$Ievent+1][$[+1] - $Now;
1909 $delay_ms = round($delay_ms / $ReplaySpeed); # 3.1
1910 if ($delay_ms < 1) { $delay_ms = 1; }
1911 timeout($delay_ms);
1912 }
1913 }
1914
1915 sub time_travel { my $dt = $_[$[];
1916 if (! $dt) { return; }
1917 my $then = $Now;
1918 $Now = $Now + $dt;
1919 if ($dt > 0) {
1920 my $found = 0;
1921 while ($Ievent < $#Track) {
1922 if ($Track[$Ievent+1][$[+1] > $Now) { $found = 1; last; }
1923 $Ievent = $Ievent + 1;
1924 }
1925 if (! $found) { $Ievent = $#Track; $Now = $Track[$Ievent][$[+1]; }
1926 replay_setup($then, $Now);
1927 } else {
1928 my $found = 0;
1929 while ($Ievent >= $[) {
1930 if ($Track[$Ievent][$[+1] < $Now) { $found = 1; last; }
1931 $Ievent = $Ievent - 1;
1932 }
1933 if (! $found) { $Ievent = $[; $Now = $Track[$Ievent][$[+1]; }
1934 replay_setup(0, $Now);
1935 }
1936 play_current_event();
1937 if (! $Paused) { set_timeout_for_next_note(); }
1938 }
1939
1940 sub event_travel { my $di = $_[$[]; # 5.2
1941 # 20120930 stripped down from time_travel, for use by UP and DOWN
1942 if (! $di) { return; }
1943 my $then = $Now;
1944 $Ievent = $Ievent + $di;
1945 if ($Ievent > $#Track) { $Ievent = $#Track
1946 } elsif ($Ievent < $[) { $Ievent = $[;
1947 }
1948 $Now = $Track[$Ievent][$[+1];
1949 replay_setup($then, $Now);
1950 play_current_event();
1951 if (! $Paused) { set_timeout_for_next_note(); }
1952 }
1953
1954 sub un_do {
1955 if ($Ihistory < $[+3) { $Message = "Already at oldest change"; return; }
1956 $Ihistory -= 3;
1957 $Now = $History[$Ihistory];
1958 $Ievent = $History[$Ihistory-1]; # 7.5 re-instated
1959 my $r = $History[$Ihistory-2];
1960 @Track = deepcopy(@$r);
1961 }
1962
1963 #------------ MIDI infrastructure from midisox_pl ------------
1964
1965 sub _print { print ($_[$[]."\n"); }
1966 sub _warn { $Message = $_[$[]; } # wiped by display_keystrokes()
1967 sub warning { _warn('warning: '.$_[$[]); }
1968 sub _die { die($_[$[]."\n"); }
1969 sub round { my $x = $_[$[];
1970 if ($x > 0.0) { return int ($x + 0.5); }
1971 if ($x < 0.0) { return int ($x - 0.5); }
1972 return 0;
1973 }
1974 sub deepcopy {
1975 use Storable;
1976 if (1 == @_ and ref($_[$[])) { return Storable::dclone($_[$[]);
1977 } else { my $b_ref = Storable::dclone(\@_); return @$b_ref;
1978 }
1979 }
1980 sub vol_mul {
1981 my $vol = $_[$[] || 100;
1982 my $mul = $_[$[+1] || 1.0;
1983 my $new_vol = round($vol*$mul);
1984 if ($new_vol < 0) { $new_vol = 0 - $new_vol; }
1985 if ($new_vol > 127) { $new_vol = 127;
1986 } elsif ($new_vol < 1) { $new_vol = 1; # some synths see vol=0 as default
1987 }
1988 return $new_vol;
1989 }
1990
1991 #---------------------- Encoding stuff -----------------------
1992
1993 sub opus2file {
1994 my ($filename, @opus) = @_;
1995 my $format = 1;
1996 if (2 == @opus) { $format = 0; }
1997 my $cpan_opus = MIDI::Opus->new(
1998 {'format'=>$format, 'ticks' => 1000, 'tracks' => []});
1999 my @list_of_tracks = ();
2000 my $itrack = $[+1;
2001 while ($itrack <= $#opus) {
2002 push @list_of_tracks,
2003 MIDI::Track->new({ 'type' => 'MTrk', 'events' => $opus[$itrack]});
2004 $itrack += 1;
2005 }
2006 $cpan_opus->tracks(@list_of_tracks);
2007 if ($filename eq '-') {
2008 $cpan_opus->write_to_file( '>-' );
2009 } elsif ($filename eq '-d') {
2010 $PID = fork;
2011 if (! $PID) {
2012 if (!open(P, '| aplaymidi -')) { die "can't run aplaymidi: $!\n"; }
2013 $cpan_opus->write_to_handle( *P{IO}, {} );
2014 close P;
2015 exit 0;
2016 }
2017 } else {
2018 $cpan_opus->write_to_file($filename);
2019 }
2020 }
2021
2022 sub score2opus {
2023 if (2 > @_) { return (1000, []); }
2024 my ($ticks, @tracks) = @_;
2025 my @opus = ($ticks,);
2026 my $itrack = $[;
2027 while ($itrack <= $#tracks) {
2028 my %time2events = ();
2029 foreach my $scoreevent_ref (@{$tracks[$itrack]}) {
2030 my @scoreevent = @{$scoreevent_ref};
2031 if ($scoreevent[0] eq 'note') {
2032 my @note_on_event = ('note_on',$scoreevent[1],
2033 $scoreevent[3],$scoreevent[4],$scoreevent[5]);
2034 my @note_off_event = ('note_off',$scoreevent[1]+$scoreevent[2],
2035 $scoreevent[3],$scoreevent[4],$scoreevent[5]);
2036 if ($time2events{$note_on_event[1]}) {
2037 push @{$time2events{$note_on_event[1]}}, \@note_on_event;
2038 } else {
2039 @{$time2events{$note_on_event[1]}} = (\@note_on_event,);
2040 }
2041 if ($time2events{$note_off_event[1]}) {
2042 push @{$time2events{$note_off_event[1]}}, \@note_off_event;
2043 } else {
2044 @{$time2events{$note_off_event[1]}} = (\@note_off_event,);
2045 }
2046 } elsif ($time2events{$scoreevent[1]}) {
2047 push @{$time2events{$scoreevent[1]}}, \@scoreevent;
2048 } else {
2049 @{$time2events{$scoreevent[1]}} = (\@scoreevent,);
2050 }
2051 }
2052 my @sorted_events = (); # list of event_refs sorted by time
2053 for my $time (sort {$a <=> $b} keys %time2events) {
2054 push @sorted_events, @{$time2events{$time}};
2055 }
2056 my $abs_time = 0;
2057 for my $event_ref (@sorted_events) { # convert abs times => delta times
2058 my $delta_time = ${$event_ref}[1] - $abs_time;
2059 $abs_time = ${$event_ref}[1];
2060 ${$event_ref}[1] = $delta_time;
2061 }
2062 push @opus, \@sorted_events;
2063 $itrack += 1;
2064 }
2065 return (@opus);
2066 }
2067
2068 sub score2file { my ($filename, @score) = @_;
2069 my @opus = score2opus(@score);
2070 return opus2file($filename, @opus);
2071 }
2072
2073 #--------------------------- Decoding stuff ------------------------
2074
2075 sub file2opus {
2076 my $opus_ref;
2077 if ($_[$[] eq '-') {
2078 $opus_ref = MIDI::Opus->new({'from_handle' => *STDIN{IO}});
2079 } elsif ($_[$[] =~ /^[a-z]+:\//) {
2080 eval 'require LWP::Simple'; if ($@) {
2081 _die "you need to install libwww-perl from www.cpan.org";
2082 }
2083 $midi = LWP::Simple::get($_[$[]);
2084 if (! defined $midi) { _die("can't fetch $_[$[]"); }
2085 open(P, '<', \$midi) or _die("can't open FileHandle, need Perl5.8");
2086 $opus_ref = MIDI::Opus->new({'from_handle' => *P{IO}});
2087 close P;
2088 } else {
2089 $opus_ref = MIDI::Opus->new({'from_file' => $_[$[]});
2090 }
2091 # $opus_ref->dump({'dump_tracks'=>1});
2092 my @my_opus = (${$opus_ref}{'ticks'},);
2093 foreach my $track ($opus_ref->tracks) {
2094 push @my_opus, $track->events_r;
2095 }
2096 # print "3:\n", Dumper(\@my_opus);
2097 return @my_opus;
2098 }
2099
2100 sub opus2score { my ($ticks, @opus_tracks) = @_;
2101 # print "opus2score: ticks=$ticks opus_tracks=@opus_tracks\n";
2102 if (!@opus_tracks) {
2103 return (1000,[],);
2104 }
2105 my @score = ($ticks,);
2106 #foreach my $i ($[+1 .. $#_) {
2107 # push @score, MIDI::Score::events_r_to_score_r($score[$i]);
2108 #}
2109 my @tracks = deepcopy(@opus_tracks); # couple of slices probably quicker...
2110 # print "opus2score: tracks is ", Dumper(@tracks);
2111 foreach my $opus_track_ref (@tracks) {
2112 my $ticks_so_far = 0;
2113 my @score_track = ();
2114 my %chapitch2note_on_events = (); # 4.4 XXX!!! Must be by Channel !!
2115 foreach $opus_event_ref (@{$opus_track_ref}) {
2116 my @opus_event = @{$opus_event_ref};
2117 $ticks_so_far += $opus_event[1];
2118 if ($opus_event[0] eq 'note_off'
2119 or ($opus_event[0] eq 'note_on' and $opus_event[4]==0)) { # YY
2120 my $cha = $opus_event[2];
2121 my $pitch = $opus_event[3];
2122 my $key = $cha*128 + $pitch;
2123 if ($chapitch2note_on_events{$key}) {
2124 my $new_event_ref = shift @{$chapitch2note_on_events{$key}};
2125 ${$new_event_ref}[2] = $ticks_so_far - ${$new_event_ref}[1];
2126 push @score_track, $new_event_ref;
2127 } else {
2128 _warn("note_off without a note_on, cha=$cha pitch=$pitch")
2129 }
2130 } elsif ($opus_event[0] eq 'note_on') {
2131 my $cha = $opus_event[2]; # 4.4
2132 my $pitch = $opus_event[3];
2133 my $new_event_ref = ['note', $ticks_so_far, 0,
2134 $cha, $pitch, $opus_event[4]];
2135 my $key = $cha*128 + $pitch;
2136 push @{$chapitch2note_on_events{$key}}, $new_event_ref;
2137 } else {
2138 $opus_event[1] = $ticks_so_far;
2139 push @score_track, \@opus_event;
2140 }
2141 }
2142 # 4.7 check for unterminated notes, see: ~/lua/lib/MIDI.lua
2143 while (my ($k1,$v1) = each %chapitch2note_on_events) {
2144 foreach my $new_e_ref (@{$v1}) {
2145 ${$new_e_ref}[2] = $ticks_so_far - ${$new_e_ref}[1];
2146 push @score_track, $new_e_ref;
2147 warn("opus2score: note_on with no note_off cha="
2148 . ${$new_e_ref}[3] . ' pitch='
2149 . ${$new_e_ref}[4] . "; adding note_off at end\n");
2150 }
2151 }
2152 push @score, \@score_track;
2153 }
2154 return @score;
2155 }
2156
2157 sub file2score {
2158 return opus2score(file2opus($_[$[]));
2159 }
2160
2161 sub file2ms_score {
2162 my @opus = file2opus($_[$[]);
2163 my @ms = to_millisecs(@opus);
2164 my @score = opus2score(@ms);
2165 # must merge the tracks of a format-2 file; could perhaps even
2166 # extend the @event to indicate which Track it originated in...
2167 my $itrack = $#score; while ($itrack > ($[+1.5)) {
2168 foreach my $event_ref (@{$score[$itrack]}) {
2169 push @{$score[$[+1]}, $event_ref; # push them onto track 1
2170 }
2171 $itrack -= 1;
2172 $#score = $itrack; # and jettison the last track
2173 }
2174 return @score;
2175 }
2176
2177 #------------------------ Other Transformations ---------------------
2178
2179 sub to_millisecs { # 20160702 rewrite, following MIDI.lua 6.7
2180 my @old_opus = @_;
2181 if (!@old_opus) { return (1000,[],); }
2182 my $old_tpq = $old_opus[$[];
2183 my @new_opus = (1000,);
2184 # 6.7 first go through building a table of set_tempos by absolute-tick
2185 my %ticks2tempo = ();
2186 $itrack = $[+1;
2187 while ($itrack <= $#old_opus) {
2188 my $ticks_so_far = 0;
2189 foreach my $old_event_ref (@{$old_opus[$itrack]}) {
2190 my @old_event = @{$old_event_ref};
2191 if ($old_event[0] eq 'note') {
2192 _die 'to_millisecs needs an opus, not a score';
2193 }
2194 $ticks_so_far += $old_event[1];
2195 if ($old_event[0] eq 'set_tempo') {
2196 $ticks2tempo{$ticks_so_far} = $old_event[2];
2197 }
2198 }
2199 $itrack += 1;
2200 }
2201 # then get the sorted-array of their keys
2202 my @tempo_ticks = sort { $a <=> $b; } keys %ticks2tempo;
2203 # then go through converting to millisec, testing if the next
2204 # set_tempo lies before the next track-event, and using it if so.
2205 $itrack = $[+1;
2206 while ($itrack <= $#old_opus) {
2207 my $ms_per_old_tick = 1000.0 / $old_tpq; # will round later
2208 my $i_tempo_ticks = 0;
2209 my $ticks_so_far = 0;
2210 my $ms_so_far = 0.0;
2211 my $previous_ms_so_far = 0.0;
2212 my @new_track = (['set_tempo',0,1000000],); # new "crochet" is 1 sec
2213 foreach my $old_event_ref (@{$old_opus[$itrack]}) {
2214 # detect if ticks2tempo has something before this event
2215 # 20160702 if ticks2tempo is at the same time, leave it
2216 my @old_event = @{$old_event_ref};
2217 my $event_delta_ticks = $old_event[1];
2218 if ($i_tempo_ticks <= $#tempo_ticks and
2219 $tempo_ticks[$i_tempo_ticks] < ($ticks_so_far+$old_event[1])) {
2220 my $delta_ticks = $tempo_ticks[$i_tempo_ticks]-$ticks_so_far;
2221 $ms_so_far += ($ms_per_old_tick * $delta_ticks);
2222 $ticks_so_far = $tempo_ticks[$i_tempo_ticks];
2223 $ms_per_old_tick=$ticks2tempo{$ticks_so_far}/(1000*$old_tpq);
2224 $i_tempo_ticks += 1;
2225 $event_delta_ticks -= $delta_ticks;
2226 } # now handle the new event
2227 my @new_event = deepcopy(@old_event); # copy.deepcopy ?
2228 $ms_so_far += ($ms_per_old_tick * $old_event[1]);
2229 $new_event[1] = round($ms_so_far-$previous_ms_so_far);
2230 if ($old_event[0] ne 'set_tempo') { # set_tempos already handled!
2231 $previous_ms_so_far = $ms_so_far;
2232 push @new_track, \@new_event;
2233 }
2234 $ticks_so_far += $event_delta_ticks;
2235 }
2236 push @new_opus, \@new_track;
2237 $itrack += 1;
2238 }
2239 # print "to_millisecs new_opus = ", Dumper(\@new_opus);
2240 return @new_opus;
2241 }
2242
2243 #----------------- non-Curses infrastructure -----------------
2244 sub line2comment { my $line = $_[$[];
2245 if ($line =~ /[a-z]', (\d+), /) { $ticks += $1;
2246 } elsif ($line =~ /MIDI::Track->new/) { $ticks = 0; return q{}; # 7.8
2247 } else { return q{};
2248 }
2249 my $len = length $line;
2250 my $spaces = " ";
2251 if ($len < 37) { $spaces = " " x (38-$len); }
2252 my $event_type; my $remainder;
2253 if ($line =~ /\['([a-z_]+)', (.+)\]/) {
2254 $event_type = $1; $remainder = $2;
2255 }
2256 if ($event_type =~ /^note_/) {
2257 my ($dt,$cha,$note,$vol) = split(/,\s*/, $remainder);
2258 my $str = note2str('',0,0,$cha,$note,$vol);
2259 if ($event_type eq 'note_off' or $vol eq '0') {
2260 return "$spaces# ticks=$ticks cha=$cha $str off";
2261 } else {
2262 return "$spaces# ticks=$ticks cha=$cha $str";
2263 }
2264 } elsif ($event_type eq 'control_change') {
2265 my ($dt,$cha,$cc,$val) = split(/,\s*/, $remainder);
2266 return "$spaces# ticks=$ticks cha=$cha cc$cc=$val";
2267 } elsif ($event_type eq 'patch_change') {
2268 my ($dt,$cha,$patch) = split(/,\s*/, $remainder);
2269 return "$spaces# ticks=$ticks cha=$cha patch=$patch";
2270 } else {
2271 return "$spaces# ticks=$ticks";
2272 }
2273 }
2274
2275
2276 =pod
2277
2278 =head1 NAME
2279
2280 midiedit - Edits a MIDI file
2281
2282 =head1 SYNOPSIS
2283
2284 midiedit filename.mid # uses the new Curses app, with sound
2285 midiedit -o 128:0 filename.mid # uses ALSA port 128:0 as synth
2286 midiedit -d filename.mid # uses your EDITOR on a MIDI::Perl dump
2287 midiedit -v # prints the Version number
2288
2289 =head1 DESCRIPTION
2290
2291 B<Midiedit> is a MIDI-file editor which now (since version 1.3)
2292 has a choice of two user-interface modes.
2293
2294 In the new default mode,
2295 it uses I<Curses> to offer a purpose-designed user-interface
2296 and I<MIDI::ALSA> to play the notes to your synth.
2297
2298 In the older lower-tech mode,
2299 it uses your favourite text-editor to edit the human-readable text-format
2300 provided by I<MIDI::Perl>'s $opus->dump function.
2301
2302 =head1 CURSES MODE
2303
2304 In the Curses mode, which is the default, I<midiedit>
2305 edits a MIDI file with a purpose-designed user-interface
2306 which re-uses some keystrokes inspired by B<vi>:
2307 for example, B<i>=insert B<m>=mark B<k/Up/j/Down>=+-1event
2308 B<u>=undo B<^R>=redo B</>=find B<?>=reversefind B<n>=findnext B<N>=findprevious
2309 B<w>=write B<q>=quit
2310 B<.>=last_edit_again,
2311 plus a few others, e.g.:
2312 B<e>=edit_event, B<D>=delete_event,
2313 B<R>=define_a_range, B<r>=operate_on_that_range,
2314 B<f>=file_operations, B<z>=all_sounds_off, and
2315 B<^H/Backspace>=return_where_you_were_before_the_I<Find>
2316
2317 As in I<mplayer>, the spacebar toggles between Play and Pause,
2318 the Left and Right arrow keys move by 1 second,
2319 the Up and Down arrow keys move by 10 seconds,
2320 and the Home and End keys move to the start and end of the file,
2321 and B<[> and B<]> or B<{> and B<}> change the Replay-speed.
2322
2323 The available keystrokes are displayed in the bottom four lines of the screen.
2324
2325 The events are displayed in B<note>-form, i.e. with a start-time
2326 and a duration. There are no separate note_on and note_off events,
2327 which solves the matching-ons-and-offs problem.
2328 All times are displayed in milliseconds.
2329
2330 The start-times can be displayed
2331 either as incremental times (since the previous event),
2332 or as absolute times (since the beginning).
2333 The B<+> and B<-> keys switch between these modes;
2334 the default mode is incremental.
2335 The behaviour of Edit, Insert and Delete adapts to the display-mode;
2336 for example with incremental times, deleting a note shortens the
2337 whole file by the deleted millisecond increment,
2338 but with absolute times deleting a note just removes that note
2339 and leaves the duration of the whole file unchanged.
2340
2341 Since version 3.0, B</>=find allows search criteria such as
2342 >62 or <25 or >=60 or <=72 or !=9 or >59&<73
2343 which, when combined with B<.>=last_edit_again
2344 make it easier to do things like
2345 "move that high bit of the piano solo into a different channel".
2346
2347 Since version 4.5, a I<Range> can be defined by pressing upper-case B<R>
2348 once at each end of the desired range.
2349 Once defined, the I<Range> can be operated on, using a lower-case B<r>,
2350 in various ways
2351 ( B<c>=compand B<d>=delete B<m>=mixer B<p>=pitch
2352 B<q>=quantise B<r>=repeat B<t>=tempo B<v>=vol B<w>=write_to_file )
2353 largely modelled on the corresponding I<midisox> effects.
2354 For details of what the I<compand> effect does, see:
2355 midisox --help-effect=compand
2356
2357 Since version 7.7, after a I<Find> (B</>, B<?>, B<n> or B<N>),
2358 B<ctrl-H> or B<Backspace> returns you to where you were before the I<Find>.
2359
2360 You can specify your choice of synth
2361 at the command line with a B<-o 128:0> option,
2362 or else with the I<ALSA_OUTPUT_PORTS> environment variable.
2363 The special value B<-o 0> silences the output
2364 (e.g. you might want to edit something while listening to something else).
2365 Since Version 2.4, you may supply a comma-separated list of ports, e.g.
2366 B<-o 20,128:1>
2367
2368 As well as the B<MIDI-Perl> CPAN module,
2369 this mode also uses the B<Curses> module for the user-interface,
2370 and the B<MIDI::ALSA> module to play the file to your synth.
2371
2372 =head1 DUMP MODE
2373
2374 In the older, low-tech B<-d> mode, I<midiedit>
2375 edits a MIDI file in the human-readable text-format
2376 provided by I<MIDI::Perl>'s $opus->dump function.
2377
2378 The text format representing the MIDI is executable Perl source,
2379 so as you edit, you should preserve valid Perl syntax.
2380 If the edited file has syntax errors,
2381 you will be asked if you want to re-edit it,
2382 and if you reply No then the original file will not get over-written.
2383
2384 If you've changed the text, and then decide you want to quit without
2385 overwriting the MIDI file, then you have to deliberately mess up
2386 the Perl syntax (e.g. make sure the brackets are unbalanced).
2387
2388 Assuming you've installed MIDI::Perl, then C<perldoc MIDI::Event>
2389 should document the format in which the various MIDI-events are represented.
2390 They are represented with incremental times (in ticks) and
2391 with separate note_on and note_off events,
2392 so you have to keep track of matching note_ons and note_offs.
2393
2394 =head1 CHANGES
2395
2396 7.8 20160701, -d with multi-track midi-files resets ticks to 0 each track
2397 7.7 20151106, after a Find, ctrl-H or Backspace returns to where you were
2398 7.6 20151105, finding a marker matches on a substring
2399 7.5 20151031, like 7.4, except it also works for multiple un-do's
2400 7.4 20151030, 'u' leaves Ievent as before last edit, not after the previous
2401 7.3 20151008, edit_again now works for markers and text events
2402 7.2 20151003, fix bug which introduced undefined events
2403 7.1 20151002, event2str defends against unprintable chars in text events
2404 7.0 20150513, displays also Metronome Click and Metronome Bell
2405 6.9 20150411, all_sounds_off also turns all notes off
2406 6.8 20150223, display channel_after_touch column-aligned as cha_aftertouch
2407 6.7 20141201, skip refreshes if <10ms to next event
2408 6.6 20141104, removed misleading 'm=mark' help-text
2409 6.5 20140703, controller_change events display controller-names
2410 6.4 20140702, display_events patch_change events display GM patch-names
2411 6.3 20140612, ask_filename does backspace, range_write won't overwrite
2412 6.2 20140611, range_write appends marker to represent time-to-next-note
2413 6.2 20140611, filename-completion gets its trailing space stripped
2414 6.2 20140611, File Include works, corresponding to range_write
2415 6.1 20140610, range_write no longer has big pause at the start
2416 6.0 20130404, display_events remembers the Ped/* state by channel
2417 5.9 20130323, find_marker with null text finds the next marker
2418 5.8 20130321, bug fixed in range_quantise effect
2419 5.7 20130302, range_repeat moves cursor down if it lay after RangeEnd
2420 5.6 20130301, range_delete moves cursor up if it lay after RangeEnd
2421 5.5 20130218, u=undo and ^R=redo seem to work
2422 5.4 20121028, replay_setup outputs bankchange before the patchchange
2423 5.3 20121001, replay_setup (hence time_travel) works for- and backward
2424 5.2 20120930, KEY_UP uses event_travel() to cope with dt=0
2425 5.1 20120930, works with MIDI::ALSA 1.15; PolyOn=127 fixed
2426 5.0 20120916, edit_event uses p=pitch not n=note
2427 4.9 20120910, f=file_menu: f=fork n=new s=save q=quit
2428 4.8 20120908, KEY_UP uses time_travel(), so as to get the right patch
2429 4.7 20120903, display_events clears lines after EOF, range_delete
2430 4.6 20120628, rw = range_write now works
2431 4.5 20120624, R and r range-operations largely work
2432 4.4 20120613, event-fields correctly displayed also in edit-mode
2433 4.3 20120612, consistent redo and undo; find_event uses time_travel
2434 4.2 20120609, can search for long gaps or short gaps
2435 4.1 20120608, becomes Paused at EOF; channel,note in bold if note-on
2436 4.0 20120604, j,k keys also available in Edit Mode
2437 3.9 20120604, '.'=repeat also offered in Edit Mode, if applicable
2438 3.8 20120604, find offers s=short_gap, l=long_gap and t=time (==go_to)
2439 3.7 20120604, '.' repeats also edit of dt if IncrementalTimes
2440 3.6 20120529, tracks shorter than screen-height don't get extended
2441 3.5 20120527, add g = go_to()
2442 3.4 20120525, displays most recent Ped and *
2443 3.3 20120510, displays currently on notes
2444 3.2 20120502, can now insert bank_change (= 2 control_changes)
2445 3.1 20120326, # ] and [ or } and { change the ReplaySpeed
2446 3.0 20120110, find_match gives find >5&<15&!=9 searches
2447 2.9 20120108, '.' repeats last edit (if event-types match)
2448 2.8 20111126, find works if cha=0 or value=0
2449 2.7 20111107, edit_event dialogue updated as changes are made
2450 2.6 20111103, use the new MIDI-ALSA 1.11 to handle portnames
2451 2.5 20111029, column-titles better reflect the event-types
2452 2.4 20111028, OutputPort can be a comma-separated list
2453 2.3 20111027, merges multiple tracks; z=all_sounds_off
2454 2.2 20111027, entering PAUSED mode causes all_sounds_off
2455 2.1 20111027, displays note-string in main window
2456 2.0 20111027, doesn't try to connect if $OutputPort undefined or "0"
2457 1.9 20111022, Phaser Depth and Poly On displayed correctly
2458 1.8 20111021, displays notes with ~ and _ correctly
2459 1.7 20110926, handles non-millisec-tick files correctly
2460 1.6 20110917, display_this_event shows changes as they are made
2461 1.5 20110910, Up/Down in edit-mode play the new note
2462 1.4 20110909, in edit mode, Up and Down don't leave edit-mode
2463 1.3 20110820, the new Curses app is the default
2464 1.2 20110708, displays helpful comments
2465 1.1 20060728, first working version
2466
2467
2468 =head1 AUTHOR
2469
2470 Peter J Billam http://www.pjb.com.au/comp/contact.html
2471
2472 =head1 CREDITS
2473
2474 Based on the I<MIDI::Perl> and I<Curses> and I<MIDI::ALSA> CPAN modules.
2475 The non-Curses mode also uses Peter Billam's I<Term::Clui> CPAN module.
2476
2477 =head1 SEE ALSO
2478
2479 http://search.cpan.org/perldoc?MIDI
2480 http://search.cpan.org/perldoc?Curses
2481 http://search.cpan.org/perldoc?MIDI::ALSA
2482 http://search.cpan.org/perldoc?Term::Clui
2483 http://www.pjb.com.au/muscript
2484 http://www.pjb.com.au/midi
2485
2486 =cut