2 This file is part of LilyPond, the GNU music typesetter.
4 Copyright (C) 2001--2009 Han-Wen Nienhuys <hanwen@xs4all.nl>
5 Jan Nieuwenhuizen <janneke@gnu.org>
8 LilyPond is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 LilyPond is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
26 s = open ("s.midi").read ()
31 returns a MIDI file as the tuple
33 ((format, division), TRACKLIST)
35 each track is an EVENTLIST, where EVENT is
37 (time, (type, ARG1, [ARG2]))
43 /* PyMIDINIT_FUNC isn't defined in Python < 2.3 */
44 #ifndef PyMODINIT_FUNC
45 # if defined(__cplusplus)
46 # define PyMODINIT_FUNC extern "C" void
47 # else /* __cplusplus */
48 # define PyMODINIT_FUNC void
49 # endif /* __cplusplus */
55 #define debug_print(f, args...) fprintf (stderr, "%s:%d: track: %p :" f, __FUNCTION__, __LINE__, *track, ##args)
57 #define debug_print(f, args...)
60 static PyObject *Midi_error;
61 static PyObject *Midi_warning;
64 midi_error (char const *func, char *s)
66 char *dest = (char*) malloc (sizeof (char) * (strlen (func) + strlen (s) + 1));
69 PyErr_SetString (Midi_error, dest);
76 midi_warning (char const *s)
78 PyErr_SetString (Midi_warning, s);
83 typedef struct message {
88 message_t channelVoiceMessages[] = {
91 {0xA0, "POLYPHONIC_KEY_PRESSURE"},
92 {0xB0, "CONTROLLER_CHANGE"},
93 {0xC0, "PROGRAM_CHANGE"},
94 {0xD0, "CHANNEL_KEY_PRESSURE"},
99 message_t channelModeMessages[] = {
100 {0x78, "ALL_SOUND_OFF"},
101 {0x79, "RESET_ALL_CONTROLLERS"},
102 {0x7A, "LOCAL_CONTROL"},
103 {0x7B, "ALL_NOTES_OFF"},
104 {0x7C, "OMNI_MODE_OFF"},
105 {0x7D, "OMNI_MODE_ON"},
106 {0x7E, "MONO_MODE_ON"},
107 {0x7F, "POLY_MODE_ON"},
111 message_t metaEvents[] = {
112 {0x00, "SEQUENCE_NUMBER"},
113 {0x01, "TEXT_EVENT"},
114 {0x02, "COPYRIGHT_NOTICE"},
115 {0x03, "SEQUENCE_TRACK_NAME"},
116 {0x04, "INSTRUMENT_NAME"},
120 {0x20, "MIDI_CHANNEL_PREFIX"},
122 {0x2F, "END_OF_TRACK"},
124 {0x54, "SMTPE_OFFSET"},
125 {0x58, "TIME_SIGNATURE"},
126 {0x59, "KEY_SIGNATURE"},
127 {0x7F, "SEQUENCER_SPECIFIC_META_EVENT"},
128 {0xFF, "META_EVENT"},
133 add_constants (PyObject *dict)
135 message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
137 for ( j =0; p[j]; j++)
138 for ( i = 0; p[j][i].description; i++)
139 PyDict_SetItemString (dict, p[j][i].description, Py_BuildValue ("i", p[j][i].msg));
143 get_number (unsigned char ** str, unsigned char * end_str, int length)
145 /* # MIDI uses big-endian for everything */
150 ((*str) + i < end_str); i++)
151 sum = (sum << 8) + (unsigned char) (*str)[i];
154 debug_print ("%d:\n", sum);
159 get_variable_length_number (unsigned char **str, unsigned char * end_str)
163 while (*str < end_str)
165 unsigned char x = **str;
167 sum = (sum << 7) + (x & 0x7F);
171 debug_print ("%d:\n", sum);
176 read_one_byte (unsigned char **track, unsigned char *end,
179 PyObject *pyev = Py_BuildValue ("(i)", x);
180 debug_print ("%x:%s", x, "event\n");
186 read_two_bytes (unsigned char **track, unsigned char *end,
189 PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
191 debug_print ("%x:%s", x, "event\n");
196 read_three_bytes (unsigned char **track, unsigned char *end,
199 PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
203 debug_print ("%x:%s", x, "event\n");
208 read_string (unsigned char **track, unsigned char *end)
210 unsigned long length = get_variable_length_number (track, end);
211 if (length > end - *track)
212 length = end - *track;
215 return Py_BuildValue ("s#", ((*track) -length), length);
218 typedef PyObject* (*Read_midi_event)
219 (unsigned char **track, unsigned char *end,
224 read_f0_byte (unsigned char **track, unsigned char *end,
228 debug_print ("%x:%s", x, "event\n");
231 unsigned char z = (*track)[0 ];
233 debug_print ("%x:%s", z, "f0-event\n");
235 return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
238 return Py_BuildValue ("(iO)", x, read_string (track, end));
241 Read_midi_event read_midi_event [16] =
249 read_one_byte, // 60 data entry.
250 read_two_bytes, // 70 all notes off
251 read_three_bytes, // 80 note off
252 read_three_bytes, // 90 note on
253 read_three_bytes, // a0 poly aftertouch
254 read_three_bytes, // b0 control
255 read_two_bytes, // c0 prog change
256 read_two_bytes, // d0 ch aftertouch
257 read_three_bytes, // e0 pitchwheel range
263 read_event (unsigned char **track, unsigned char *end, PyObject *time,
264 unsigned char *running_status)
266 int rsb_skip = ((**track & 0x80)) ? 1 :0;
268 unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
270 PyObject * bare_event = 0;
271 debug_print ("%x:%s", x, "event\n");
275 // printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
276 bare_event = (*read_midi_event[x >> 4]) (track, end, x);
278 return Py_BuildValue ("(OO)", time, bare_event);
284 midi_parse_track (unsigned char **track, unsigned char *track_end)
286 unsigned int time = 0;
287 unsigned long track_len, track_size;
288 PyObject *pytrack = 0;
290 debug_print ("%s", "\n");
292 track_size = track_end - *track;
294 debug_print ("%s", "\n");
295 if (memcmp (*track, "MTrk", 4))
296 return midi_error (__FUNCTION__, ": MTrk expected");
300 track_len = get_number (track, *track + 4, 4);
303 debug_print ("track_len: %u\n", track_len);
304 debug_print ("track_size: %u\n", track_size);
305 debug_print ("track begin: %p\n", track);
306 debug_print ("track end: %p\n", track + track_len);
308 if (track_len > track_size)
309 return midi_error (__FUNCTION__, ": track size corrupt");
311 pytrack = PyList_New (0);
313 if (*track + track_len < track_end)
314 track_end = *track + track_len;
317 PyObject *pytime = PyInt_FromLong (0L);
318 unsigned char running_status = 0;
320 while (*track < track_end)
322 long dt = get_variable_length_number(track, track_end);
327 pytime = PyInt_FromLong (time);
329 pyev = read_event (track, track_end, pytime,
332 PyList_Append (pytrack, pyev);
342 pymidi_parse_track (PyObject *self, PyObject *args)
344 unsigned char *track, *track_end;
345 unsigned long track_size;
347 debug_print ("%s", "\n");
348 if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
352 return midi_error (__FUNCTION__, ": negative track size");
354 track_end = track + track_size;
356 return midi_parse_track (&track, track_end);
360 midi_parse (unsigned char **midi,unsigned char *midi_end)
362 PyObject *pymidi = 0;
363 unsigned long header_len;
364 unsigned format, tracks;
368 debug_print ("%s", "\n");
371 header_len = get_number (midi, *midi + 4, 4);
374 return midi_error (__FUNCTION__, ": header too short");
376 format = get_number (midi, *midi + 2, 2);
377 tracks = get_number (midi, *midi + 2, 2);
380 return midi_error (__FUNCTION__, ": too many tracks");
382 division = get_number (midi, *midi + 2, 2) * 4;
386 /* return midi_error (cannot handle non-metrical time"); */
388 *midi += header_len - 6;
390 pymidi = PyList_New (0);
393 for (i = 0; i < tracks; i++)
394 PyList_Append (pymidi, midi_parse_track (midi, midi_end));
396 pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
402 pymidi_parse (PyObject *self, PyObject *args)
404 unsigned char *midi, *midi_end;
405 unsigned long midi_size;
407 debug_print ("%s", "\n");
408 if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
411 if (memcmp (midi, "MThd", 4))
412 return midi_error (__FUNCTION__, ": MThd expected");
416 midi_end = midi + midi_size;
418 return midi_parse (&midi, midi_end);
422 static PyMethodDef MidiMethods[] =
424 {"parse", pymidi_parse, 1},
425 {"parse_track", pymidi_parse_track, 1},
426 {0, 0} /* Sentinel */
433 m = Py_InitModule ("midi", MidiMethods);
434 d = PyModule_GetDict (m);
436 Midi_error = PyString_FromString ("midi.error");
437 PyDict_SetItemString (d, "error", Midi_error);
439 Midi_warning = PyString_FromString ("midi.warning");
440 PyDict_SetItemString (d, "warning", Midi_warning);