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