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