Fix metronome alignment.
[lilypond/mpolesky.git] / python / midi.c
blob01c9925ece5445a65d947109f6efc7bc3c80945a
1 /*
2 This file is part of LilyPond, the GNU music typesetter.
4 Copyright (C) 2001--2010 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/>.
24 python
25 import midi
26 s = open ("s.midi").read ()
27 midi.parse_track (s)
28 midi.parse (s)
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]))
41 #include <Python.h>
43 char *
44 compat_itoa (int i)
46 static char buffer[9];
47 snprintf (buffer, 8, "%d", i);
48 return buffer;
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 */
58 #endif
60 #if 0
61 int x = 0;
62 int *track = &x;
63 #define debug_print(f, args...) fprintf (stderr, "%s:%d: track: %p :" f, __FUNCTION__, __LINE__, *track, ##args)
64 #else
65 #define debug_print(f, args...)
66 #endif
68 static PyObject *Midi_error;
69 static PyObject *Midi_warning;
71 static PyObject *
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));
76 strcpy (dest, func);
77 strcat (dest, s);
78 strcat (dest, t);
79 PyErr_SetString (Midi_error, dest);
80 free (dest);
82 return 0;
85 static PyObject *
86 midi_warning (char const *s)
88 PyErr_SetString (Midi_warning, s);
89 return 0;
93 typedef struct message {
94 unsigned char msg;
95 char * description;
96 } message_t;
98 message_t channelVoiceMessages[] = {
99 {0x80, "NOTE_OFF"},
100 {0x90, "NOTE_ON"},
101 {0xA0, "POLYPHONIC_KEY_PRESSURE"},
102 {0xB0, "CONTROLLER_CHANGE"},
103 {0xC0, "PROGRAM_CHANGE"},
104 {0xD0, "CHANNEL_KEY_PRESSURE"},
105 {0xE0, "PITCH_BEND"},
106 {0,0}
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"},
118 {0,0}
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"},
127 {0x05, "LYRIC"},
128 {0x06, "MARKER"},
129 {0x07, "CUE_POINT"},
130 {0x20, "MIDI_CHANNEL_PREFIX"},
131 {0x21, "MIDI_PORT"},
132 {0x2F, "END_OF_TRACK"},
133 {0x51, "SET_TEMPO"},
134 {0x54, "SMTPE_OFFSET"},
135 {0x58, "TIME_SIGNATURE"},
136 {0x59, "KEY_SIGNATURE"},
137 {0x7F, "SEQUENCER_SPECIFIC_META_EVENT"},
138 {0xFF, "META_EVENT"},
139 {0,0}
142 void
143 add_constants (PyObject *dict)
145 message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
146 int i,j;
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));
152 unsigned long int
153 get_number (unsigned char ** str, unsigned char * end_str, int length)
155 /* # MIDI uses big-endian for everything */
156 long sum = 0;
157 int i = 0;
159 for (; i < length &&
160 ((*str) + i < end_str); i++)
161 sum = (sum << 8) + (unsigned char) (*str)[i];
163 *str += length;
164 debug_print ("%d:\n", sum);
165 return sum;
168 unsigned long int
169 get_variable_length_number (unsigned char **str, unsigned char * end_str)
171 long sum = 0;
173 while (*str < end_str)
175 unsigned char x = **str;
176 (*str) ++;
177 sum = (sum << 7) + (x & 0x7F);
178 if (!(x & 0x80))
179 break;
181 debug_print ("%d:\n", sum);
182 return sum;
185 PyObject *
186 read_one_byte (unsigned char **track, unsigned char *end,
187 unsigned char x)
189 PyObject *pyev = Py_BuildValue ("(i)", x);
190 debug_print ("%x:%s", x, "event\n");
192 return pyev;
195 PyObject *
196 read_two_bytes (unsigned char **track, unsigned char *end,
197 unsigned char x)
199 PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
200 *track += 1;
201 debug_print ("%x:%s", x, "event\n");
202 return pyev;
205 PyObject *
206 read_three_bytes (unsigned char **track, unsigned char *end,
207 unsigned char x)
209 PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
210 (*track)[1]);
212 *track += 2;
213 debug_print ("%x:%s", x, "event\n");
214 return pyev;
217 PyObject *
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;
224 *track += length;
225 return Py_BuildValue ("s#", ((*track) -length), length);
228 typedef PyObject* (*Read_midi_event)
229 (unsigned char **track, unsigned char *end,
230 unsigned char x);
233 static PyObject *
234 read_f0_byte (unsigned char **track, unsigned char *end,
235 unsigned char x)
238 debug_print ("%x:%s", x, "event\n");
239 if (x == 0xff)
241 unsigned char z = (*track)[0 ];
242 *track += 1;
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] =
253 read_one_byte, // 0
254 read_one_byte, // 10
255 read_one_byte, // 20
256 read_one_byte, // 30
257 read_one_byte, // 40
258 read_one_byte, // 50
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
268 read_f0_byte, // f0
272 static PyObject *
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");
282 *running_status = x;
283 *track += rsb_skip;
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);
287 if (bare_event)
288 return Py_BuildValue ("(OO)", time, bare_event);
289 else
290 return NULL;
293 static PyObject *
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))
307 *track[4] = 0;
308 return midi_error (__FUNCTION__, ": MTrk expected, got: ", *(char**)track);
311 *track += 4;
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);
335 PyObject *pyev = 0;
337 time += dt;
338 if (dt)
339 pytime = PyInt_FromLong (time);
341 pyev = read_event (track, track_end, pytime,
342 &running_status);
343 if (pyev)
344 PyList_Append (pytrack, pyev);
348 *track = track_end;
349 return pytrack;
353 static PyObject *
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))
361 return 0;
363 if (track_size < 0)
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);
371 static PyObject *
372 midi_parse (unsigned char **midi,unsigned char *midi_end)
374 PyObject *pymidi = 0;
375 unsigned long header_len;
376 unsigned format, tracks;
377 int division;
378 int i;
380 debug_print ("%s", "\n");
382 /* Header */
383 header_len = get_number (midi, *midi + 4, 4);
385 if (header_len < 6)
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);
391 if (tracks > 32)
392 return midi_error (__FUNCTION__, ": too many tracks: ", compat_itoa (tracks));
394 division = get_number (midi, *midi + 2, 2) * 4;
397 if (division < 0)
398 /* return midi_error (cannot handle non-metrical time"); */
400 *midi += header_len - 6;
402 pymidi = PyList_New (0);
404 /* Tracks */
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),
409 pymidi);
410 return pymidi;
413 static PyObject *
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))
421 return 0;
423 if (memcmp (midi, "MThd", 4))
425 midi[4] = 0;
426 return midi_error (__FUNCTION__, ": MThd expected, got: ", (char*)midi);
429 midi += 4;
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 */
444 PyMODINIT_FUNC
445 initmidi (void)
447 PyObject *m, *d;
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);
453 add_constants (d);
454 Midi_warning = PyString_FromString ("midi.warning");
455 PyDict_SetItemString (d, "warning", Midi_warning);
458 FIXME.
460 (void) midi_warning;