]> git.donarmstrong.com Git - lilypond.git/blob - modules/midi.c
release: 1.5.17
[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));
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       if (z == 0x2f && (*track)[0] == 0x00) /* end of track */
220         {
221           *track += 1;
222           return 0;
223         }
224       else
225         return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
226     }
227
228   return Py_BuildValue ("(iO)", x, read_string (track, end));
229 }
230
231 Read_midi_event read_midi_event [16] =
232 {
233   read_one_byte,  //  0
234   read_one_byte,  // 10
235   read_one_byte,  // 20
236   read_one_byte,  // 30
237   read_one_byte,  // 40
238   read_one_byte,  // 50
239   read_one_byte,  // 60 data entry.
240   read_two_bytes, // 70 all notes off
241   read_three_bytes, // 80 note off
242   read_three_bytes, // 90 note on
243   read_three_bytes, // a0 poly aftertouch
244   read_three_bytes, // b0 control
245   read_two_bytes,  // c0 prog change
246   read_two_bytes, // d0 ch aftertouch
247   read_three_bytes, // e0 pitchwheel range 
248   read_f0_byte,   // f0
249 };
250
251
252 static PyObject *
253 read_event (unsigned char **track, unsigned char *end, PyObject *time,
254             unsigned char *running_status)
255 {
256   int rsb_skip = ((**track & 0x80)) ? 1 :0;
257
258   unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
259
260   PyObject * bare_event = 0;
261   debug_print ("%x:%s", x, "event\n");
262   *running_status = x;
263   *track += rsb_skip;
264   
265   //  printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
266   bare_event = (*read_midi_event[x >> 4]) (track, end, x);
267   if (bare_event)
268     return Py_BuildValue ("(OO)", time, bare_event);
269   else
270     return NULL;
271 }
272
273 static PyObject *
274 midi_parse_track (unsigned char **track, unsigned char *track_end)
275 {
276   unsigned int time = 0;
277   unsigned char running_status;
278   unsigned long track_len, track_size;
279   PyObject *pytrack = 0;
280
281   debug_print ("%s", "\n");
282   
283   track_size = track_end - *track;
284
285   debug_print ("%s", "\n");
286   if (strcmp (*track, "MTrk"))
287     return midi_error (__FUNCTION__ ": MTrk expected");
288   
289   *track += 4;
290
291   track_len = get_number (track, *track + 4, 4);
292
293
294   debug_print ("track_len: %u\n", track_len);
295   debug_print ("track_size: %u\n", track_size);
296   debug_print ("track begin: %p\n", track);
297   debug_print ("track end: %p\n", track + track_len);
298   
299   if (track_len > track_size)
300     return midi_error (__FUNCTION__ ": track size corrupt");
301
302   pytrack = PyList_New (0);
303
304   track_end = *track + track_len;
305
306   {  
307     PyObject *pytime = PyInt_FromLong (0L);
308     while (*track < track_end)
309       {
310         long dt = get_variable_length_number(track, track_end);
311         PyObject *pyev = 0;
312
313         time += dt;
314         if (dt)
315           pytime = PyInt_FromLong (time);
316
317         pyev = read_event (track, track_end, pytime,
318                            &running_status);
319         if (pyev)
320           PyList_Append (pytrack, pyev);
321       }
322   }
323   
324   *track = track_end;
325   return pytrack;
326 }
327
328
329 static PyObject *
330 pymidi_parse_track (PyObject *self, PyObject *args)
331 {
332   unsigned char *track, *track_end;
333   unsigned long track_size, track_len;
334
335   PyObject * sobj = PyTuple_GetItem (args, 0);
336
337   debug_print ("%s", "\n");
338   if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
339     return 0;
340
341   if (track_size < 0)
342     return midi_error (__FUNCTION__  ": negative track size");
343
344   track_end = track + track_size;
345   
346   return midi_parse_track (&track, track_end);
347 }
348
349 static PyObject *
350 midi_parse (unsigned char **midi,unsigned  char *midi_end)
351 {
352   PyObject *pymidi = 0;
353   unsigned long header_len;
354   unsigned format, tracks;
355   int division;
356   int i;
357   
358   debug_print ("%s", "\n");
359
360   /* Header */
361   header_len = get_number (midi, *midi + 4, 4);
362
363   
364   if (header_len < 6)
365     return midi_error (__FUNCTION__ ": header too short");
366     
367   format = get_number (midi, *midi + 2, 2);
368   tracks = get_number (midi, *midi + 2, 2);
369
370   if (tracks > 32)
371     return midi_error (__FUNCTION__ ": too many tracks");
372   
373   division = get_number (midi, *midi + 2, 2) * 4;
374
375
376   if (division < 0)
377     /* return midi_error ("can't handle non-metrical time"); */
378     ;
379   *midi += header_len - 6;
380
381   pymidi = PyList_New (0);
382
383   /* Tracks */
384   for (i = 0; i < tracks; i++)
385     PyList_Append (pymidi, midi_parse_track (midi, midi_end));
386
387   pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
388                           pymidi);
389   return pymidi;
390 }
391
392 static PyObject *
393 pymidi_parse (PyObject *self, PyObject *args)
394 {
395   unsigned char *midi, *midi_end;
396   unsigned long midi_size, midi_len;
397   
398   PyObject *sobj = PyTuple_GetItem (args, 0);
399
400   debug_print ("%s", "\n");
401   if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
402     return 0;
403
404   if (strcmp (midi, "MThd"))
405       return midi_error (__FUNCTION__ ": MThd expected");
406   
407   midi += 4;
408
409   midi_end = midi + midi_size;
410
411   return midi_parse (&midi, midi_end);
412 }
413
414
415 static PyMethodDef MidiMethods[] = 
416 {
417   {"parse",  pymidi_parse, 1},
418   {"parse_track",  pymidi_parse_track, 1},
419   {0, 0}        /* Sentinel */
420 };
421
422 initmidi ()
423 {
424   PyObject *m, *d;
425   m = Py_InitModule ("midi", MidiMethods);
426   d = PyModule_GetDict (m);
427   
428   Midi_error = PyString_FromString ("midi.error");
429   PyDict_SetItemString (d, "error", Midi_error);
430   add_constants (d);
431   Midi_warning = PyString_FromString ("midi.warning");
432   PyDict_SetItemString (d, "warning", Midi_warning);
433 }