]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilymidi.py
lilymidi: Add --pretty switch to lilymidi.py to display midi data in human-readable...
[lilypond.git] / scripts / lilymidi.py
1 #!@TARGET_PYTHON@
2
3 # Copyright (C) 2006--2011 Brailcom, o.p.s.
4 #
5 # Author: Milan Zamazal <pdm@brailcom.org>
6 #
7 # This file is part of LilyPond, the GNU music typesetter.
8 #
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.
13 #
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.
18 #
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/>.
21
22 import optparse
23 import os
24 import sys
25
26 """
27 @relocate-preamble@
28 """
29
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.add_option ('', '--pretty', action='store_true', dest='pretty',
39                        help="dump parsed contents of the MIDI file in human-readable form (implies --dump)")
40     parser.usage = parser.usage + " FILE"
41     options, args = parser.parse_args (args)
42     if len (args) != 1:
43         parser.print_help ()
44         sys.exit (2)
45     return options, args
46
47 def read_midi (file):
48     import midi
49     return midi.parse (open (file).read ())
50
51 def track_info (data):
52     tracks = data[1]
53     def track_name (track):
54         name = ''
55         for time, event in track:
56             if time > 0:
57                 break
58             if event[0] == 255 and event[1] == 3:
59                 name = event[2]
60                 break
61         return name
62     track_info = []
63     for i in range (len (tracks)):
64         track_info.append ((i, track_name (tracks[i])))
65     return track_info
66
67
68 class formatter:
69    def __init__ (self, txt = ""):
70      self.text = txt
71    def format_vals (self, val1, val2 = ""):
72      return str (val1) + str(val2)
73    def format (self, val1, val2 = ""):
74      return self.text + self.format_vals (val1, val2)
75 class none_formatter (formatter):
76    def format_vals (self, val1, val2 = ""):
77      return ''
78 class meta_formatter (formatter):
79    def format_vals (self, val1, val2):
80      return str (val2);
81 class tempo_formatter (formatter):
82    def format_vals (self, val1, val2):
83      return str (val2) + " msec/quarter"
84
85 class time_signature_formatter (formatter):
86    def format_vals (self, val1, val2 = ""):
87      return str (val2)   # TODO
88 class key_signature_formatter (formatter):
89    def format_vals (self, val1, val2):
90      return str (val2)   # TODO
91 class channel_formatter (formatter):
92    def __init__ (self, txt, ch):
93      formatter.__init__ (self, txt)
94      self.channel = ch
95    def format (self, val1, val2 = ""):
96      return self.text + "Channel " + str (self.channel) + ", " + \
97             self.format_vals (val1, val2)
98 class control_mode_formatter (formatter):
99    def __init__ (self, txt, ch):
100      formatter.__init__ (self, txt)
101      self.mode = ch
102    def format (self, val1, val2 = ""):
103      return self.text + str (self.mode) + ", " + \
104             self.format_vals (val1, val2)
105 class note_formatter (channel_formatter):
106    def pitch (self, val):
107      pitch_names = ['C', 'Cis', 'D', 'Dis', 'E', 'F', 'Fis', 'G', 'Gis', 'A', 'Ais', 'B'];
108      p = val % 12;
109      oct = val / 12 -1;
110      return pitch_names[p] + str(oct) + "(" + str(val) + ")"
111    def velocity (self, val):
112      #01   #10   #20   #30   #40   #50   #60   #70   #7F
113      pass;
114    def format_vals (self, val1, val2):
115      return self.pitch (val1)
116
117
118 meta_dict = {0x00: meta_formatter ("Seq.Nr.:    "),
119              0x01: meta_formatter ("Text:       "),
120              0x02: meta_formatter ("Copyright:  "),
121              0x03: meta_formatter ("Track name: "),
122              0x04: meta_formatter ("Instrument: "),
123              0x05: meta_formatter ("Lyric:      "),
124              0x06: meta_formatter ("Marker:     "),
125              0x07: meta_formatter ("Cue point:  "),
126              0x2F: none_formatter ("End of Track"),
127              0x51: tempo_formatter ("Tempo:      "),
128              0x54: meta_formatter ("SMPTE Offs.:"),
129              0x58: time_signature_formatter ("Time signature: "),
130              0x59: key_signature_formatter ("Key signature: ")
131 }
132
133 def dump_event (ev, time, padding):
134     ch = ev[0] & 0x0F;
135     func = ev[0] & 0xF0;
136     f = None
137     if (ev[0] == 0xFF):
138         f = meta_dict.get (ev[1], formatter ())
139     if (func == 0x80):
140         f = note_formatter ("Note off: ", ch)
141     elif (func == 0x90):
142         if (ev[2] == 0):
143           desc = "Note off: "
144         else:
145           desc = "Note on: "
146         f = note_formatter (desc, ch)
147     elif (func == 0xA0):
148         f = note_formatter ("Polyphonic aftertouch: ", ch, "Aftertouch pressure: ")
149     elif (func == 0xB0):
150         f = control_mode_formatter ("Control mode change: ", ch)
151     elif (func == 0xC0):
152         f = channel_formatter ("Program Change: ", ch)
153     elif (func == 0xD0):
154         f = channel_formatter ("Channel aftertouch: ", ch)
155     elif (ev[0] in [0xF0, 0xF7]):
156         f = meta_formatter ("System-exclusive event: ")
157
158     if f:
159       if len (ev) > 2:
160         print padding + f.format (ev[1], ev[2])
161       elif len (ev) > 1:
162         print padding + f.format (ev[1])
163       else:
164         print padding + f.format ()
165     else:
166       print padding + "Unrecognized MIDI event: " + str (ev);
167
168 def dump_midi (data, midi_file, options):
169     if not options.pretty:
170         print data
171         return
172     # First, dump general info, #tracks, etc.
173     print "Filename:     " + midi_file;
174     i = data[0];
175     m_formats = {0: 'single multi-channel track',
176                  1: "one or more simultaneous tracks",
177                  2: "one or more sequentially independent single-track patterns"}
178     print "MIDI format:  " + str (i[0]) + " (" + m_formats.get (i[0], "") + ")";
179     print "Divisions:    " + str (i[1]) + " per whole note";
180     print "#Tracks:      " + str ( len (data[1]))
181     n = 0;
182     for tr in data[1]:
183       time = 0;
184       n += 1;
185       print
186       print "Track " + str(n) + ":"
187       print "    Time 0:"
188       for ev in tr:
189         if ev[0]>time:
190            time = ev[0]
191            print "    Time " + str(time) + ": "
192         dump_event (ev[1], time, "        ");
193
194
195
196 def go ():
197     options, args = process_options (sys.argv[1:])
198     midi_file = args[0]
199     midi_data = read_midi (midi_file)
200     info = track_info (midi_data)
201     if (options.dump or options.pretty):
202         dump_midi (midi_data, midi_file, options);
203     elif options.regexp:
204         import re
205         regexp = re.compile (options.regexp)
206         numbers = [str(n+1) for n, name in info if regexp.search (name)]
207         if numbers:
208             if options.prefix:
209                 sys.stdout.write ('%s ' % (options.prefix,))
210             import string
211             sys.stdout.write (string.join (numbers, ','))
212             sys.stdout.write ('\n')
213     else:
214         for n, name in info:
215             sys.stdout.write ('%d %s\n' % (n+1, name,))
216
217 if __name__ == '__main__':
218     go ()