2 This file is part of LilyPond, the GNU music typesetter.
4 Copyright (C) 2001--2011 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]))
46 static char buffer[9];
47 snprintf (buffer, 8, "%d", i);
51 /* PyMIDINIT_FUNC isn't defined in Python < 2.3 */
52 #ifndef PyMODINIT_FUNC
53 # if defined(__cplusplus)
54 # define PyMODINIT_FUNC extern "C" void
55 # else /* __cplusplus */
56 # define PyMODINIT_FUNC void
57 # endif /* __cplusplus */
63 #define debug_print(f, args...) fprintf (stderr, "%s:%d: track: %p :" f, __FUNCTION__, __LINE__, *track, ##args)
65 #define debug_print(f, args...)
68 static PyObject *Midi_error;
69 static PyObject *Midi_warning;
72 midi_error (char const *func, char *s, char *t)
74 char *dest = (char*) malloc (sizeof (char)
75 * (strlen (func) + strlen (s) + strlen (t) + 1));
79 PyErr_SetString (Midi_error, dest);
86 midi_warning (char const *s)
88 PyErr_SetString (Midi_warning, s);
93 typedef struct message {
98 message_t channelVoiceMessages[] = {
101 {0xA0, "POLYPHONIC_KEY_PRESSURE"},
102 {0xB0, "CONTROLLER_CHANGE"},
103 {0xC0, "PROGRAM_CHANGE"},
104 {0xD0, "CHANNEL_KEY_PRESSURE"},
105 {0xE0, "PITCH_BEND"},
109 message_t channelModeMessages[] = {
110 {0x78, "ALL_SOUND_OFF"},
111 {0x79, "RESET_ALL_CONTROLLERS"},
112 {0x7A, "LOCAL_CONTROL"},
113 {0x7B, "ALL_NOTES_OFF"},
114 {0x7C, "OMNI_MODE_OFF"},
115 {0x7D, "OMNI_MODE_ON"},
116 {0x7E, "MONO_MODE_ON"},
117 {0x7F, "POLY_MODE_ON"},
121 message_t metaEvents[] = {
122 {0x00, "SEQUENCE_NUMBER"},
123 {0x01, "TEXT_EVENT"},
124 {0x02, "COPYRIGHT_NOTICE"},
125 {0x03, "SEQUENCE_TRACK_NAME"},
126 {0x04, "INSTRUMENT_NAME"},
130 {0x20, "MIDI_CHANNEL_PREFIX"},
132 {0x2F, "END_OF_TRACK"},
134 {0x54, "SMTPE_OFFSET"},
135 {0x58, "TIME_SIGNATURE"},
136 {0x59, "KEY_SIGNATURE"},
137 {0x7F, "SEQUENCER_SPECIFIC_META_EVENT"},
138 {0xFF, "META_EVENT"},
143 add_constants (PyObject *dict)
145 message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
147 for ( j =0; p[j]; j++)
148 for ( i = 0; p[j][i].description; i++)
149 PyDict_SetItemString (dict, p[j][i].description, Py_BuildValue ("i", p[j][i].msg));
153 get_number (unsigned char ** str, unsigned char * end_str, int length)
155 /* # MIDI uses big-endian for everything */
160 ((*str) + i < end_str); i++)
161 sum = (sum << 8) + (unsigned char) (*str)[i];
164 debug_print ("%d:\n", sum);
169 get_variable_length_number (unsigned char **str, unsigned char * end_str)
173 while (*str < end_str)
175 unsigned char x = **str;
177 sum = (sum << 7) + (x & 0x7F);
181 debug_print ("%d:\n", sum);
186 read_one_byte (unsigned char **track, unsigned char *end,
189 PyObject *pyev = Py_BuildValue ("(i)", x);
190 debug_print ("%x:%s", x, "event\n");
196 read_two_bytes (unsigned char **track, unsigned char *end,
199 PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
201 debug_print ("%x:%s", x, "event\n");
206 read_three_bytes (unsigned char **track, unsigned char *end,
209 PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
213 debug_print ("%x:%s", x, "event\n");
218 read_string (unsigned char **track, unsigned char *end)
220 unsigned long length = get_variable_length_number (track, end);
221 if (length > end - *track)
222 length = end - *track;
225 return Py_BuildValue ("s#", ((*track) -length), length);
228 typedef PyObject* (*Read_midi_event)
229 (unsigned char **track, unsigned char *end,
234 read_f0_byte (unsigned char **track, unsigned char *end,
238 debug_print ("%x:%s", x, "event\n");
241 unsigned char z = (*track)[0 ];
243 debug_print ("%x:%s", z, "f0-event\n");
245 return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
248 return Py_BuildValue ("(iO)", x, read_string (track, end));
251 Read_midi_event read_midi_event [16] =
259 read_one_byte, // 60 data entry.
260 read_two_bytes, // 70 all notes off
261 read_three_bytes, // 80 note off
262 read_three_bytes, // 90 note on
263 read_three_bytes, // a0 poly aftertouch
264 read_three_bytes, // b0 control
265 read_two_bytes, // c0 prog change
266 read_two_bytes, // d0 ch aftertouch
267 read_three_bytes, // e0 pitchwheel range
273 read_event (unsigned char **track, unsigned char *end, PyObject *time,
274 unsigned char *running_status)
276 int rsb_skip = ((**track & 0x80)) ? 1 :0;
278 unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
280 PyObject * bare_event = 0;
281 debug_print ("%x:%s", x, "event\n");
285 // printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
286 bare_event = (*read_midi_event[x >> 4]) (track, end, x);
288 return Py_BuildValue ("(OO)", time, bare_event);
294 midi_parse_track (unsigned char **track, unsigned char *track_end)
296 unsigned int time = 0;
297 unsigned long track_len, track_size;
298 PyObject *pytrack = 0;
300 debug_print ("%s", "\n");
302 track_size = track_end - *track;
304 debug_print ("%s", "\n");
305 if (memcmp (*track, "MTrk", 4))
308 return midi_error (__FUNCTION__, ": MTrk expected, got: ", *(char**)track);
313 track_len = get_number (track, *track + 4, 4);
315 debug_print ("track_len: %u\n", track_len);
316 debug_print ("track_size: %u\n", track_size);
317 debug_print ("track begin: %p\n", track);
318 debug_print ("track end: %p\n", track + track_len);
320 if (track_len > track_size)
321 return midi_error (__FUNCTION__, ": track length corrupt: ", compat_itoa (track_len));
323 pytrack = PyList_New (0);
325 if (*track + track_len < track_end)
326 track_end = *track + track_len;
329 PyObject *pytime = PyInt_FromLong (0L);
330 unsigned char running_status = 0;
332 while (*track < track_end)
334 long dt = get_variable_length_number(track, track_end);
339 pytime = PyInt_FromLong (time);
341 pyev = read_event (track, track_end, pytime,
344 PyList_Append (pytrack, pyev);
354 pymidi_parse_track (PyObject *self, PyObject *args)
356 unsigned char *track, *track_end;
357 unsigned long track_size;
359 debug_print ("%s", "\n");
360 if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
364 return midi_error (__FUNCTION__, ": negative track size: ", compat_itoa (track_size));
366 track_end = track + track_size;
368 return midi_parse_track (&track, track_end);
372 midi_parse (unsigned char **midi,unsigned char *midi_end)
374 PyObject *pymidi = 0;
375 unsigned long header_len;
376 unsigned format, tracks;
380 debug_print ("%s", "\n");
383 header_len = get_number (midi, *midi + 4, 4);
386 return midi_error (__FUNCTION__, ": header too short: ", compat_itoa (header_len));
388 format = get_number (midi, *midi + 2, 2);
389 tracks = get_number (midi, *midi + 2, 2);
392 return midi_error (__FUNCTION__, ": too many tracks: ", compat_itoa (tracks));
394 division = get_number (midi, *midi + 2, 2) * 4;
398 /* return midi_error (cannot handle non-metrical time"); */
400 *midi += header_len - 6;
402 pymidi = PyList_New (0);
405 for (i = 0; i < tracks; i++)
406 PyList_Append (pymidi, midi_parse_track (midi, midi_end));
408 pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
414 pymidi_parse (PyObject *self, PyObject *args)
416 unsigned char *midi, *midi_end;
417 unsigned long midi_size;
419 debug_print ("%s", "\n");
420 if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
423 if (memcmp (midi, "MThd", 4))
426 return midi_error (__FUNCTION__, ": MThd expected, got: ", (char*)midi);
431 midi_end = midi + midi_size;
433 return midi_parse (&midi, midi_end);
437 static PyMethodDef MidiMethods[] =
439 {"parse", pymidi_parse, 1},
440 {"parse_track", pymidi_parse_track, 1},
441 {0, 0} /* Sentinel */
448 m = Py_InitModule ("midi", MidiMethods);
449 d = PyModule_GetDict (m);
451 Midi_error = PyString_FromString ("midi.error");
452 PyDict_SetItemString (d, "error", Midi_error);
454 Midi_warning = PyString_FromString ("midi.warning");
455 PyDict_SetItemString (d, "warning", Midi_warning);