]> git.donarmstrong.com Git - lilypond.git/blob - python/midi.c
2002-07-13 Han-Wen <hanwen@cs.uu.nl>
[lilypond.git] / python / midi.c
1 /*
2   midi.c -- implement Python midi parser module
3
4   source file of the GNU LilyPond music typesetter
5
6   (c)  2001 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7             Jan Nieuwenhuizen <janneke@gnu.org>
8
9 */
10
11 /*
12
13 python2
14 import midi
15 s = open ("s.midi").read ()
16 midi.parse_track (s)
17 midi.parse (s)
18
19 */
20
21 #include "config.h"
22
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
43
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
51
52 static PyObject *Midi_error;
53 static PyObject *Midi_warning;
54
55 static PyObject *
56 midi_error (char *s)
57 {
58   PyErr_SetString (Midi_error, s);
59   return 0;
60 }
61
62 static PyObject *
63 midi_warning (char *s)
64 {
65   PyErr_SetString (Midi_warning, s);
66   return 0;
67 }
68
69
70 typedef struct message {
71   unsigned char msg;
72   char * description;
73 } message_t;
74
75 message_t channelVoiceMessages[] = {
76   0x80, "NOTE_OFF",
77   0x90, "NOTE_ON",
78   0xA0, "POLYPHONIC_KEY_PRESSURE",
79   0xB0, "CONTROLLER_CHANGE",
80   0xC0, "PROGRAM_CHANGE",
81   0xD0, "CHANNEL_KEY_PRESSURE",
82   0xE0, "PITCH_BEND",
83   0,0
84 };
85
86 message_t channelModeMessages[] = {
87   0x78, "ALL_SOUND_OFF",
88   0x79, "RESET_ALL_CONTROLLERS",
89   0x7A, "LOCAL_CONTROL",
90   0x7B, "ALL_NOTES_OFF",
91   0x7C, "OMNI_MODE_OFF",
92   0x7D, "OMNI_MODE_ON",
93   0x7E, "MONO_MODE_ON",
94   0x7F, "POLY_MODE_ON",
95   0,0
96 };
97
98 message_t metaEvents[] = {
99   0x00, "SEQUENCE_NUMBER",
100   0x01, "TEXT_EVENT",
101   0x02, "COPYRIGHT_NOTICE",
102   0x03, "SEQUENCE_TRACK_NAME",
103   0x04, "INSTRUMENT_NAME",
104   0x05, "LYRIC",
105   0x06, "MARKER",
106   0x07, "CUE_POINT",
107   0x20, "MIDI_CHANNEL_PREFIX",
108   0x21, "MIDI_PORT",
109   0x2F, "END_OF_TRACK",
110   0x51, "SET_TEMPO",
111   0x54, "SMTPE_OFFSET",
112   0x58, "TIME_SIGNATURE",
113   0x59, "KEY_SIGNATURE",
114   0x7F, "SEQUENCER_SPECIFIC_META_EVENT",
115   0xFF, "META_EVENT",
116   0,0
117 };
118
119 void
120 add_constants (PyObject *dict)
121 {
122   message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
123   int i,j;
124   for ( j =0; p[j]; j++)
125     for ( i = 0; p[j][i].description; i++)
126       PyDict_SetItemString (dict, p[j][i].description, Py_BuildValue ("i", p[j][i].msg));
127 }
128
129 unsigned long int
130 get_number (unsigned char ** str, unsigned char * end_str, int length)
131 {
132   /* # MIDI uses big-endian for everything */
133   long sum = 0;
134   int i = 0;
135   
136   for (; i < length; i++)
137     sum = (sum << 8) + (unsigned char) (*str)[i];
138
139   *str += length;
140   debug_print ("%d:\n", sum);
141   return sum;
142 }
143
144 unsigned long int
145 get_variable_length_number (unsigned char **str, unsigned char * end_str)
146 {
147   long sum = 0;
148   int i = 0;
149   while (*str < end_str)
150     {
151       unsigned char x = **str;
152       (*str) ++;
153       sum = (sum << 7) + (x & 0x7F);
154       if (!(x & 0x80))
155         break;
156     }
157   debug_print ("%d:\n", sum);
158   return sum;
159 }
160
161 PyObject *
162 read_one_byte (unsigned char **track, unsigned char *end, 
163                unsigned char x)
164 {
165   PyObject *pyev = Py_BuildValue ("(i)", x);
166   debug_print ("%x:%s", x, "event\n");
167
168   return pyev;
169 }
170
171 PyObject *
172 read_two_bytes (unsigned char **track, unsigned char *end, 
173                 unsigned char x)
174 {
175   PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
176   *track += 1;
177   debug_print ("%x:%s", x, "event\n");
178   return pyev;
179 }
180
181 PyObject *
182 read_three_bytes (unsigned char **track, unsigned char *end, 
183                   unsigned char x)
184 {
185   PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
186                                   (*track)[1]);
187
188   *track += 2;
189   debug_print ("%x:%s", x, "event\n");
190   return pyev;
191 }
192
193 PyObject *
194 read_string (unsigned char **track, unsigned char *end) 
195 {
196   unsigned long length = get_variable_length_number (track, end);
197   if (length > end - *track)
198     length = end - *track;
199
200   *track += length;
201   return Py_BuildValue ("s#", ((*track) -length), length);
202 }
203
204 typedef PyObject* (*Read_midi_event)
205      (unsigned char **track, unsigned char *end, 
206       unsigned char x);
207
208
209 static PyObject *
210 read_f0_byte (unsigned char **track, unsigned char *end, 
211               unsigned char x)
212               
213 {
214   debug_print ("%x:%s", x, "event\n");
215   if (x == 0xff)
216     {
217       unsigned char z = (*track)[0 ];
218       *track += 1;
219       debug_print ("%x:%s", z, "f0-event\n");
220
221       return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
222     }
223
224   return Py_BuildValue ("(iO)", x, read_string (track, end));
225 }
226
227 Read_midi_event read_midi_event [16] =
228 {
229   read_one_byte,  //  0
230   read_one_byte,  // 10
231   read_one_byte,  // 20
232   read_one_byte,  // 30
233   read_one_byte,  // 40
234   read_one_byte,  // 50
235   read_one_byte,  // 60 data entry.
236   read_two_bytes, // 70 all notes off
237   read_three_bytes, // 80 note off
238   read_three_bytes, // 90 note on
239   read_three_bytes, // a0 poly aftertouch
240   read_three_bytes, // b0 control
241   read_two_bytes,  // c0 prog change
242   read_two_bytes, // d0 ch aftertouch
243   read_three_bytes, // e0 pitchwheel range 
244   read_f0_byte,   // f0
245 };
246
247
248 static PyObject *
249 read_event (unsigned char **track, unsigned char *end, PyObject *time,
250             unsigned char *running_status)
251 {
252   int rsb_skip = ((**track & 0x80)) ? 1 :0;
253
254   unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
255
256   PyObject * bare_event = 0;
257   debug_print ("%x:%s", x, "event\n");
258   *running_status = x;
259   *track += rsb_skip;
260   
261   //  printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
262   bare_event = (*read_midi_event[x >> 4]) (track, end, x);
263   if (bare_event)
264     return Py_BuildValue ("(OO)", time, bare_event);
265   else
266     return NULL;
267 }
268
269 static PyObject *
270 midi_parse_track (unsigned char **track, unsigned char *track_end)
271 {
272   unsigned int time = 0;
273   unsigned char running_status;
274   unsigned long track_len, track_size;
275   PyObject *pytrack = 0;
276
277   debug_print ("%s", "\n");
278   
279   track_size = track_end - *track;
280
281   debug_print ("%s", "\n");
282   if (strcmp (*track, "MTrk"))
283     return midi_error (__FUNCTION__ ": MTrk expected");
284   
285   *track += 4;
286
287   track_len = get_number (track, *track + 4, 4);
288
289
290   debug_print ("track_len: %u\n", track_len);
291   debug_print ("track_size: %u\n", track_size);
292   debug_print ("track begin: %p\n", track);
293   debug_print ("track end: %p\n", track + track_len);
294   
295   if (track_len > track_size)
296     return midi_error (__FUNCTION__ ": track size corrupt");
297
298   pytrack = PyList_New (0);
299
300   track_end = *track + track_len;
301
302   {  
303     PyObject *pytime = PyInt_FromLong (0L);
304     while (*track < track_end)
305       {
306         long dt = get_variable_length_number(track, track_end);
307         PyObject *pyev = 0;
308
309         time += dt;
310         if (dt)
311           pytime = PyInt_FromLong (time);
312
313         pyev = read_event (track, track_end, pytime,
314                            &running_status);
315         if (pyev)
316           PyList_Append (pytrack, pyev);
317       }
318   }
319   
320   *track = track_end;
321   return pytrack;
322 }
323
324
325 static PyObject *
326 pymidi_parse_track (PyObject *self, PyObject *args)
327 {
328   unsigned char *track, *track_end;
329   unsigned long track_size, track_len;
330
331   PyObject * sobj = PyTuple_GetItem (args, 0);
332
333   debug_print ("%s", "\n");
334   if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
335     return 0;
336
337   if (track_size < 0)
338     return midi_error (__FUNCTION__  ": negative track size");
339
340   track_end = track + track_size;
341   
342   return midi_parse_track (&track, track_end);
343 }
344
345 static PyObject *
346 midi_parse (unsigned char **midi,unsigned  char *midi_end)
347 {
348   PyObject *pymidi = 0;
349   unsigned long header_len;
350   unsigned format, tracks;
351   int division;
352   int i;
353   
354   debug_print ("%s", "\n");
355
356   /* Header */
357   header_len = get_number (midi, *midi + 4, 4);
358
359   
360   if (header_len < 6)
361     return midi_error (__FUNCTION__ ": header too short");
362     
363   format = get_number (midi, *midi + 2, 2);
364   tracks = get_number (midi, *midi + 2, 2);
365
366   if (tracks > 32)
367     return midi_error (__FUNCTION__ ": too many tracks");
368   
369   division = get_number (midi, *midi + 2, 2) * 4;
370
371
372   if (division < 0)
373     /* return midi_error ("can't handle non-metrical time"); */
374     ;
375   *midi += header_len - 6;
376
377   pymidi = PyList_New (0);
378
379   /* Tracks */
380   for (i = 0; i < tracks; i++)
381     PyList_Append (pymidi, midi_parse_track (midi, midi_end));
382
383   pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
384                           pymidi);
385   return pymidi;
386 }
387
388 static PyObject *
389 pymidi_parse (PyObject *self, PyObject *args)
390 {
391   unsigned char *midi, *midi_end;
392   unsigned long midi_size, midi_len;
393   
394   PyObject *sobj = PyTuple_GetItem (args, 0);
395
396   debug_print ("%s", "\n");
397   if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
398     return 0;
399
400   if (strcmp (midi, "MThd"))
401       return midi_error (__FUNCTION__ ": MThd expected");
402   
403   midi += 4;
404
405   midi_end = midi + midi_size;
406
407   return midi_parse (&midi, midi_end);
408 }
409
410
411 static PyMethodDef MidiMethods[] = 
412 {
413   {"parse",  pymidi_parse, 1},
414   {"parse_track",  pymidi_parse_track, 1},
415   {0, 0}        /* Sentinel */
416 };
417
418 initmidi ()
419 {
420   PyObject *m, *d;
421   m = Py_InitModule ("midi", MidiMethods);
422   d = PyModule_GetDict (m);
423   
424   Midi_error = PyString_FromString ("midi.error");
425   PyDict_SetItemString (d, "error", Midi_error);
426   add_constants (d);
427   Midi_warning = PyString_FromString ("midi.warning");
428   PyDict_SetItemString (d, "warning", Midi_warning);
429 }