2 midi.c -- implement Python midi parser module
4 source file of the GNU LilyPond music typesetter
6 (c) 2001 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 Jan Nieuwenhuizen <janneke@gnu.org>
15 s = open ("s.midi").read ()
24 #if HAVE_PYTHON2_PYTHON_H
25 #include <python2/Python.h>
26 #elif HAVE_PYTHON2_1_PYTHON_H
27 #include <python2.1/Python.h>
28 #elif HAVE_PYTHON2_0_PYTHON_H
29 #include <python2.0/Python.h>
30 #elif HAVE_PYTHON1_5_PYTHON_H
31 #include <python1.5/Python.h>
32 #elif HAVE_PYTHON_PYTHON_H
34 #include <python/Python.h>
45 #define debug_print(f, args...) fprintf (stderr, "%s:%d: track: %p :" f, __FUNCTION__, __LINE__, *track, ##args)
47 #define debug_print(f, args...)
50 static PyObject *Midi_error;
51 static PyObject *Midi_warning;
56 PyErr_SetString (Midi_error, s);
61 midi_warning (char *s)
63 PyErr_SetString (Midi_warning, s);
68 typedef struct message {
73 message_t channelVoiceMessages[] = {
76 0xA0, "POLYPHONIC_KEY_PRESSURE",
77 0xB0, "CONTROLLER_CHANGE",
78 0xC0, "PROGRAM_CHANGE",
79 0xD0, "CHANNEL_KEY_PRESSURE",
84 message_t channelModeMessages[] = {
85 0x78, "ALL_SOUND_OFF",
86 0x79, "RESET_ALL_CONTROLLERS",
87 0x7A, "LOCAL_CONTROL",
88 0x7B, "ALL_NOTES_OFF",
89 0x7C, "OMNI_MODE_OFF",
96 message_t metaEvents[] = {
97 0x00, "SEQUENCE_NUMBER",
99 0x02, "COPYRIGHT_NOTICE",
100 0x03, "SEQUENCE_TRACK_NAME",
101 0x04, "INSTRUMENT_NAME",
105 0x20, "MIDI_CHANNEL_PREFIX",
107 0x2F, "END_OF_TRACK",
109 0x54, "SMTPE_OFFSET",
110 0x58, "TIME_SIGNATURE",
111 0x59, "KEY_SIGNATURE",
112 0x7F, "SEQUENCER_SPECIFIC_META_EVENT",
118 add_constants (PyObject *dict)
120 message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
122 for ( j =0; p[j]; j++)
123 for ( i = 0; p[j][i].description; i++)
124 PyDict_SetItemString (dict, p[j][i].description, Py_BuildValue ("i", p[j][i].msg));
128 get_number (unsigned char ** str, unsigned char * end_str, int length)
130 /* # MIDI uses big-endian for everything */
134 for (; i < length; i++)
135 sum = (sum << 8) + (unsigned char) (*str)[i];
138 debug_print ("%d:\n", sum);
143 get_variable_length_number (unsigned char **str, unsigned char * end_str)
147 while (*str < end_str)
149 unsigned char x = **str;
151 sum = (sum << 7) + (x & 0x7F);
155 debug_print ("%d:\n", sum);
160 read_one_byte (unsigned char **track, unsigned char *end,
163 PyObject *pyev = Py_BuildValue ("(i)", x);
164 debug_print ("%x:%s", x, "event\n");
170 read_two_bytes (unsigned char **track, unsigned char *end,
173 PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
175 debug_print ("%x:%s", x, "event\n");
180 read_three_bytes (unsigned char **track, unsigned char *end,
183 PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
187 debug_print ("%x:%s", x, "event\n");
192 read_string (unsigned char **track, unsigned char *end)
194 unsigned long length = get_variable_length_number (track, end);
195 if (length > end - *track)
196 length = end - *track;
199 return Py_BuildValue ("s", ((*track) -length));
202 typedef PyObject* (*Read_midi_event)
203 (unsigned char **track, unsigned char *end,
208 read_f0_byte (unsigned char **track, unsigned char *end,
212 debug_print ("%x:%s", x, "event\n");
215 unsigned char z = (*track)[0 ];
217 debug_print ("%x:%s", z, "f0-event\n");
219 if (z == 0x2f && (*track)[0] == 0x00) /* end of track */
225 return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
228 return Py_BuildValue ("(iO)", x, read_string (track, end));
231 Read_midi_event read_midi_event [16] =
239 read_one_byte, // 60 data entry.
240 read_two_bytes, // 70 all notes off
241 read_three_bytes, // 80 note off
242 read_three_bytes, // 90 note on
243 read_three_bytes, // a0 poly aftertouch
244 read_three_bytes, // b0 control
245 read_two_bytes, // c0 prog change
246 read_two_bytes, // d0 ch aftertouch
247 read_three_bytes, // e0 pitchwheel range
253 read_event (unsigned char **track, unsigned char *end, PyObject *time,
254 unsigned char *running_status)
256 int rsb_skip = ((**track & 0x80)) ? 1 :0;
258 unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
260 PyObject * bare_event = 0;
261 debug_print ("%x:%s", x, "event\n");
265 // printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
266 bare_event = (*read_midi_event[x >> 4]) (track, end, x);
268 return Py_BuildValue ("(OO)", time, bare_event);
274 midi_parse_track (unsigned char **track, unsigned char *track_end)
276 unsigned int time = 0;
277 unsigned char running_status;
278 unsigned long track_len, track_size;
279 PyObject *pytrack = 0;
281 debug_print ("%s", "\n");
283 track_size = track_end - *track;
285 debug_print ("%s", "\n");
286 if (strcmp (*track, "MTrk"))
287 return midi_error (__FUNCTION__ ": MTrk expected");
291 track_len = get_number (track, *track + 4, 4);
294 debug_print ("track_len: %u\n", track_len);
295 debug_print ("track_size: %u\n", track_size);
296 debug_print ("track begin: %p\n", track);
297 debug_print ("track end: %p\n", track + track_len);
299 if (track_len > track_size)
300 return midi_error (__FUNCTION__ ": track size corrupt");
302 pytrack = PyList_New (0);
304 track_end = *track + track_len;
307 PyObject *pytime = PyInt_FromLong (0L);
308 while (*track < track_end)
310 long dt = get_variable_length_number(track, track_end);
315 pytime = PyInt_FromLong (time);
317 pyev = read_event (track, track_end, pytime,
320 PyList_Append (pytrack, pyev);
330 pymidi_parse_track (PyObject *self, PyObject *args)
332 unsigned char *track, *track_end;
333 unsigned long track_size, track_len;
335 PyObject * sobj = PyTuple_GetItem (args, 0);
337 debug_print ("%s", "\n");
338 if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
342 return midi_error (__FUNCTION__ ": negative track size");
344 track_end = track + track_size;
346 return midi_parse_track (&track, track_end);
350 midi_parse (unsigned char **midi,unsigned char *midi_end)
352 PyObject *pymidi = 0;
353 unsigned long header_len;
354 unsigned format, tracks;
358 debug_print ("%s", "\n");
361 header_len = get_number (midi, *midi + 4, 4);
365 return midi_error (__FUNCTION__ ": header too short");
367 format = get_number (midi, *midi + 2, 2);
368 tracks = get_number (midi, *midi + 2, 2);
371 return midi_error (__FUNCTION__ ": too many tracks");
373 division = get_number (midi, *midi + 2, 2) * 4;
377 /* return midi_error ("can't handle non-metrical time"); */
379 *midi += header_len - 6;
381 pymidi = PyList_New (0);
384 for (i = 0; i < tracks; i++)
385 PyList_Append (pymidi, midi_parse_track (midi, midi_end));
387 pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
393 pymidi_parse (PyObject *self, PyObject *args)
395 unsigned char *midi, *midi_end;
396 unsigned long midi_size, midi_len;
398 PyObject *sobj = PyTuple_GetItem (args, 0);
400 debug_print ("%s", "\n");
401 if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
404 if (strcmp (midi, "MThd"))
405 return midi_error (__FUNCTION__ ": MThd expected");
409 midi_end = midi + midi_size;
411 return midi_parse (&midi, midi_end);
415 static PyMethodDef MidiMethods[] =
417 {"parse", pymidi_parse, 1},
418 {"parse_track", pymidi_parse_track, 1},
419 {0, 0} /* Sentinel */
425 m = Py_InitModule ("midi", MidiMethods);
426 d = PyModule_GetDict (m);
428 Midi_error = PyString_FromString ("midi.error");
429 PyDict_SetItemString (d, "error", Midi_error);
431 Midi_warning = PyString_FromString ("midi.warning");
432 PyDict_SetItemString (d, "warning", Midi_warning);