Fix #1092.
[lilypond/mpolesky.git] / scripts / lilymidi.py
blob0801382f55ed67673c87ae2c4aebe53274230267
1 #!@TARGET_PYTHON@
3 # Copyright (C) 2006--2010 Brailcom, o.p.s.
5 # Author: Milan Zamazal <pdm@brailcom.org>
7 # This file is part of LilyPond, the GNU music typesetter.
9 # LilyPond is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
14 # LilyPond is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
22 import optparse
23 import os
24 import sys
26 """
27 @relocate-preamble@
28 """
30 def process_options (args):
31 parser = optparse.OptionParser (version="@TOPLEVEL_VERSION@")
32 parser.add_option ('', '--filter-tracks', metavar='REGEXP', action='store', type='string', dest='regexp',
33 help="display only tracks numbers, of those track names matching REGEXP")
34 parser.add_option ('', '--prefix-tracks', metavar='PREFIX', action='store', type='string', dest='prefix',
35 help="prefix filtered track numbers with PREFIX")
36 parser.add_option ('', '--dump', action='store_true', dest='dump',
37 help="just dump parsed contents of the MIDI file")
38 parser.usage = parser.usage + " FILE"
39 options, args = parser.parse_args (args)
40 if len (args) != 1:
41 parser.print_help ()
42 sys.exit (2)
43 return options, args
45 def read_midi (file):
46 import midi
47 return midi.parse (open (file).read ())
49 def track_info (data):
50 tracks = data[1]
51 def track_name (track):
52 name = ''
53 for time, event in track:
54 if time > 0:
55 break
56 if event[0] == 255 and event[1] == 3:
57 name = event[2]
58 break
59 return name
60 track_info = []
61 for i in range (len (tracks)):
62 track_info.append ((i, track_name (tracks[i])))
63 return track_info
65 def go ():
66 options, args = process_options (sys.argv[1:])
67 midi_file = args[0]
68 midi_data = read_midi (midi_file)
69 info = track_info (midi_data)
70 if options.dump:
71 print midi_data
72 elif options.regexp:
73 import re
74 regexp = re.compile (options.regexp)
75 numbers = [str(n+1) for n, name in info if regexp.search (name)]
76 if numbers:
77 if options.prefix:
78 sys.stdout.write ('%s ' % (options.prefix,))
79 import string
80 sys.stdout.write (string.join (numbers, ','))
81 sys.stdout.write ('\n')
82 else:
83 for n, name in info:
84 sys.stdout.write ('%d %s\n' % (n+1, name,))
86 if __name__ == '__main__':
87 go ()