File: cmidi.c

package info (click to toggle)
csound 1%3A6.18.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 63,220 kB
  • sloc: ansic: 192,643; cpp: 14,149; javascript: 9,654; objc: 9,181; python: 3,376; java: 3,337; sh: 1,840; yacc: 1,255; xml: 985; perl: 635; lisp: 411; tcl: 341; lex: 217; makefile: 128
file content (314 lines) | stat: -rw-r--r-- 9,778 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
    cmidi.c:

    Copyright (C) 2011 V Lazzarini

    This file is part of Csound.

    The Csound Library is free software; you can redistribute it
    and/or modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    Csound is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with Csound; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
    02110-1301 USA
*/

/* Realtime MIDI using coremidi */


#include <CoreMIDI/CoreMIDI.h>
#include <CoreAudio/HostTime.h>
#include <CoreFoundation/CoreFoundation.h>
#include "csdl.h"                               /*      CMIDI.C         */
#include "midiops.h"


/* MIDI message queue size */
#define DSIZE 4096

/* MIDI data struct */
typedef struct {
  Byte status;
  Byte data1;
  Byte data2;
  Byte flag;
} MIDIdata;

/* user data for MIDI callbacks */
typedef struct _cdata {
  MIDIdata *mdata;
  int p; int q;
  MIDIClientRef mclient;
} cdata;


/* coremidi callback, called when MIDI data is available */
void ReadProc(const MIDIPacketList *pktlist, void *refcon, void *srcConnRefCon)
{
    IGN(srcConnRefCon);
    cdata *data = (cdata *)refcon;
    MIDIdata *mdata = data->mdata;
    int *p = &data->p;
    UInt32 i, j;
    MIDIPacket *packet = &((MIDIPacketList *)pktlist)->packet[0];
    Byte *curpack;

    for (i = 0; i < pktlist->numPackets; i++) {
      for (j=0; j < packet->length; j+=3) {
        curpack = packet->data+j;
        memcpy(&mdata[*p], curpack, 3);
        mdata[*p].flag = 1;
        (*p)++;
        if (*p == DSIZE) *p = 0;
      }
      packet = MIDIPacketNext(packet);
    }

}


static int listDevices(CSOUND *csound, CS_MIDIDEVICE *list, int isOutput)
{
    int k, endpoints;
    MIDIEndpointRef endpoint;
    CFStringRef name = NULL;
    CFStringEncoding defaultEncoding = CFStringGetSystemEncoding();
    char tmp[64];
    char *drv = (char*) (csound->QueryGlobalVariable(csound, "_RTMIDI"));
    if (isOutput) return 0;
    endpoints = MIDIGetNumberOfSources();
    if (list == NULL) return endpoints;
    for(k=0; k < endpoints; k++) {
      endpoint = MIDIGetSource(k);
      MIDIObjectGetStringProperty(endpoint, kMIDIPropertyName, &name);
      const char *sn = CFStringGetCStringPtr(name, defaultEncoding);
      if(sn != NULL)
       strncpy(list[k].device_name, sn, 63);
      snprintf(tmp, 64, "%d", k);
      strncpy(list[k].device_id, tmp, 63);
      list[k].isOutput = isOutput;
      strcpy(list[k].interface_name, "");
      strncpy(list[k].midi_module, drv, 63);
    }
    if (name) CFRelease(name);
    return endpoints;
}


/* csound MIDI input open callback, sets the device for input */
static int MidiInDeviceOpen(CSOUND *csound, void **userData, const char *dev)
{
    int k, endpoints;
    CFStringRef name = NULL, cname = NULL, pname = NULL;
    CFStringEncoding defaultEncoding = CFStringGetSystemEncoding();
    MIDIClientRef mclient = (MIDIClientRef) 0;
    MIDIPortRef mport =  (MIDIPortRef) 0;
    MIDIEndpointRef endpoint;
    MIDIdata *mdata = (MIDIdata *) csound->Malloc(csound, DSIZE*sizeof(MIDIdata));
    OSStatus ret;
    cdata *refcon = (cdata *) csound->Malloc(csound, sizeof(cdata));
    memset(mdata, 0, sizeof(MIDIdata)*DSIZE);
    refcon->mdata = mdata;
    refcon->p = 0;
    refcon->q = 0;
    /* MIDI client */
    cname = CFStringCreateWithCString(NULL, "my client", defaultEncoding);
    ret = MIDIClientCreate(cname, NULL, NULL, &mclient);
    if (!ret){
      /* MIDI input port */
      pname = CFStringCreateWithCString(NULL, "inport", defaultEncoding);
      ret = MIDIInputPortCreate(mclient, pname, ReadProc, refcon, &mport);
      if (!ret){
        /* sources, we connect to all available input sources */
        endpoints = MIDIGetNumberOfSources();
       OPARMS O;
       csound->GetOParms(csound, &O);
       if(O.msglevel || O.odebug)
        csound->Message(csound, Str("%d MIDI sources in system\n"), endpoints);
        if (!strcmp(dev,"all")) {
          if(O.msglevel || O.odebug)
           csound->Message(csound, "%s", Str("receiving from all sources\n"));
          for(k=0; k < endpoints; k++){
            endpoint = MIDIGetSource(k);
            long srcRefCon = (long) endpoint;
            MIDIPortConnectSource(mport, endpoint, (void *) srcRefCon);
            MIDIObjectGetStringProperty(endpoint, kMIDIPropertyName, &name);
            if(O.msglevel || O.odebug)
             csound->Message(csound, Str("connecting midi device %d: %s\n"), k,
                            CFStringGetCStringPtr(name, defaultEncoding));
          }
        }
        else{
          k = atoi(dev);
          if (k < endpoints){
            endpoint = MIDIGetSource(k);
            long srcRefCon = (long) endpoint;
            MIDIPortConnectSource(mport, endpoint, (void *) srcRefCon);
            MIDIObjectGetStringProperty(endpoint, kMIDIPropertyName, &name);
            if(O.msglevel || O.odebug)
             csound->Message(csound, Str("connecting midi device %d: %s\n"), k,
                            CFStringGetCStringPtr(name, defaultEncoding));
          }
          else {
            if(O.msglevel || O.odebug)
            csound->Message(csound,
                            Str("MIDI device number %d is out-of-range, "
                                "not connected\n"), k);
          }
        }

      }
    }
    refcon->mclient = mclient;
    *userData = (void*) refcon;
    if (name) CFRelease(name);
    if (pname) CFRelease(pname);
    if (cname) CFRelease(cname);
    /* report success */
    return 0;
}

