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