Midi2ly: in --preview mode, only parse first eight 4/4 bars (12288 clocks).
[lilypond/patrick.git] / python / midi.c
blob187268b78efc105fe44dfdeee9c345ea781a3c05
1 /*
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/>.
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 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)
65 #else
66 #define debug_print(f, args...)
67 #endif
69 static PyObject *Midi_error;
70 static PyObject *Midi_warning;
72 static PyObject *
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));
77 strcpy (dest, func);
78 strcat (dest, s);
79 strcat (dest, t);
80 PyErr_SetString (Midi_error, dest);
81 free (dest);
83 return 0;
86 static PyObject *
87 midi_warning (char const *s)
89 PyErr_SetString (Midi_warning, s);
90 return 0;
94 typedef struct message {
95 unsigned char msg;
96 char * description;
97 } message_t;
99 message_t channelVoiceMessages[] = {
100 {0x80, "NOTE_OFF"},
101 {0x90, "NOTE_ON"},
102 {0xA0, "POLYPHONIC_KEY_PRESSURE"},
103 {0xB0, "CONTROLLER_CHANGE"},
104 {0xC0, "PROGRAM_CHANGE"},
105 {0xD0, "CHANNEL_KEY_PRESSURE"},
106 {0xE0, "PITCH_BEND"},
107 {0,0}
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"},
119 {0,0}
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"},
128 {0x05, "LYRIC"},
129 {0x06, "MARKER"},
130 {0x07, "CUE_POINT"},
131 {0x20, "MIDI_CHANNEL_PREFIX"},
132 {0x21, "MIDI_PORT"},
133 {0x2F, "END_OF_TRACK"},
134 {0x51, "SET_TEMPO"},
135 {0x54, "SMTPE_OFFSET"},
136 {0x58, "TIME_SIGNATURE"},
137 {0x59, "KEY_SIGNATURE"},
138 {0x7F, "SEQUENCER_SPECIFIC_META_EVENT"},
139 {0xFF, "META_EVENT"},
140 {0,0}
143 void
144 add_constants (PyObject *dict)
146 message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
147 int i,j;
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));
153 unsigned long int
154 get_number (unsigned char ** str, unsigned char * end_str, int length)
156 /* # MIDI uses big-endian for everything */
157 long sum = 0;
158 int i = 0;
160 for (; i < length &&
161 ((*str) + i < end_str); i++)
162 sum = (sum << 8) + (unsigned char) (*str)[i];
164 *str += length;
165 debug_print ("%ld:\n", sum);
166 return sum;
169 unsigned long int
170 get_variable_length_number (unsigned char **str, unsigned char * end_str)
172 long sum = 0;
174 while (*str < end_str)
176 unsigned char x = **str;
177 (*str) ++;
178 sum = (sum << 7) + (x & 0x7F);
179 if (!(x & 0x80))
180 break;
182 debug_print ("%ld:\n", sum);
183 return sum;
186 PyObject *
187 read_one_byte (unsigned char **track, unsigned char *end,
188 unsigned char x)
190 PyObject *pyev = Py_BuildValue ("(i)", x);
191 debug_print ("%x:%s", x, "event\n");
193 return pyev;
196 PyObject *
197 read_two_bytes (unsigned char **track, unsigned char *end,
198 unsigned char x)
200 PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
201 *track += 1;
202 debug_print ("%x:%s", x, "event\n");
203 return pyev;
206 PyObject *
207 read_three_bytes (unsigned char **track, unsigned char *end,
208 unsigned char x)
210 PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
211 (*track)[1]);
213 *track += 2;
214 debug_print ("%x:%s", x, "event\n");
215 return pyev;
218 PyObject *
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;
225 *track += length;
226 return Py_BuildValue ("s#", ((*track) -length), length);
229 typedef PyObject* (*Read_midi_event)
230 (unsigned char **track, unsigned char *end,
231 unsigned char x);
234 static PyObject *
235 read_f0_byte (unsigned char **track, unsigned char *end,
236 unsigned char x)
239 debug_print ("%x:%s", x, "event\n");
240 if (x == 0xff)
242 unsigned char z = (*track)[0 ];
243 *track += 1;
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] =
254 read_one_byte, // 0
255 read_one_byte, // 10
256 read_one_byte, // 20
257 read_one_byte, // 30
258 read_one_byte, // 40
259 read_one_byte, // 50
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
269 read_f0_byte, // f0
273 static PyObject *
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");
283 *running_status = x;
284 *track += rsb_skip;
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);
288 if (bare_event)
289 return Py_BuildValue ("(OO)", time, bare_event);
290 else
291 return NULL;
294 static PyObject *
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))
308 *track[4] = 0;
309 return midi_error (__FUNCTION__, ": MTrk expected, got: ", *(char**)track);
312 *track += 4;
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);
336 PyObject *pyev = 0;
338 time += dt;
339 if (dt)
340 pytime = PyInt_FromLong (time);
341 if (clocks_max && time > clocks_max)
342 break;
343 pyev = read_event (track, track_end, pytime,
344 &running_status);
345 if (pyev)
346 PyList_Append (pytrack, pyev);
350 *track = track_end;
351 return pytrack;
355 static PyObject *
356 pymidi_parse_track (PyObject *self, PyObject *args)
358 unsigned char *track, *track_end;
359 unsigned long track_size;
360 int clocks_max;
362 debug_print ("%s", "\n");
363 if (!PyArg_ParseTuple (args, "s#|i", &track, &track_size, &clocks_max))
364 return 0;
365 debug_print ("clocks_max: %d\n", clocks_max);
367 if (track_size < 0)
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);
375 static PyObject *
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;
381 int division;
382 int i;
384 debug_print ("%s", "\n");
386 /* Header */
387 header_len = get_number (midi, *midi + 4, 4);
389 if (header_len < 6)
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);
395 if (tracks > 256)
396 return midi_error (__FUNCTION__, ": too many tracks: ", compat_itoa (tracks));
398 division = get_number (midi, *midi + 2, 2) * 4;
401 if (division < 0)
402 /* return midi_error (cannot handle non-metrical time"); */
404 *midi += header_len - 6;
406 pymidi = PyList_New (0);
408 /* Tracks */
409 for (i = 0; i < tracks; i++)
410 PyList_Append (pymidi, midi_parse_track (midi, midi_end, clocks_max));
412 pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
413 pymidi);
414 return pymidi;
417 static PyObject *
418 pymidi_parse (PyObject *self, PyObject *args)
420 unsigned char *midi, *midi_end;
421 unsigned long midi_size;
422 int clocks_max;
424 debug_print ("%s", "\n");
425 if (!PyArg_ParseTuple (args, "s#|i", &midi, &midi_size, &clocks_max))
426 return 0;
427 debug_print ("clocks_max: %d\n", clocks_max);
429 if (memcmp (midi, "MThd", 4))
431 midi[4] = 0;
432 return midi_error (__FUNCTION__, ": MThd expected, got: ", (char*)midi);
435 midi += 4;
437 midi_end = midi + midi_size;
439 return midi_parse (&midi, midi_end, clocks_max);
442 static PyMethodDef MidiMethods[] =
444 {"parse", pymidi_parse, METH_VARARGS},
445 {"parse_track", pymidi_parse_track, METH_VARARGS},
446 {0, 0} /* Sentinel */
449 PyMODINIT_FUNC
450 initmidi (void)
452 PyObject *m, *d;
453 m = Py_InitModule ("midi", MidiMethods);
454 d = PyModule_GetDict (m);
456 Midi_error = PyString_FromString ("midi.error");
457 PyDict_SetItemString (d, "error", Midi_error);
458 add_constants (d);
459 Midi_warning = PyString_FromString ("midi.warning");
460 PyDict_SetItemString (d, "warning", Midi_warning);
463 FIXME.
465 (void) midi_warning;