static int MidiOutDeviceOpen(CSOUND *csound, void **userData, const char *dev)
{
     IGN(userData); IGN(dev);
    /*stub for the moment */
    csound->Message(csound, "%s", Str("output not implemented yet in CoreMIDI\n"));
    return 0;
}

/* used to distinguish between 1 and 2-byte messages */
static  const   int     datbyts[8] = { 2, 2, 2, 2, 1, 1, 2, 0 };

/* csound MIDI read callback, called every k-cycle */
static int MidiDataRead(CSOUND *csound, void *userData,
                         unsigned char *mbuf, int nbytes)
{
  IGN(csound);
    cdata *data = (cdata *)userData;
    MIDIdata *mdata = data->mdata;
    int *q = &data->q, st, d1, d2, n = 0;

    /* check if there is new data in circular queue */
    while (mdata[*q].flag) {
      st = (int) mdata[*q].status;
      d1 = (int) mdata[*q].data1;
      d2 = (int) mdata[*q].data2;

      if (st < 0x80) goto next;

      if (st >= 0xF0 &&
          !(st == 0xF8 || st == 0xFA || st == 0xFB ||
            st == 0xFC || st == 0xFF)) goto next;

      nbytes -= (datbyts[(st - 0x80) >> 4] + 1);
      if (nbytes < 0) break;

      /* write to csound midi buffer */
      n += (datbyts[(st - 0x80) >> 4] + 1);
      switch (datbyts[(st - 0x80) >> 4]) {
      case 0:
        *mbuf++ = (unsigned char) st;
        break;
      case 1:
        *mbuf++ = (unsigned char) st;
        *mbuf++ = (unsigned char) d1;
        break;
      case 2:
        *mbuf++ = (unsigned char) st;
        *mbuf++ = (unsigned char) d1;
        *mbuf++ = (unsigned char) d2;
        break;
      }
      /* mark as read */
    next:
      mdata[*q].flag = 0;
      (*q)++;
      if (*q==DSIZE) *q = 0;

    }

    /* return the number of bytes read */
    return n;
}

/* csound close device callback */
static int MidiInDeviceClose(CSOUND *csound, void *userData)
{
    cdata * data = (cdata *)userData;
    if (data != NULL) {
      MIDIClientDispose(data->mclient);
      csound->Free(csound, data->mdata);
      csound->Free(csound, data);
    }
    return 0;
}

static int MidiDataWrite(CSOUND *csound, void *userData,
                          const unsigned char *mbuf, int nbytes)
{
    /* stub at the moment */
    /*
    */
  IGN(csound); IGN(userData); IGN(mbuf); IGN(nbytes);
    return nbytes;
}



static int MidiOutDeviceClose(CSOUND *csound, void *userData)
{
    /* stub at the moment */
  IGN(csound); IGN(userData);
    return 0;
}

/* module interface functions */

PUBLIC int csoundModuleCreate(CSOUND *csound)
{
    /* nothing to do, report success */
    //csound->Message(csound, "%s",
    //                Str("CoreMIDI real time MIDI plugin for Csound\n"));
    IGN(csound);
    return 0;
}

PUBLIC int csoundModuleInit(CSOUND *csound)
{
    char    *drv;
    csound->module_list_add(csound, "coremidi", "midi");
    drv = (char*) (csound->QueryGlobalVariable(csound, "_RTMIDI"));
    if (drv == NULL)
      return 0;
    if (!(strcmp(drv, "coremidi") == 0 || strcmp(drv, "CoreMidi") == 0 ||
          strcmp(drv, "CoreMIDI") == 0 || strcmp(drv, "cm") == 0))
      return 0;
    {
    OPARMS O;
    csound->GetOParms(csound, &O);
    if(O.msglevel || O.odebug)
     csound->Message(csound, "%s", Str("rtmidi: CoreMIDI module enabled\n"));
    }
    csound->SetExternalMidiInOpenCallback(csound, MidiInDeviceOpen);
    csound->SetExternalMidiReadCallback(csound, MidiDataRead);
    csound->SetExternalMidiInCloseCallback(csound, MidiInDeviceClose);
    csound->SetExternalMidiOutOpenCallback(csound, MidiOutDeviceOpen);
    csound->SetExternalMidiWriteCallback(csound, MidiDataWrite);
    csound->SetExternalMidiOutCloseCallback(csound, MidiOutDeviceClose);
    csound->SetMIDIDeviceListCallback(csound,listDevices);
    return 0;
}

PUBLIC int csoundModuleInfo(void)
{
    /* does not depend on MYFLT type */
    return ((CS_APIVERSION << 16) + (CS_APISUBVER << 8));
}