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