Add angularity to regtest and docstring for parenthesize markup
[lilypond/mpolesky.git] / python / midi.c
blobbe06bb66cea0f892ba5ae79d9eb2ae5a7fd06ebb
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 /* PyMIDINIT_FUNC isn't defined in Python < 2.3 */
44 #ifndef PyMODINIT_FUNC
45 # if defined(__cplusplus)
46 # define PyMODINIT_FUNC extern "C" void
47 # else /* __cplusplus */
48 # define PyMODINIT_FUNC void
49 # endif /* __cplusplus */
50 #endif
52 #if 0
53 int x = 0;
54 int *track = &x;
55 #define debug_print(f, args...) fprintf (stderr, "%s:%d: track: %p :" f, __FUNCTION__, __LINE__, *track, ##args)
56 #else
57 #define debug_print(f, args...)
58 #endif
60 static PyObject *Midi_error;
61 static PyObject *Midi_warning;
63 static PyObject *
64 midi_error (char const *func, char *s)
66 char *dest = (char*) malloc (sizeof (char) * (strlen (func) + strlen (s) + 1));
67 strcpy (dest, func);
68 strcat (dest, s);
69 PyErr_SetString (Midi_error, dest);
70 free (dest);
72 return 0;
75 static PyObject *
76 midi_warning (char const *s)
78 PyErr_SetString (Midi_warning, s);
79 return 0;
83 typedef struct message {
84 unsigned char msg;
85 char * description;
86 } message_t;
88 message_t channelVoiceMessages[] = {
89 {0x80, "NOTE_OFF"},
90 {0x90, "NOTE_ON"},
91 {0xA0, "POLYPHONIC_KEY_PRESSURE"},
92 {0xB0, "CONTROLLER_CHANGE"},
93 {0xC0, "PROGRAM_CHANGE"},
94 {0xD0, "CHANNEL_KEY_PRESSURE"},
95 {0xE0, "PITCH_BEND"},
96 {0,0}
99 message_t channelModeMessages[] = {
100 {0x78, "ALL_SOUND_OFF"},
101 {0x79, "RESET_ALL_CONTROLLERS"},
102 {0x7A, "LOCAL_CONTROL"},
103 {0x7B, "ALL_NOTES_OFF"},
104 {0x7C, "OMNI_MODE_OFF"},
105 {0x7D, "OMNI_MODE_ON"},
106 {0x7E, "MONO_MODE_ON"},
107 {0x7F, "POLY_MODE_ON"},
108 {0,0}
111 message_t metaEvents[] = {
112 {0x00, "SEQUENCE_NUMBER"},
113 {0x01, "TEXT_EVENT"},
114 {0x02, "COPYRIGHT_NOTICE"},
115 {0x03, "SEQUENCE_TRACK_NAME"},
116 {0x04, "INSTRUMENT_NAME"},
117 {0x05, "LYRIC"},
118 {0x06, "MARKER"},
119 {0x07, "CUE_POINT"},
120 {0x20, "MIDI_CHANNEL_PREFIX"},
121 {0x21, "MIDI_PORT"},
122 {0x2F, "END_OF_TRACK"},
123 {0x51, "SET_TEMPO"},
124 {0x54, "SMTPE_OFFSET"},
125 {0x58, "TIME_SIGNATURE"},
126 {0x59, "KEY_SIGNATURE"},
127 {0x7F, "SEQUENCER_SPECIFIC_META_EVENT"},
128 {0xFF, "META_EVENT"},
129 {0,0}
132 void
133 add_constants (PyObject *dict)
135 message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
136 int i,j;
137 for ( j =0; p[j]; j++)
138 for ( i = 0; p[j][i].description; i++)
139 PyDict_SetItemString (dict, p[j][i].description, Py_BuildValue ("i", p[j][i].msg));
142 unsigned long int
143 get_number (unsigned char ** str, unsigned char * end_str, int length)
145 /* # MIDI uses big-endian for everything */
146 long sum = 0;
147 int i = 0;
149 for (; i < length &&
150 ((*str) + i < end_str); i++)
151 sum = (sum << 8) + (unsigned char) (*str)[i];
153 *str += length;
154 debug_print ("%d:\n", sum);
155 return sum;
158 unsigned long int
159 get_variable_length_number (unsigned char **str, unsigned char * end_str)
161 long sum = 0;
163 while (*str < end_str)
165 unsigned char x = **str;
166 (*str) ++;
167 sum = (sum << 7) + (x & 0x7F);
168 if (!(x & 0x80))
169 break;
171 debug_print ("%d:\n", sum);
172 return sum;
175 PyObject *
176 read_one_byte (unsigned char **track, unsigned char *end,
177 unsigned char x)
179 PyObject *pyev = Py_BuildValue ("(i)", x);
180 debug_print ("%x:%s", x, "event\n");
182 return pyev;
185 PyObject *
186 read_two_bytes (unsigned char **track, unsigned char *end,
187 unsigned char x)
189 PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
190 *track += 1;
191 debug_print ("%x:%s", x, "event\n");
192 return pyev;
195 PyObject *
196 read_three_bytes (unsigned char **track, unsigned char *end,
197 unsigned char x)
199 PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
200 (*track)[1]);
202 *track += 2;
203 debug_print ("%x:%s", x, "event\n");
204 return pyev;
207 PyObject *
208 read_string (unsigned char **track, unsigned char *end)
210 unsigned long length = get_variable_length_number (track, end);
211 if (length > end - *track)
212 length = end - *track;
214 *track += length;
215 return Py_BuildValue ("s#", ((*track) -length), length);
218 typedef PyObject* (*Read_midi_event)
219 (unsigned char **track, unsigned char *end,
220 unsigned char x);
223 static PyObject *
224 read_f0_byte (unsigned char **track, unsigned char *end,
225 unsigned char x)
228 debug_print ("%x:%s", x, "event\n");
229 if (x == 0xff)
231 unsigned char z = (*track)[0 ];
232 *track += 1;
233 debug_print ("%x:%s", z, "f0-event\n");
235 return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
238 return Py_BuildValue ("(iO)", x, read_string (track, end));
241 Read_midi_event read_midi_event [16] =
243 read_one_byte, // 0
244 read_one_byte, // 10
245 read_one_byte, // 20
246 read_one_byte, // 30
247 read_one_byte, // 40
248 read_one_byte, // 50
249 read_one_byte, // 60 data entry.
250 read_two_bytes, // 70 all notes off
251 read_three_bytes, // 80 note off
252 read_three_bytes, // 90 note on
253 read_three_bytes, // a0 poly aftertouch
254 read_three_bytes, // b0 control
255 read_two_bytes, // c0 prog change
256 read_two_bytes, // d0 ch aftertouch
257 read_three_bytes, // e0 pitchwheel range
258 read_f0_byte, // f0
262 static PyObject *
263 read_event (unsigned char **track, unsigned char *end, PyObject *time,
264 unsigned char *running_status)
266 int rsb_skip = ((**track & 0x80)) ? 1 :0;
268 unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
270 PyObject * bare_event = 0;
271 debug_print ("%x:%s", x, "event\n");
272 *running_status = x;
273 *track += rsb_skip;
275 // printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
276 bare_event = (*read_midi_event[x >> 4]) (track, end, x);
277 if (bare_event)
278 return Py_BuildValue ("(OO)", time, bare_event);
279 else
280 return NULL;
283 static PyObject *
284 midi_parse_track (unsigned char **track, unsigned char *track_end)
286 unsigned int time = 0;
287 unsigned long track_len, track_size;
288 PyObject *pytrack = 0;
290 debug_print ("%s", "\n");
292 track_size = track_end - *track;
294 debug_print ("%s", "\n");
295 if (memcmp (*track, "MTrk", 4))
296 return midi_error (__FUNCTION__, ": MTrk expected");
298 *track += 4;
300 track_len = get_number (track, *track + 4, 4);
303 debug_print ("track_len: %u\n", track_len);
304 debug_print ("track_size: %u\n", track_size);
305 debug_print ("track begin: %p\n", track);
306 debug_print ("track end: %p\n", track + track_len);
308 if (track_len > track_size)
309 return midi_error (__FUNCTION__, ": track size corrupt");
311 pytrack = PyList_New (0);
313 if (*track + track_len < track_end)
314 track_end = *track + track_len;
317 PyObject *pytime = PyInt_FromLong (0L);
318 unsigned char running_status = 0;
320 while (*track < track_end)
322 long dt = get_variable_length_number(track, track_end);
323 PyObject *pyev = 0;
325 time += dt;
326 if (dt)
327 pytime = PyInt_FromLong (time);
329 pyev = read_event (track, track_end, pytime,
330 &running_status);
331 if (pyev)
332 PyList_Append (pytrack, pyev);
336 *track = track_end;
337 return pytrack;
341 static PyObject *
342 pymidi_parse_track (PyObject *self, PyObject *args)
344 unsigned char *track, *track_end;
345 unsigned long track_size;
347 debug_print ("%s", "\n");
348 if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
349 return 0;
351 if (track_size < 0)
352 return midi_error (__FUNCTION__, ": negative track size");
354 track_end = track + track_size;
356 return midi_parse_track (&track, track_end);
359 static PyObject *
360 midi_parse (unsigned char **midi,unsigned char *midi_end)
362 PyObject *pymidi = 0;
363 unsigned long header_len;
364 unsigned format, tracks;
365 int division;
366 int i;
368 debug_print ("%s", "\n");
370 /* Header */
371 header_len = get_number (midi, *midi + 4, 4);
373 if (header_len < 6)
374 return midi_error (__FUNCTION__, ": header too short");
376 format = get_number (midi, *midi + 2, 2);
377 tracks = get_number (midi, *midi + 2, 2);
379 if (tracks > 32)
380 return midi_error (__FUNCTION__, ": too many tracks");
382 division = get_number (midi, *midi + 2, 2) * 4;
385 if (division < 0)
386 /* return midi_error (cannot handle non-metrical time"); */
388 *midi += header_len - 6;
390 pymidi = PyList_New (0);
392 /* Tracks */
393 for (i = 0; i < tracks; i++)
394 PyList_Append (pymidi, midi_parse_track (midi, midi_end));
396 pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
397 pymidi);
398 return pymidi;
401 static PyObject *
402 pymidi_parse (PyObject *self, PyObject *args)
404 unsigned char *midi, *midi_end;
405 unsigned long midi_size;
407 debug_print ("%s", "\n");
408 if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
409 return 0;
411 if (memcmp (midi, "MThd", 4))
412 return midi_error (__FUNCTION__, ": MThd expected");
414 midi += 4;
416 midi_end = midi + midi_size;
418 return midi_parse (&midi, midi_end);
422 static PyMethodDef MidiMethods[] =
424 {"parse", pymidi_parse, 1},
425 {"parse_track", pymidi_parse_track, 1},
426 {0, 0} /* Sentinel */
429 PyMODINIT_FUNC
430 initmidi (void)
432 PyObject *m, *d;
433 m = Py_InitModule ("midi", MidiMethods);
434 d = PyModule_GetDict (m);
436 Midi_error = PyString_FromString ("midi.error");
437 PyDict_SetItemString (d, "error", Midi_error);
438 add_constants (d);
439 Midi_warning = PyString_FromString ("midi.warning");
440 PyDict_SetItemString (d, "warning", Midi_warning);
443 FIXME.
445 (void) midi_warning;