]> git.donarmstrong.com Git - lilypond.git/blob - python/midi.c
* Another grand 2003 update.
[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 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 * func, char *s)
57 {
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);
63   
64   return 0;
65 }
66
67 static PyObject *
68 midi_warning (char *s)
69 {
70   PyErr_SetString (Midi_warning, s);
71   return 0;
72 }
73
74
75 typedef struct message {
76   unsigned char msg;
77   char * description;
78 } message_t;
79
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
89 };
90
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",
100   0,0
101 };
102
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",
121   0,0
122 };
123
124 void
125 add_constants (PyObject *dict)
126 {
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));
132 }
133
134 unsigned long int
135 get_number (unsigned char ** str, unsigned char * end_str, int length)
136 {
137   /* # MIDI uses big-endian for everything */
138   long sum = 0;
139   int i = 0;
140   
141   for (; i < length; i++)
142     sum = (sum << 8) + (unsigned char) (*str)[i];
143
144   *str += length;
145   debug_print ("%d:\n", sum);
146   return sum;
147 }
148
149 unsigned long int
150 get_variable_length_number (unsigned char **str, unsigned char * end_str)
151 {
152   long sum = 0;
153   int i = 0;
154   while (*str < end_str)
155     {
156       unsigned char x = **str;
157       (*str) ++;
158       sum = (sum << 7) + (x & 0x7F);
159       if (!(x & 0x80))
160         break;
161     }
162   debug_print ("%d:\n", sum);
163   return sum;
164 }
165
166 PyObject *
167 read_one_byte (unsigned char **track, unsigned char *end, 
168                unsigned char x)
169 {
170   PyObject *pyev = Py_BuildValue ("(i)", x);
171   debug_print ("%x:%s", x, "event\n");
172
173   return pyev;
174 }
175
176 PyObject *
177 read_two_bytes (unsigned char **track, unsigned char *end, 
178                 unsigned char x)
179 {
180   PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
181   *track += 1;
182   debug_print ("%x:%s", x, "event\n");
183   return pyev;
184 }
185
186 PyObject *
187 read_three_bytes (unsigned char **track, unsigned char *end, 
188                   unsigned char x)
189 {
190   PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
191                                   (*track)[1]);
192
193   *track += 2;
194   debug_print ("%x:%s", x, "event\n");
195   return pyev;
196 }
197
198 PyObject *
199 read_string (unsigned char **track, unsigned char *end) 
200 {
201   unsigned long length = get_variable_length_number (track, end);
202   if (length > end - *track)
203     length = end - *track;
204
205   *track += length;
206   return Py_BuildValue ("s#", ((*track) -length), length);
207 }
208
209 typedef PyObject* (*Read_midi_event)
210      (unsigned char **track, unsigned char *end, 
211       unsigned char x);
212
213
214 static PyObject *
215 read_f0_byte (unsigned char **track, unsigned char *end, 
216               unsigned char x)
217               
218 {
219   debug_print ("%x:%s", x, "event\n");
220   if (x == 0xff)
221     {
222       unsigned char z = (*track)[0 ];
223       *track += 1;
224       debug_print ("%x:%s", z, "f0-event\n");
225
226       return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
227     }
228
229   return Py_BuildValue ("(iO)", x, read_string (track, end));
230 }
231
232 Read_midi_event read_midi_event [16] =
233 {
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
250 };
251
252
253 static PyObject *
254 read_event (unsigned char **track, unsigned char *end, PyObject *time,
255             unsigned char *running_status)
256 {
257   int rsb_skip = ((**track & 0x80)) ? 1 :0;
258
259   unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
260
261   PyObject * bare_event = 0;
262   debug_print ("%x:%s", x, "event\n");
263   *running_status = x;
264   *track += rsb_skip;
265   
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;
272 }
273
274 static PyObject *
275 midi_parse_track (unsigned char **track, unsigned char *track_end)
276 {
277   unsigned int time = 0;
278   unsigned char running_status;
279   unsigned long track_len, track_size;
280   PyObject *pytrack = 0;
281
282   debug_print ("%s", "\n");
283   
284   track_size = track_end - *track;
285
286   debug_print ("%s", "\n");
287   if (strcmp (*track, "MTrk"))
288     return midi_error (__FUNCTION__,  ": MTrk expected");
289   
290   *track += 4;
291
292   track_len = get_number (track, *track + 4, 4);
293
294
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);
299   
300   if (track_len > track_size)
301     return midi_error (__FUNCTION__,  ": track size corrupt");
302
303   pytrack = PyList_New (0);
304
305   track_end = *track + track_len;
306
307   {  
308     PyObject *pytime = PyInt_FromLong (0L);
309     while (*track < track_end)
310       {
311         long dt = get_variable_length_number(track, track_end);
312         PyObject *pyev = 0;
313
314         time += dt;
315         if (dt)
316           pytime = PyInt_FromLong (time);
317
318         pyev = read_event (track, track_end, pytime,
319                            &running_status);
320         if (pyev)
321           PyList_Append (pytrack, pyev);
322       }
323   }
324   
325   *track = track_end;
326   return pytrack;
327 }
328
329
330 static PyObject *
331 pymidi_parse_track (PyObject *self, PyObject *args)
332 {
333   unsigned char *track, *track_end;
334   unsigned long track_size, track_len;
335
336   PyObject * sobj = PyTuple_GetItem (args, 0);
337
338   debug_print ("%s", "\n");
339   if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
340     return 0;
341
342   if (track_size < 0)
343     return midi_error (__FUNCTION__,   ": negative track size");
344
345   track_end = track + track_size;
346   
347   return midi_parse_track (&track, track_end);
348 }
349
350 static PyObject *
351 midi_parse (unsigned char **midi,unsigned  char *midi_end)
352 {
353   PyObject *pymidi = 0;
354   unsigned long header_len;
355   unsigned format, tracks;
356   int division;
357   int i;
358   
359   debug_print ("%s", "\n");
360
361   /* Header */
362   header_len = get_number (midi, *midi + 4, 4);
363
364   
365   if (header_len < 6)
366     return midi_error (__FUNCTION__,  ": header too short");
367     
368   format = get_number (midi, *midi + 2, 2);
369   tracks = get_number (midi, *midi + 2, 2);
370
371   if (tracks > 32)
372     return midi_error (__FUNCTION__,  ": too many tracks");
373   
374   division = get_number (midi, *midi + 2, 2) * 4;
375
376
377   if (division < 0)
378     /* return midi_error ("can't handle non-metrical time"); */
379     ;
380   *midi += header_len - 6;
381
382   pymidi = PyList_New (0);
383
384   /* Tracks */
385   for (i = 0; i < tracks; i++)
386     PyList_Append (pymidi, midi_parse_track (midi, midi_end));
387
388   pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
389                           pymidi);
390   return pymidi;
391 }
392
393 static PyObject *
394 pymidi_parse (PyObject *self, PyObject *args)
395 {
396   unsigned char *midi, *midi_end;
397   unsigned long midi_size, midi_len;
398   
399   PyObject *sobj = PyTuple_GetItem (args, 0);
400
401   debug_print ("%s", "\n");
402   if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
403     return 0;
404
405   if (strcmp (midi, "MThd"))
406       return midi_error (__FUNCTION__,  ": MThd expected");
407   
408   midi += 4;
409
410   midi_end = midi + midi_size;
411
412   return midi_parse (&midi, midi_end);
413 }
414
415
416 static PyMethodDef MidiMethods[] = 
417 {
418   {"parse",  pymidi_parse, 1},
419   {"parse_track",  pymidi_parse_track, 1},
420   {0, 0}        /* Sentinel */
421 };
422
423 initmidi ()
424 {
425   PyObject *m, *d;
426   m = Py_InitModule ("midi", MidiMethods);
427   d = PyModule_GetDict (m);
428   
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);
434 }