2 This file is part of LilyPond, the GNU music typesetter.
4 Copyright (C) 2001--2015 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 urg_debug_print(f, args...) fprintf (stderr, "%s:%d: track: %p: " f, __FUNCTION__, __LINE__, *track, ##args)
64 #define debug_print(f, args...) fprintf (stderr, f, ##args)
66 #define debug_print(f, args...)
69 static PyObject *Midi_error;
70 static PyObject *Midi_warning;
73 midi_error (char const *func, char *s, char *t)
75 char *dest = (char*) malloc (sizeof (char)
76 * (strlen (func) + strlen (s) + strlen (t) + 1));
80 PyErr_SetString (Midi_error, dest);
87 midi_warning (char const *s)
89 PyErr_SetString (Midi_warning, s);
94 typedef struct message {
99 message_t channelVoiceMessages[] = {
102 {0xA0, "POLYPHONIC_KEY_PRESSURE"},
103 {0xB0, "CONTROLLER_CHANGE"},
104 {0xC0, "PROGRAM_CHANGE"},
105 {0xD0, "CHANNEL_KEY_PRESSURE"},
106 {0xE0, "PITCH_BEND"},
110 message_t channelModeMessages[] = {
111 {0x78, "ALL_SOUND_OFF"},
112 {0x79, "RESET_ALL_CONTROLLERS"},
113 {0x7A, "LOCAL_CONTROL"},
114 {0x7B, "ALL_NOTES_OFF"},
115 {0x7C, "OMNI_MODE_OFF"},
116 {0x7D, "OMNI_MODE_ON"},
117 {0x7E, "MONO_MODE_ON"},
118 {0x7F, "POLY_MODE_ON"},
122 message_t metaEvents[] = {
123 {0x00, "SEQUENCE_NUMBER"},
124 {0x01, "TEXT_EVENT"},
125 {0x02, "COPYRIGHT_NOTICE"},
126 {0x03, "SEQUENCE_TRACK_NAME"},
127 {0x04, "INSTRUMENT_NAME"},
131 {0x20, "MIDI_CHANNEL_PREFIX"},
133 {0x2F, "END_OF_TRACK"},
135 {0x54, "SMTPE_OFFSET"},
136 {0x58, "TIME_SIGNATURE"},
137 {0x59, "KEY_SIGNATURE"},
138 {0x7F, "SEQUENCER_SPECIFIC_META_EVENT"},
139 {0xFF, "META_EVENT"},
144 add_constants (PyObject *dict)
146 message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
148 for ( j =0; p[j]; j++)
149 for ( i = 0; p[j][i].description; i++)
150 PyDict_SetItemString (dict, p[j][i].description, Py_BuildValue ("i", p[j][i].msg));
154 get_number (unsigned char ** str, unsigned char * end_str, int length)
156 /* # MIDI uses big-endian for everything */
161 ((*str) + i < end_str); i++)
162 sum = (sum << 8) + (unsigned char) (*str)[i];
165 debug_print ("%ld:\n", sum);
170 get_variable_length_number (unsigned char **str, unsigned char * end_str)
174 while (*str < end_str)
176 unsigned char x = **str;
178 sum = (sum << 7) + (x & 0x7F);
182 debug_print ("%ld:\n", sum);
187 read_one_byte (unsigned char **track, unsigned char *end,
190 PyObject *pyev = Py_BuildValue ("(i)", x);
191 debug_print ("%x:%s", x, "event\n");
197 read_two_bytes (unsigned char **track, unsigned char *end,
200 PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
202 debug_print ("%x:%s", x, "event\n");
207 read_three_bytes (unsigned char **track, unsigned char *end,
210 PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
214 debug_print ("%x:%s", x, "event\n");
219 read_string (unsigned char **track, unsigned char *end)
221 unsigned long length = get_variable_length_number (track, end);
222 if (length > end - *track)
223 length = end - *track;
226 return Py_BuildValue ("s#", ((*track) -length), length);
229 typedef PyObject* (*Read_midi_event)
230 (unsigned char **track, unsigned char *end,
235 read_f0_byte (unsigned char **track, unsigned char *end,
239 debug_print ("%x:%s", x, "event\n");
242 unsigned char z = (*track)[0 ];
244 debug_print ("%x:%s", z, "f0-event\n");
246 return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
249 return Py_BuildValue ("(iO)", x, read_string (track, end));
252 Read_midi_event read_midi_event [16] =
260 read_one_byte, // 60 data entry.
261 read_two_bytes, // 70 all notes off
262 read_three_bytes, // 80 note off
263 read_three_bytes, // 90 note on
264 read_three_bytes, // a0 poly aftertouch
265 read_three_bytes, // b0 control
266 read_two_bytes, // c0 prog change
267 read_two_bytes, // d0 ch aftertouch
268 read_three_bytes, // e0 pitchwheel range
274 read_event (unsigned char **track, unsigned char *end, PyObject *time,
275 unsigned char *running_status)
277 int rsb_skip = ((**track & 0x80)) ? 1 :0;
279 unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
281 PyObject * bare_event = 0;
282 debug_print ("%x:%s", x, "event\n");
286 // printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
287 bare_event = (*read_midi_event[x >> 4]) (track, end, x);
289 return Py_BuildValue ("(OO)", time, bare_event);
295 midi_parse_track (unsigned char **track, unsigned char *track_end, int clocks_max)
297 unsigned int time = 0;
298 unsigned long track_len, track_size;
299 PyObject *pytrack = 0;
301 debug_print ("%s", "\n");
303 track_size = track_end - *track;
305 debug_print ("%s", "\n");
306 if (memcmp (*track, "MTrk", 4))
309 return midi_error (__FUNCTION__, ": MTrk expected, got: ", *(char**)track);
314 track_len = get_number (track, *track + 4, 4);
316 debug_print ("track_len: %lu\n", track_len);
317 debug_print ("track_size: %lu\n", track_size);
318 debug_print ("track begin: %p\n", track);
319 debug_print ("track end: %p\n", track + track_len);
321 if (track_len > track_size)
322 return midi_error (__FUNCTION__, ": track length corrupt: ", compat_itoa (track_len));
324 pytrack = PyList_New (0);
326 if (*track + track_len < track_end)
327 track_end = *track + track_len;
330 PyObject *pytime = PyInt_FromLong (0L);
331 unsigned char running_status = 0;
333 while (*track < track_end)
335 long dt = get_variable_length_number(track, track_end);
340 pytime = PyInt_FromLong (time);
341 if (clocks_max && time > clocks_max)
343 pyev = read_event (track, track_end, pytime,
346 PyList_Append (pytrack, pyev);
356 pymidi_parse_track (PyObject *self, PyObject *args)
358 unsigned char *track, *track_end;
362 debug_print ("%s", "\n");
363 if (!PyArg_ParseTuple (args, "s#|i", &track, &track_size, &clocks_max))
365 debug_print ("clocks_max: %d\n", clocks_max);
368 return midi_error (__FUNCTION__, ": negative track size: ", compat_itoa (track_size));
370 track_end = track + track_size;
372 return midi_parse_track (&track, track_end, clocks_max);
376 midi_parse (unsigned char **midi,unsigned char *midi_end, int clocks_max)
378 PyObject *pymidi = 0;
379 unsigned long header_len;
380 unsigned format, tracks;
384 debug_print ("%s", "\n");
387 header_len = get_number (midi, *midi + 4, 4);
390 return midi_error (__FUNCTION__, ": header too short: ", compat_itoa (header_len));
392 format = get_number (midi, *midi + 2, 2);
393 tracks = get_number (midi, *midi + 2, 2);
396 return midi_error (__FUNCTION__, ": too many tracks: ", compat_itoa (tracks));
398 division = get_number (midi, *midi + 2, 2) * 4;
403 return midi_error (cannot handle non-metrical time");
406 *midi += header_len - 6;
408 pymidi = PyList_New (0);
411 for (i = 0; i < tracks; i++)
412 PyList_Append (pymidi, midi_parse_track (midi, midi_end, clocks_max));
414 pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
420 pymidi_parse (PyObject *self, PyObject *args)
422 unsigned char *midi, *midi_end;
423 unsigned long midi_size;
426 debug_print ("%s", "\n");
427 if (!PyArg_ParseTuple (args, "s#|i", &midi, &midi_size, &clocks_max))
429 debug_print ("clocks_max: %d\n", clocks_max);
431 if (memcmp (midi, "MThd", 4))
434 return midi_error (__FUNCTION__, ": MThd expected, got: ", (char*)midi);
439 midi_end = midi + midi_size;
441 return midi_parse (&midi, midi_end, clocks_max);
444 static PyMethodDef MidiMethods[] =
446 {"parse", pymidi_parse, METH_VARARGS},
447 {"parse_track", pymidi_parse_track, METH_VARARGS},
448 {0, 0} /* Sentinel */
455 m = Py_InitModule ("midi", MidiMethods);
456 d = PyModule_GetDict (m);
458 Midi_error = PyString_FromString ("midi.error");
459 PyDict_SetItemString (d, "error", Midi_error);
461 Midi_warning = PyString_FromString ("midi.warning");
462 PyDict_SetItemString (d, "warning", Midi_warning);