Debian Codegraph @

examples/apmid

raw
1 #! /usr/bin/perl
2 #########################################################################
3 # This Perl script is Copyright (c) 2011, Peter J Billam #
4 # www.pjb.com.au #
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 # XXX should, by default, display elapsed time while playing,
10 # mplayer displays on STDOUT (if stdout is a tty ?)
11 # A: 249.3 (04:09.2) of 537.0 (08:57.0) 0.4%
12 # perhaps also spacebar, arrows and page-keys;
13 # perhaps also channels, perhaps even the sounding notes ?;
14 # therefore also a -q=quiet or -s=silent option
15 my $Version = '1.2';
16 my $VersionDate = '03nov2011';
17 use open ':locale';
18
19 my $OutputPort = '';
20 while ($ARGV[$[] =~ /^-([a-z])/) {
21 if ($1 eq 'v') { shift;
22 my $n = $0; $n =~ s{^.*/([^/]+)$}{$1};
23 print "$n version $Version $VersionDate\n";
24 exit 0;
25 } elsif ($1 eq 'p' or $1 eq 'o') { shift; $OutputPort = shift;
26 } else {
27 print "usage:\n"; my $synopsis = 0;
28 while (<DATA>) {
29 if (/^=head1 SYNOPSIS/) { $synopsis = 1; next; }
30 if ($synopsis && /^=head1/) { last; }
31 if ($synopsis && /\S/) { s/^\s*/ /; print $_; next; }
32 }
33 exit 0;
34 }
35 }
36 if (!$OutputPort) { $OutputPort = $ENV{'ALSA_OUTPUT_PORTS'}; }
37 if (!$OutputPort) { die "-p not specified and ALSA_OUTPUT_PORTS not set\n"; }
38
39 use Data::Dumper; $Data::Dumper::Indent = 0; $Data::Dumper::Sortkeys = 1;
40 eval 'require MIDI'; if ($@) {
41 die "you'll need to install the MIDI-Perl module from www.cpan.org\n";
42 }
43 eval 'require MIDI::ALSA'; if ($@) {
44 die "you'll need to install the MIDI::ALSA module from www.cpan.org\n";
45 }
46
47 MIDI::ALSA::client("$0 MIDI::ALSA client", 0, 1, 1) or die "client failed";
48 foreach my $cl_po (split /,/, $OutputPort) {
49 if (! MIDI::ALSA::connectto( 1, $cl_po )) {
50 die "can't connect to ALSA client $cl_po\n";
51 }
52 }
53 MIDI::ALSA::start() or die "start failed";
54
55 my @score = file2ms_score($ARGV[$[]);
56 # look for FF 09 events {'raw_meta_event', dtime, command(0-255), raw}
57 # actually they appear as {'text_event_09', dtime, text}
58 # and connect to their synths, in case they weren't specified in $OutputPort
59 foreach my $is ($[+1..$#score) {
60 foreach my $ev_ref (@{$score[$is]}) {
61 my @event = @{$ev_ref};
62 if ($event[$[] eq 'text_event_09') {
63 my $text = $event[$[+2];
64 my ($cl,$po) = MIDI::ALSA::parse_address($text);
65 if (! $cl) {
66 warn "FF 09 event: can't find client $text\n";
67 } else {
68 # cheap handling of pre-existing connection
69 if (MIDI::ALSA::connectto(1,$cl,$po)) {
70 warn "FF 09 event: connecting to $text\n";
71 }
72 }
73
74 }
75 }
76 }
77 foreach my $is ($[+1..$#score) {
78 my @cl_po = (); # each track starts with this empty
79 foreach my $ev_ref (@{$score[$is]}) {
80 my @event = @{$ev_ref};
81 # detect FF 09 events and set alsa-destination-port accordingly
82 if ($event[$[] eq 'text_event_09') {
83 my $text = $event[$[+2];
84 @cl_po = MIDI::ALSA::parse_address($text);
85 # warn "text=$text cl_po=@cl_po\n";
86 next;
87 }
88 my @alsaevent = MIDI::ALSA::scoreevent2alsa(@event);
89 if (@cl_po) { $alsaevent[$[+6] = \@cl_po; }
90 # Doesn't seem to work, although I think this is what aplaymidi does.
91 # @cl_po is 128:0 but the doc reads more like every separate synth needs
92 # a separate $id:$portnum connecting to it, and $alsaevent[$[+6] should be
93 # set to the local end $id:$portnum, rather than the remote end 128:0
94 if (@alsaevent) { MIDI::ALSA::output(@alsaevent); }
95 }
96 }
97 MIDI::ALSA::syncoutput() or die "syncoutput failed";
98
99 #-------------------- Decoding stuff from midisox_pl -------------------
100
101 sub file2opus {
102 my $opus_ref;
103 if ($_[$[] eq '-') {
104 $opus_ref = MIDI::Opus->new({'from_handle' => *STDIN{IO}});
105 } elsif ($_[$[] =~ /^[a-z]+:\//) {
106 eval 'require LWP::Simple'; if ($@) {
107 die "you'll need to install libwww-perl from www.cpan.org\n";
108 }
109 $midi = LWP::Simple::get($_[$[]);
110 if (! defined $midi) { die "can't fetch $_[$[]\n"; }
111 open(P, '<', \$midi) or die "can't open FileHandle, need Perl5.8\n";
112 $opus_ref = MIDI::Opus->new({'from_handle' => *P{IO}});
113 close P;
114 } else {
115 $opus_ref = MIDI::Opus->new({'from_file' => $_[$[]});
116 }
117 # $opus_ref->dump({'dump_tracks'=>1});
118 my @my_opus = (${$opus_ref}{'ticks'},);
119 foreach my $track ($opus_ref->tracks) {
120 push @my_opus, $track->events_r;
121 }
122 # print "3:\n", Dumper(\@my_opus);
123 return @my_opus;
124 }
125
126 sub opus2score { my ($ticks, @opus_tracks) = @_;
127 # print "opus2score: ticks=$ticks opus_tracks=@opus_tracks\n";
128 if (!@opus_tracks) {
129 return (1000,[],);
130 }
131 my @score = ($ticks,);
132 my @tracks = deepcopy(@opus_tracks); # couple of slices probably quicker...
133 # print "opus2score: tracks is ", Dumper(@tracks);
134 foreach my $opus_track_ref (@tracks) {
135 my $ticks_so_far = 0;
136 my @score_track = ();
137 my %chapitch2note_on_events = (); # 4.4 XXX!!! Must be by Channel !!
138 foreach $opus_event_ref (@{$opus_track_ref}) {
139 my @opus_event = @{$opus_event_ref};
140 $ticks_so_far += $opus_event[1];
141 if ($opus_event[0] eq 'note_off'
142 or ($opus_event[0] eq 'note_on' and $opus_event[4]==0)) { # YY
143 my $cha = $opus_event[2];
144 my $pitch = $opus_event[3];
145 my $key = $cha*128 + $pitch;
146 if ($chapitch2note_on_events{$key}) {
147 my $new_event_ref = shift @{$chapitch2note_on_events{$key}};
148 ${$new_event_ref}[2] = $ticks_so_far - ${$new_event_ref}[1];
149 push @score_track, $new_event_ref;
150 } else {
151 warn("note_off without a note_on, cha=$cha pitch=$pitch")
152 }
153 } elsif ($opus_event[0] eq 'note_on') {
154 my $cha = $opus_event[2]; # 4.4
155 my $pitch = $opus_event[3];
156 my $new_event_ref = ['note', $ticks_so_far, 0,
157 $cha, $pitch, $opus_event[4]];
158 my $key = $cha*128 + $pitch;
159 push @{$chapitch2note_on_events{$key}}, $new_event_ref;
160 } else {
161 $opus_event[1] = $ticks_so_far;
162 push @score_track, \@opus_event;
163 }
164 }
165 # check for unterminated notes, see: ~/lua/lib/MIDI.lua
166 while (my ($k1,$v1) = each %chapitch2note_on_events) {
167 foreach my $new_e_ref (@{$v1}) {
168 ${$new_e_ref}[2] = $ticks_so_far - ${$new_e_ref}[1];
169 push @score_track, $new_e_ref;
170 warn("opus2score: note_on with no note_off cha="
171 . ${$new_e_ref}[3] . ' pitch='
172 . ${$new_e_ref}[4] . "; adding note_off at end\n");
173 }
174 }
175 push @score, \@score_track;
176 }
177
178 return @score;
179 }
180
181 sub file2score {
182 return opus2score(file2opus(midi));
183 }
184
185 sub file2ms_score {
186 #print "file2ms_score(@_)\n";
187 # return opus2score(to_millisecs(file2opus($_[$[])));
188 my @opus = file2opus($_[$[]);
189 my @ms = to_millisecs(@opus);
190 my @score = opus2score(@ms);
191 return @score;
192 }
193
194 #------------------------ Other Transformations ---------------------
195
196 sub to_millisecs {
197 my @old_opus = @_;
198 if (!@old_opus) {
199 return (1000,[],);
200 }
201 my $old_tpq = $_[$[];
202 my @new_opus = (1000,);
203 my $millisec_per_old_tick = 1000.0 / $old_tpq; # float: will round later
204 $itrack = $[+1;
205 while ($itrack <= $#old_opus) {
206 my $millisec_so_far = 0.0;
207 my $previous_millisec_so_far = 0.0;
208 my @new_track = (['set_tempo',0,1000000],); # new "crochet" is 1 sec
209 foreach my $old_event_ref (@{$old_opus[$itrack]}) {
210 my @old_event = @{$old_event_ref};
211 # print "to_millisecs: old_event = @old_event\n";
212 if ($old_event[0] eq 'note') {
213 die "to_millisecs needs an opus, not a score\n";
214 }
215 my @new_event = deepcopy(@old_event); # copy.deepcopy ?
216 $millisec_so_far += ($millisec_per_old_tick * $old_event[1]);
217 $new_event[1] = round($millisec_so_far-$previous_millisec_so_far);
218 if ($old_event[0] eq 'set_tempo') {
219 $millisec_per_old_tick = $old_event[2] / (1000.0 * $old_tpq);
220 } else {
221 $previous_millisec_so_far = $millisec_so_far;
222 push @new_track, \@new_event;
223 }
224 }
225 push @new_opus, \@new_track;
226 $itrack += 1;
227 }
228 # print "to_millisecs new_opus = ", Dumper(\@new_opus);
229 return @new_opus;
230 }
231
232 sub round { my $x = $_[$[];
233 if ($x > 0.0) { return int ($x + 0.5); }
234 if ($x < 0.0) { return int ($x - 0.5); }
235 return 0;
236 }
237
238 sub deepcopy {
239 use Storable;
240 if (1 == @_ and ref($_[$[])) {
241 return Storable::dclone($_[$[]);
242 } else {
243 my $b_ref = Storable::dclone(\@_);
244 return @$b_ref;
245 }
246 }
247
248 __END__
249
250 =pod
251
252 =head1 NAME
253
254 apmid - rough aplaymidi work-alike, to demonstrate MIDI::ALSA
255
256 =head1 SYNOPSIS
257
258 apmid -p 20:0,128 filename.mid
259
260 =head1 DESCRIPTION
261
262 This script is a rough aplaymidi work-alike, to demonstrate MIDI::ALSA
263
264 =head1 OPTIONS
265
266 =over 3
267
268 =item I<-p 20:0,128:0>
269
270 Plays to the ALSA clients 20 and 128;
271 the default is the envronment variable ALSA_OUTPUT_PORTS
272
273 =item I<-v>
274
275 Prints version number.
276
277 =back
278
279 =head1 CHANGES
280
281 20111103 1.2 use the new MIDI-ALSA 1.11 to handle portnames
282 20111031 1.1 connects from multiple (comma-separated) ports
283 20110310 1.0 first working version
284
285 =head1 AUTHOR
286
287 Peter J Billam http://www.pjb.com.au/comp/contact.html
288
289 =head1 CREDITS
290
291 Based on
292
293 =head1 SEE ALSO
294
295 http://www.pjb.com.au/
296 perl(1).
297
298 =cut
299