new file.
[lilypond.git] / python / midi.c
blob05d616070606a9bffb649f8c0f2f9758a38dc5ad
1 /*
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>
9 */
13 python2
14 import midi
15 s = open ("s.midi").read ()
16 midi.parse_track (s)
17 midi.parse (s)
21 #include "config.h"
23 /* urg */
24 #if HAVE_PYTHON2_PYTHON_H
25 #include <python2/Python.h>
26 #elif HAVE_PYTHON2_2_PYTHON_H
27 #include <python2.2/Python.h>
28 #elif HAVE_PYTHON2_1_PYTHON_H
29 #include <python2.1/Python.h>
30 #elif HAVE_PYTHON2_0_PYTHON_H
31 #include <python2.0/Python.h>
32 #elif HAVE_PYTHON1_5_PYTHON_H
33 #include <python1.5/Python.h>
34 #elif HAVE_PYTHON_PYTHON_H
35 #define assert(x)
36 #include <python/Python.h>
37 #elif HAVE_PYTHON_H
38 #define assert(x)
39 #include <Python.h>
40 #else
41 #error Need Python.h
42 #endif
44 #if 0
45 int x = 0;
46 int *track = &x;
47 #define debug_print(f, args...) fprintf (stderr, "%s:%d: track: %p :" f, __FUNCTION__, __LINE__, *track, ##args)
48 #else
49 #define debug_print(f, args...)
50 #endif
52 static PyObject *Midi_error;
53 static PyObject *Midi_warning;
55 static PyObject *
56 midi_error (char * func, char *s)
58 char*dest = (char*) malloc (sizeof (char) * (strlen (func) + strlen (s) + 1));
59 strcpy (dest, func);
60 strcat (dest, s);
61 PyErr_SetString (Midi_error, dest);
62 free (dest);
64 return 0;
67 static PyObject *
68 midi_warning (char *s)
70 PyErr_SetString (Midi_warning, s);
71 return 0;
75 typedef struct message {
76 unsigned char msg;
77 char * description;
78 } message_t;
80 message_t channelVoiceMessages[] = {
81 0x80, "NOTE_OFF",
82 0x90, "NOTE_ON",
83 0xA0, "POLYPHONIC_KEY_PRESSURE",
84 0xB0, "CONTROLLER_CHANGE",
85 0xC0, "PROGRAM_CHANGE",
86 0xD0, "CHANNEL_KEY_PRESSURE",
87 0xE0, "PITCH_BEND",
88 0,0
91 message_t channelModeMessages[] = {
92 0x78, "ALL_SOUND_OFF",
93 0x79, "RESET_ALL_CONTROLLERS",
94 0x7A, "LOCAL_CONTROL",
95 0x7B, "ALL_NOTES_OFF",
96 0x7C, "OMNI_MODE_OFF",
97 0x7D, "OMNI_MODE_ON",
98 0x7E, "MONO_MODE_ON",
99 0x7F, "POLY_MODE_ON",
103 message_t metaEvents[] = {
104 0x00, "SEQUENCE_NUMBER",
105 0x01, "TEXT_EVENT",
106 0x02, "COPYRIGHT_NOTICE",
107 0x03, "SEQUENCE_TRACK_NAME",
108 0x04, "INSTRUMENT_NAME",
109 0x05, "LYRIC",
110 0x06, "MARKER",
111 0x07, "CUE_POINT",
112 0x20, "MIDI_CHANNEL_PREFIX",
113 0x21, "MIDI_PORT",
114 0x2F, "END_OF_TRACK",
115 0x51, "SET_TEMPO",
116 0x54, "SMTPE_OFFSET",
117 0x58, "TIME_SIGNATURE",
118 0x59, "KEY_SIGNATURE",
119 0x7F, "SEQUENCER_SPECIFIC_META_EVENT",
120 0xFF, "META_EVENT",
124 void
125 add_constants (PyObject *dict)
127 message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
128 int i,j;
129 for ( j =0; p[j]; j++)
130 for ( i = 0; p[j][i].description; i++)
131 PyDict_SetItemString (dict, p[j][i].description, Py_BuildValue ("i", p[j][i].msg));
134 unsigned long int
135 get_number (unsigned char ** str, unsigned char * end_str, int length)
137 /* # MIDI uses big-endian for everything */
138 long sum = 0;
139 int i = 0;
141 for (; i < length; i++)
142 sum = (sum << 8) + (unsigned char) (*str)[i];
144 *str += length;
145 debug_print ("%d:\n", sum);
146 return sum;
149 unsigned long int
150 get_variable_length_number (unsigned char **str, unsigned char * end_str)
152 long sum = 0;
153 int i = 0;
154 while (*str < end_str)
156 unsigned char x = **str;
157 (*str) ++;
158 sum = (sum << 7) + (x & 0x7F);
159 if (!(x & 0x80))
160 break;
162 debug_print ("%d:\n", sum);
163 return sum;
166 PyObject *
167 read_one_byte (unsigned char **track, unsigned char *end,
168 unsigned char x)
170 PyObject *pyev = Py_BuildValue ("(i)", x);
171 debug_print ("%x:%s", x, "event\n");
173 return pyev;
176 PyObject *
177 read_two_bytes (unsigned char **track, unsigned char *end,
178 unsigned char x)
180 PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
181 *track += 1;
182 debug_print ("%x:%s", x, "event\n");
183 return pyev;
186 PyObject *
187 read_three_bytes (unsigned char **track, unsigned char *end,
188 unsigned char x)
190 PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
191 (*track)[1]);
193 *track += 2;
194 debug_print ("%x:%s", x, "event\n");
195 return pyev;
198 PyObject *
199 read_string (unsigned char **track, unsigned char *end)
201 unsigned long length = get_variable_length_number (track, end);
202 if (length > end - *track)
203 length = end - *track;
205 *track += length;
206 return Py_BuildValue ("s#", ((*track) -length), length);
209 typedef PyObject* (*Read_midi_event)
210 (unsigned char **track, unsigned char *end,
211 unsigned char x);
214 static PyObject *
215 read_f0_byte (unsigned char **track, unsigned char *end,
216 unsigned char x)
219 debug_print ("%x:%s", x, "event\n");
220 if (x == 0xff)
222 unsigned char z = (*track)[0 ];
223 *track += 1;
224 debug_print ("%x:%s", z, "f0-event\n");
226 return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
229 return Py_BuildValue ("(iO)", x, read_string (track, end));
232 Read_midi_event read_midi_event [16] =
234 read_one_byte, // 0
235 read_one_byte, // 10
236 read_one_byte, // 20
237 read_one_byte, // 30
238 read_one_byte, // 40
239 read_one_byte, // 50
240 read_one_byte, // 60 data entry.
241 read_two_bytes, // 70 all notes off
242 read_three_bytes, // 80 note off
243 read_three_bytes, // 90 note on
244 read_three_bytes, // a0 poly aftertouch
245 read_three_bytes, // b0 control
246 read_two_bytes, // c0 prog change
247 read_two_bytes, // d0 ch aftertouch
248 read_three_bytes, // e0 pitchwheel range
249 read_f0_byte, // f0
253 static PyObject *
254 read_event (unsigned char **track, unsigned char *end, PyObject *time,
255 unsigned char *running_status)
257 int rsb_skip = ((**track & 0x80)) ? 1 :0;
259 unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
261 PyObject * bare_event = 0;
262 debug_print ("%x:%s", x, "event\n");
263 *running_status = x;
264 *track += rsb_skip;
266 // printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
267 bare_event = (*read_midi_event[x >> 4]) (track, end, x);
268 if (bare_event)
269 return Py_BuildValue ("(OO)", time, bare_event);
270 else
271 return NULL;
274 static PyObject *
275 midi_parse_track (unsigned char **track, unsigned char *track_end)
277 unsigned int time = 0;
278 unsigned char running_status;
279 unsigned long track_len, track_size;
280 PyObject *pytrack = 0;
282 debug_print ("%s", "\n");
284 track_size = track_end - *track;
286 debug_print ("%s", "\n");
287 if (strcmp (*track, "MTrk"))
288 return midi_error (__FUNCTION__, ": MTrk expected");
290 *track += 4;
292 track_len = get_number (track, *track + 4, 4);
295 debug_print ("track_len: %u\n", track_len);
296 debug_print ("track_size: %u\n", track_size);
297 debug_print ("track begin: %p\n", track);
298 debug_print ("track end: %p\n", track + track_len);
300 if (track_len > track_size)
301 return midi_error (__FUNCTION__, ": track size corrupt");
303 pytrack = PyList_New (0);
305 track_end = *track + track_len;
308 PyObject *pytime = PyInt_FromLong (0L);
309 while (*track < track_end)
311 long dt = get_variable_length_number(track, track_end);
312 PyObject *pyev = 0;
314 time += dt;
315 if (dt)
316 pytime = PyInt_FromLong (time);
318 pyev = read_event (track, track_end, pytime,
319 &running_status);
320 if (pyev)
321 PyList_Append (pytrack, pyev);
325 *track = track_end;
326 return pytrack;
330 static PyObject *
331 pymidi_parse_track (PyObject *self, PyObject *args)
333 unsigned char *track, *track_end;
334 unsigned long track_size, track_len;
336 PyObject * sobj = PyTuple_GetItem (args, 0);
338 debug_print ("%s", "\n");
339 if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
340 return 0;
342 if (track_size < 0)
343 return midi_error (__FUNCTION__, ": negative track size");
345 track_end = track + track_size;
347 return midi_parse_track (&track, track_end);
350 static PyObject *
351 midi_parse (unsigned char **midi,unsigned char *midi_end)
353 PyObject *pymidi = 0;
354 unsigned long header_len;
355 unsigned format, tracks;
356 int division;
357 int i;
359 debug_print ("%s", "\n");
361 /* Header */
362 header_len = get_number (midi, *midi + 4, 4);
365 if (header_len < 6)
366 return midi_error (__FUNCTION__, ": header too short");
368 format = get_number (midi, *midi + 2, 2);
369 tracks = get_number (midi, *midi + 2, 2);
371 if (tracks > 32)
372 return midi_error (__FUNCTION__, ": too many tracks");
374 division = get_number (midi, *midi + 2, 2) * 4;
377 if (division < 0)
378 /* return midi_error ("can't handle non-metrical time"); */
380 *midi += header_len - 6;
382 pymidi = PyList_New (0);
384 /* Tracks */
385 for (i = 0; i < tracks; i++)
386 PyList_Append (pymidi, midi_parse_track (midi, midi_end));
388 pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
389 pymidi);
390 return pymidi;
393 static PyObject *
394 pymidi_parse (PyObject *self, PyObject *args)
396 unsigned char *midi, *midi_end;
397 unsigned long midi_size, midi_len;
399 PyObject *sobj = PyTuple_GetItem (args, 0);
401 debug_print ("%s", "\n");
402 if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
403 return 0;
405 if (strcmp (midi, "MThd"))
406 return midi_error (__FUNCTION__, ": MThd expected");
408 midi += 4;
410 midi_end = midi + midi_size;
412 return midi_parse (&midi, midi_end);
416 static PyMethodDef MidiMethods[] =
418 {"parse", pymidi_parse, 1},
419 {"parse_track", pymidi_parse_track, 1},
420 {0, 0} /* Sentinel */
423 initmidi ()
425 PyObject *m, *d;
426 m = Py_InitModule ("midi", MidiMethods);
427 d = PyModule_GetDict (m);
429 Midi_error = PyString_FromString ("midi.error");
430 PyDict_SetItemString (d, "error", Midi_error);
431 add_constants (d);
432 Midi_warning = PyString_FromString ("midi.warning");
433 PyDict_SetItemString (d, "warning", Midi_warning);