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