2 midi.c -- implement Python midi parser module
4 source file of the GNU LilyPond music typesetter
6 (c) 2001--2006 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 Jan Nieuwenhuizen <janneke@gnu.org>
15 s = open ("s.midi").read ()
20 returns a MIDI file as the tuple
22 (format, division, TRACKLIST)
24 each track is an EVENTLIST, where EVENT is
26 (time, (type, ARG1, [ARG2]))
32 /* PyMIDINIT_FUNC isn't defined in Python < 2.3 */
33 #ifndef PyMODINIT_FUNC
34 # if defined(__cplusplus)
35 # define PyMODINIT_FUNC extern "C" void
36 # else /* __cplusplus */
37 # define PyMODINIT_FUNC void
38 # endif /* __cplusplus */
44 #define debug_print(f, args...) fprintf (stderr, "%s:%d: track: %p :" f, __FUNCTION__, __LINE__, *track, ##args)
46 #define debug_print(f, args...)
49 static PyObject *Midi_error;
50 static PyObject *Midi_warning;
53 midi_error (char const *func, char *s)
55 char *dest = (char*) malloc (sizeof (char) * (strlen (func) + strlen (s) + 1));
58 PyErr_SetString (Midi_error, dest);
65 midi_warning (char const *s)
67 PyErr_SetString (Midi_warning, s);
72 typedef struct message {
77 message_t channelVoiceMessages[] = {
80 0xA0, "POLYPHONIC_KEY_PRESSURE",
81 0xB0, "CONTROLLER_CHANGE",
82 0xC0, "PROGRAM_CHANGE",
83 0xD0, "CHANNEL_KEY_PRESSURE",
88 message_t channelModeMessages[] = {
89 0x78, "ALL_SOUND_OFF",
90 0x79, "RESET_ALL_CONTROLLERS",
91 0x7A, "LOCAL_CONTROL",
92 0x7B, "ALL_NOTES_OFF",
93 0x7C, "OMNI_MODE_OFF",
100 message_t metaEvents[] = {
101 0x00, "SEQUENCE_NUMBER",
103 0x02, "COPYRIGHT_NOTICE",
104 0x03, "SEQUENCE_TRACK_NAME",
105 0x04, "INSTRUMENT_NAME",
109 0x20, "MIDI_CHANNEL_PREFIX",
111 0x2F, "END_OF_TRACK",
113 0x54, "SMTPE_OFFSET",
114 0x58, "TIME_SIGNATURE",
115 0x59, "KEY_SIGNATURE",
116 0x7F, "SEQUENCER_SPECIFIC_META_EVENT",
122 add_constants (PyObject *dict)
124 message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
126 for ( j =0; p[j]; j++)
127 for ( i = 0; p[j][i].description; i++)
128 PyDict_SetItemString (dict, p[j][i].description, Py_BuildValue ("i", p[j][i].msg));
132 get_number (unsigned char ** str, unsigned char * end_str, int length)
134 /* # MIDI uses big-endian for everything */
138 for (; i < length; i++)
139 sum = (sum << 8) + (unsigned char) (*str)[i];
142 debug_print ("%d:\n", sum);
147 get_variable_length_number (unsigned char **str, unsigned char * end_str)
151 while (*str < end_str)
153 unsigned char x = **str;
155 sum = (sum << 7) + (x & 0x7F);
159 debug_print ("%d:\n", sum);
164 read_one_byte (unsigned char **track, unsigned char *end,
167 PyObject *pyev = Py_BuildValue ("(i)", x);
168 debug_print ("%x:%s", x, "event\n");
174 read_two_bytes (unsigned char **track, unsigned char *end,
177 PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
179 debug_print ("%x:%s", x, "event\n");
184 read_three_bytes (unsigned char **track, unsigned char *end,
187 PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
191 debug_print ("%x:%s", x, "event\n");
196 read_string (unsigned char **track, unsigned char *end)
198 unsigned long length = get_variable_length_number (track, end);
199 if (length > end - *track)
200 length = end - *track;
203 return Py_BuildValue ("s#", ((*track) -length), length);
206 typedef PyObject* (*Read_midi_event)
207 (unsigned char **track, unsigned char *end,
212 read_f0_byte (unsigned char **track, unsigned char *end,
216 debug_print ("%x:%s", x, "event\n");
219 unsigned char z = (*track)[0 ];
221 debug_print ("%x:%s", z, "f0-event\n");
223 return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
226 return Py_BuildValue ("(iO)", x, read_string (track, end));
229 Read_midi_event read_midi_event [16] =
237 read_one_byte, // 60 data entry.
238 read_two_bytes, // 70 all notes off
239 read_three_bytes, // 80 note off
240 read_three_bytes, // 90 note on
241 read_three_bytes, // a0 poly aftertouch
242 read_three_bytes, // b0 control
243 read_two_bytes, // c0 prog change
244 read_two_bytes, // d0 ch aftertouch
245 read_three_bytes, // e0 pitchwheel range
251 read_event (unsigned char **track, unsigned char *end, PyObject *time,
252 unsigned char *running_status)
254 int rsb_skip = ((**track & 0x80)) ? 1 :0;
256 unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
258 PyObject * bare_event = 0;
259 debug_print ("%x:%s", x, "event\n");
263 // printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
264 bare_event = (*read_midi_event[x >> 4]) (track, end, x);
266 return Py_BuildValue ("(OO)", time, bare_event);
272 midi_parse_track (unsigned char **track, unsigned char *track_end)
274 unsigned int time = 0;
275 unsigned char running_status;
276 unsigned long track_len, track_size;
277 PyObject *pytrack = 0;
279 debug_print ("%s", "\n");
281 track_size = track_end - *track;
283 debug_print ("%s", "\n");
284 if (memcmp (*track, "MTrk", 4))
285 return midi_error (__FUNCTION__, ": MTrk expected");
289 track_len = get_number (track, *track + 4, 4);
292 debug_print ("track_len: %u\n", track_len);
293 debug_print ("track_size: %u\n", track_size);
294 debug_print ("track begin: %p\n", track);
295 debug_print ("track end: %p\n", track + track_len);
297 if (track_len > track_size)
298 return midi_error (__FUNCTION__, ": track size corrupt");
300 pytrack = PyList_New (0);
302 track_end = *track + track_len;
305 PyObject *pytime = PyInt_FromLong (0L);
306 while (*track < track_end)
308 long dt = get_variable_length_number(track, track_end);
313 pytime = PyInt_FromLong (time);
315 pyev = read_event (track, track_end, pytime,
318 PyList_Append (pytrack, pyev);
328 pymidi_parse_track (PyObject *self, PyObject *args)
330 unsigned char *track, *track_end;
331 unsigned long track_size, track_len;
333 PyObject * sobj = PyTuple_GetItem (args, 0);
335 debug_print ("%s", "\n");
336 if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
340 return midi_error (__FUNCTION__, ": negative track size");
342 track_end = track + track_size;
344 return midi_parse_track (&track, track_end);
348 midi_parse (unsigned char **midi,unsigned char *midi_end)
350 PyObject *pymidi = 0;
351 unsigned long header_len;
352 unsigned format, tracks;
356 debug_print ("%s", "\n");
359 header_len = get_number (midi, *midi + 4, 4);
363 return midi_error (__FUNCTION__, ": header too short");
365 format = get_number (midi, *midi + 2, 2);
366 tracks = get_number (midi, *midi + 2, 2);
369 return midi_error (__FUNCTION__, ": too many tracks");
371 division = get_number (midi, *midi + 2, 2) * 4;
375 /* return midi_error ("can't handle non-metrical time"); */
377 *midi += header_len - 6;
379 pymidi = PyList_New (0);
382 for (i = 0; i < tracks; i++)
383 PyList_Append (pymidi, midi_parse_track (midi, midi_end));
385 pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
391 pymidi_parse (PyObject *self, PyObject *args)
393 unsigned char *midi, *midi_end;
394 unsigned long midi_size, midi_len;
396 PyObject *sobj = PyTuple_GetItem (args, 0);
398 debug_print ("%s", "\n");
399 if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
402 if (memcmp (midi, "MThd", 4))
403 return midi_error (__FUNCTION__, ": MThd expected");
407 midi_end = midi + midi_size;
409 return midi_parse (&midi, midi_end);
413 static PyMethodDef MidiMethods[] =
415 {"parse", pymidi_parse, 1},
416 {"parse_track", pymidi_parse_track, 1},
417 {0, 0} /* Sentinel */
424 m = Py_InitModule ("midi", MidiMethods);
425 d = PyModule_GetDict (m);
427 Midi_error = PyString_FromString ("midi.error");
428 PyDict_SetItemString (d, "error", Midi_error);
430 Midi_warning = PyString_FromString ("midi.warning");
431 PyDict_SetItemString (d, "warning", Midi_warning);