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