]> git.donarmstrong.com Git - lilypond.git/blob - python/midi.c
Run grand-replace for 2010.
[lilypond.git] / python / midi.c
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 2001--2010 Han-Wen Nienhuys <hanwen@xs4all.nl>
5             Jan Nieuwenhuizen <janneke@gnu.org>
6
7
8   LilyPond is free software: you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation, either version 3 of the License, or
11   (at your option) any later version.
12
13   LilyPond is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /*
23
24 python
25 import midi
26 s = open ("s.midi").read ()
27 midi.parse_track (s)
28 midi.parse (s)
29
30
31 returns a MIDI file as the tuple
32
33  ((format, division), TRACKLIST) 
34
35 each track is an EVENTLIST, where EVENT is
36
37   (time, (type, ARG1, [ARG2]))
38
39 */
40
41 #include <Python.h>
42
43 /* PyMIDINIT_FUNC isn't defined in Python < 2.3 */
44 #ifndef PyMODINIT_FUNC
45 #       if defined(__cplusplus)
46 #               define PyMODINIT_FUNC extern "C" void
47 #       else /* __cplusplus */
48 #               define PyMODINIT_FUNC void
49 #       endif /* __cplusplus */
50 #endif
51
52 #if 0
53 int x = 0;
54 int *track = &x;
55 #define debug_print(f, args...) fprintf (stderr, "%s:%d: track: %p :" f, __FUNCTION__, __LINE__, *track, ##args)
56 #else
57 #define debug_print(f, args...)
58 #endif
59
60 static PyObject *Midi_error;
61 static PyObject *Midi_warning;
62
63 static PyObject *
64 midi_error (char const *func, char *s)
65 {
66   char *dest = (char*) malloc (sizeof (char) * (strlen (func) + strlen (s) + 1));
67   strcpy (dest, func);
68   strcat (dest, s);
69   PyErr_SetString (Midi_error, dest);
70   free (dest);
71   
72   return 0;
73 }
74
75 static PyObject *
76 midi_warning (char const *s)
77 {
78   PyErr_SetString (Midi_warning, s);
79   return 0;
80 }
81
82
83 typedef struct message {
84   unsigned char msg;
85   char * description;
86 } message_t;
87
88 message_t channelVoiceMessages[] = {
89   {0x80, "NOTE_OFF"},
90   {0x90, "NOTE_ON"},
91   {0xA0, "POLYPHONIC_KEY_PRESSURE"},
92   {0xB0, "CONTROLLER_CHANGE"},
93   {0xC0, "PROGRAM_CHANGE"},
94   {0xD0, "CHANNEL_KEY_PRESSURE"},
95   {0xE0, "PITCH_BEND"},
96   {0,0}
97 };
98
99 message_t channelModeMessages[] = {
100   {0x78, "ALL_SOUND_OFF"},
101   {0x79, "RESET_ALL_CONTROLLERS"},
102   {0x7A, "LOCAL_CONTROL"},
103   {0x7B, "ALL_NOTES_OFF"},
104   {0x7C, "OMNI_MODE_OFF"},
105   {0x7D, "OMNI_MODE_ON"},
106   {0x7E, "MONO_MODE_ON"},
107   {0x7F, "POLY_MODE_ON"},
108   {0,0}
109 };
110
111 message_t metaEvents[] = {
112   {0x00, "SEQUENCE_NUMBER"},
113   {0x01, "TEXT_EVENT"},
114   {0x02, "COPYRIGHT_NOTICE"},
115   {0x03, "SEQUENCE_TRACK_NAME"},
116   {0x04, "INSTRUMENT_NAME"},
117   {0x05, "LYRIC"},
118   {0x06, "MARKER"},
119   {0x07, "CUE_POINT"},
120   {0x20, "MIDI_CHANNEL_PREFIX"},
121   {0x21, "MIDI_PORT"},
122   {0x2F, "END_OF_TRACK"},
123   {0x51, "SET_TEMPO"},
124   {0x54, "SMTPE_OFFSET"},
125   {0x58, "TIME_SIGNATURE"},
126   {0x59, "KEY_SIGNATURE"},
127   {0x7F, "SEQUENCER_SPECIFIC_META_EVENT"},
128   {0xFF, "META_EVENT"},
129   {0,0}
130 };
131
132 void
133 add_constants (PyObject *dict)
134 {
135   message_t * p[] = {metaEvents, channelModeMessages, channelVoiceMessages ,0};
136   int i,j;
137   for ( j =0; p[j]; j++)
138     for ( i = 0; p[j][i].description; i++)
139       PyDict_SetItemString (dict, p[j][i].description, Py_BuildValue ("i", p[j][i].msg));
140 }
141
142 unsigned long int
143 get_number (unsigned char ** str, unsigned char * end_str, int length)
144 {
145   /* # MIDI uses big-endian for everything */
146   long sum = 0;
147   int i = 0;
148   
149   for (; i < length &&
150          ((*str) + i < end_str); i++)
151     sum = (sum << 8) + (unsigned char) (*str)[i];
152
153   *str += length;
154   debug_print ("%d:\n", sum);
155   return sum;
156 }
157
158 unsigned long int
159 get_variable_length_number (unsigned char **str, unsigned char * end_str)
160 {
161   long sum = 0;
162
163   while (*str < end_str)
164     {
165       unsigned char x = **str;
166       (*str) ++;
167       sum = (sum << 7) + (x & 0x7F);
168       if (!(x & 0x80))
169         break;
170     }
171   debug_print ("%d:\n", sum);
172   return sum;
173 }
174
175 PyObject *
176 read_one_byte (unsigned char **track, unsigned char *end, 
177                unsigned char x)
178 {
179   PyObject *pyev = Py_BuildValue ("(i)", x);
180   debug_print ("%x:%s", x, "event\n");
181
182   return pyev;
183 }
184
185 PyObject *
186 read_two_bytes (unsigned char **track, unsigned char *end, 
187                 unsigned char x)
188 {
189   PyObject *pyev = Py_BuildValue ("(ii)", x, (*track)[0]);
190   *track += 1;
191   debug_print ("%x:%s", x, "event\n");
192   return pyev;
193 }
194
195 PyObject *
196 read_three_bytes (unsigned char **track, unsigned char *end, 
197                   unsigned char x)
198 {
199   PyObject *pyev = Py_BuildValue ("(iii)", x, (*track)[0],
200                                   (*track)[1]);
201
202   *track += 2;
203   debug_print ("%x:%s", x, "event\n");
204   return pyev;
205 }
206
207 PyObject *
208 read_string (unsigned char **track, unsigned char *end) 
209 {
210   unsigned long length = get_variable_length_number (track, end);
211   if (length > end - *track)
212     length = end - *track;
213
214   *track += length;
215   return Py_BuildValue ("s#", ((*track) -length), length);
216 }
217
218 typedef PyObject* (*Read_midi_event)
219   (unsigned char **track, unsigned char *end, 
220    unsigned char x);
221
222
223 static PyObject *
224 read_f0_byte (unsigned char **track, unsigned char *end, 
225               unsigned char x)
226               
227 {
228   debug_print ("%x:%s", x, "event\n");
229   if (x == 0xff)
230     {
231       unsigned char z = (*track)[0 ];
232       *track += 1;
233       debug_print ("%x:%s", z, "f0-event\n");
234
235       return Py_BuildValue ("(iiO)", x, z, read_string (track, end));
236     }
237
238   return Py_BuildValue ("(iO)", x, read_string (track, end));
239 }
240
241 Read_midi_event read_midi_event [16] =
242 {
243   read_one_byte,  //  0
244   read_one_byte,  // 10
245   read_one_byte,  // 20
246   read_one_byte,  // 30
247   read_one_byte,  // 40
248   read_one_byte,  // 50
249   read_one_byte,  // 60 data entry.
250   read_two_bytes, // 70 all notes off
251   read_three_bytes, // 80 note off
252   read_three_bytes, // 90 note on
253   read_three_bytes, // a0 poly aftertouch
254   read_three_bytes, // b0 control
255   read_two_bytes,  // c0 prog change
256   read_two_bytes, // d0 ch aftertouch
257   read_three_bytes, // e0 pitchwheel range 
258   read_f0_byte,   // f0
259 };
260
261
262 static PyObject *
263 read_event (unsigned char **track, unsigned char *end, PyObject *time,
264             unsigned char *running_status)
265 {
266   int rsb_skip = ((**track & 0x80)) ? 1 :0;
267
268   unsigned char x = (rsb_skip) ? (*track)[0]: *running_status;
269
270   PyObject * bare_event = 0;
271   debug_print ("%x:%s", x, "event\n");
272   *running_status = x;
273   *track += rsb_skip;
274   
275   //  printf ("%x %x %d next %x\n", x, (*track)[0], rsb_skip, (*track)[1]);
276   bare_event = (*read_midi_event[x >> 4]) (track, end, x);
277   if (bare_event)
278     return Py_BuildValue ("(OO)", time, bare_event);
279   else
280     return NULL;
281 }
282
283 static PyObject *
284 midi_parse_track (unsigned char **track, unsigned char *track_end)
285 {
286   unsigned int time = 0;
287   unsigned long track_len, track_size;
288   PyObject *pytrack = 0;
289
290   debug_print ("%s", "\n");
291   
292   track_size = track_end - *track;
293
294   debug_print ("%s", "\n");
295   if (memcmp (*track, "MTrk", 4))
296     return midi_error (__FUNCTION__,  ": MTrk expected");
297   
298   *track += 4;
299
300   track_len = get_number (track, *track + 4, 4);
301
302
303   debug_print ("track_len: %u\n", track_len);
304   debug_print ("track_size: %u\n", track_size);
305   debug_print ("track begin: %p\n", track);
306   debug_print ("track end: %p\n", track + track_len);
307   
308   if (track_len > track_size)
309     return midi_error (__FUNCTION__,  ": track size corrupt");
310
311   pytrack = PyList_New (0);
312
313   if (*track + track_len < track_end)
314     track_end = *track + track_len;
315
316   {  
317     PyObject *pytime = PyInt_FromLong (0L);
318     unsigned char running_status = 0;
319         
320     while (*track < track_end)
321       {
322         long dt = get_variable_length_number(track, track_end);
323         PyObject *pyev = 0;
324
325         time += dt;
326         if (dt)
327           pytime = PyInt_FromLong (time);
328
329         pyev = read_event (track, track_end, pytime,
330                            &running_status);
331         if (pyev)
332           PyList_Append (pytrack, pyev);
333       }
334   }
335   
336   *track = track_end;
337   return pytrack;
338 }
339
340
341 static PyObject *
342 pymidi_parse_track (PyObject *self, PyObject *args)
343 {
344   unsigned char *track, *track_end;
345   unsigned long track_size;
346
347   debug_print ("%s", "\n");
348   if (!PyArg_ParseTuple (args, "s#", &track, &track_size))
349     return 0;
350
351   if (track_size < 0)
352     return midi_error (__FUNCTION__,   ": negative track size");
353
354   track_end = track + track_size;
355   
356   return midi_parse_track (&track, track_end);
357 }
358
359 static PyObject *
360 midi_parse (unsigned char **midi,unsigned  char *midi_end)
361 {
362   PyObject *pymidi = 0;
363   unsigned long header_len;
364   unsigned format, tracks;
365   int division;
366   int i;
367   
368   debug_print ("%s", "\n");
369
370   /* Header */
371   header_len = get_number (midi, *midi + 4, 4);
372   
373   if (header_len < 6)
374     return midi_error (__FUNCTION__,  ": header too short");
375     
376   format = get_number (midi, *midi + 2, 2);
377   tracks = get_number (midi, *midi + 2, 2);
378
379   if (tracks > 32)
380     return midi_error (__FUNCTION__,  ": too many tracks");
381   
382   division = get_number (midi, *midi + 2, 2) * 4;
383
384
385   if (division < 0)
386     /* return midi_error (cannot handle non-metrical time"); */
387     ;
388   *midi += header_len - 6;
389
390   pymidi = PyList_New (0);
391
392   /* Tracks */
393   for (i = 0; i < tracks; i++)
394     PyList_Append (pymidi, midi_parse_track (midi, midi_end));
395
396   pymidi = Py_BuildValue ("(OO)", Py_BuildValue ("(ii)", format, division),
397                           pymidi);
398   return pymidi;
399 }
400
401 static PyObject *
402 pymidi_parse (PyObject *self, PyObject *args)
403 {
404   unsigned char *midi, *midi_end;
405   unsigned long midi_size;
406   
407   debug_print ("%s", "\n");
408   if (!PyArg_ParseTuple (args, "s#", &midi, &midi_size))
409     return 0;
410
411   if (memcmp (midi, "MThd", 4))
412     return midi_error (__FUNCTION__,  ": MThd expected");
413   
414   midi += 4;
415
416   midi_end = midi + midi_size;
417
418   return midi_parse (&midi, midi_end);
419 }
420
421
422 static PyMethodDef MidiMethods[] = 
423 {
424   {"parse",  pymidi_parse, 1},
425   {"parse_track",  pymidi_parse_track, 1},
426   {0, 0}        /* Sentinel */
427 };
428
429 PyMODINIT_FUNC
430 initmidi (void)
431 {
432   PyObject *m, *d;
433   m = Py_InitModule ("midi", MidiMethods);
434   d = PyModule_GetDict (m);
435   
436   Midi_error = PyString_FromString ("midi.error");
437   PyDict_SetItemString (d, "error", Midi_error);
438   add_constants (d);
439   Midi_warning = PyString_FromString ("midi.warning");
440   PyDict_SetItemString (d, "warning", Midi_warning);
441
442   /*
443     FIXME.
444    */
445   (void) midi_warning;
446 }
447