jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

427 lines
15KB

  1. /*
  2. Copyright (C) 2009 Grame
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  14. */
  15. #include "JackCoreMidiDriver.h"
  16. #include "JackGraphManager.h"
  17. #include "JackServer.h"
  18. #include "JackEngineControl.h"
  19. #include "JackDriverLoader.h"
  20. #include <mach/mach_time.h>
  21. #include <assert.h>
  22. #include <iostream>
  23. #include <sstream>
  24. #include <string>
  25. namespace Jack
  26. {
  27. static MIDITimeStamp MIDIGetCurrentHostTime()
  28. {
  29. return mach_absolute_time();
  30. }
  31. void JackCoreMidiDriver::ReadProcAux(const MIDIPacketList *pktlist, jack_ringbuffer_t* ringbuffer)
  32. {
  33. // Write the number of packets
  34. size_t size = jack_ringbuffer_write(ringbuffer, (char*)&pktlist->numPackets, sizeof(UInt32));
  35. if (size != sizeof(UInt32)) {
  36. jack_error("ReadProc : ring buffer is full, skip events...");
  37. return;
  38. }
  39. for (unsigned int i = 0; i < pktlist->numPackets; ++i) {
  40. MIDIPacket *packet = (MIDIPacket *)pktlist->packet;
  41. // TODO : use timestamp
  42. // Write length of each packet first
  43. size = jack_ringbuffer_write(ringbuffer, (char*)&packet->length, sizeof(UInt16));
  44. if (size != sizeof(UInt16)) {
  45. jack_error("ReadProc : ring buffer is full, skip events...");
  46. return;
  47. }
  48. // Write event actual data
  49. size = jack_ringbuffer_write(ringbuffer, (char*)packet->data, packet->length);
  50. if (size != packet->length) {
  51. jack_error("ReadProc : ring buffer is full, skip events...");
  52. return;
  53. }
  54. packet = MIDIPacketNext(packet);
  55. }
  56. }
  57. void JackCoreMidiDriver::ReadProc(const MIDIPacketList *pktlist, void *refCon, void *connRefCon)
  58. {
  59. jack_ringbuffer_t* ringbuffer = (jack_ringbuffer_t*)connRefCon;
  60. ReadProcAux(pktlist, ringbuffer);
  61. }
  62. void JackCoreMidiDriver::ReadVirtualProc(const MIDIPacketList *pktlist, void *refCon, void *connRefCon)
  63. {
  64. jack_ringbuffer_t* ringbuffer = (jack_ringbuffer_t*)refCon;
  65. ReadProcAux(pktlist, ringbuffer);
  66. }
  67. void JackCoreMidiDriver::NotifyProc(const MIDINotification *message, void *refCon)
  68. {
  69. jack_info("NotifyProc %d", message->messageID);
  70. }
  71. JackCoreMidiDriver::JackCoreMidiDriver(const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table)
  72. : JackMidiDriver(name, alias, engine, table), fMidiClient(NULL), fInputPort(NULL), fOutputPort(NULL), fRealCaptureChannels(0), fRealPlaybackChannels(0)
  73. {}
  74. JackCoreMidiDriver::~JackCoreMidiDriver()
  75. {}
  76. int JackCoreMidiDriver::Open(bool capturing,
  77. bool playing,
  78. int inchannels,
  79. int outchannels,
  80. bool monitor,
  81. const char* capture_driver_name,
  82. const char* playback_driver_name,
  83. jack_nframes_t capture_latency,
  84. jack_nframes_t playback_latency)
  85. {
  86. OSStatus err;
  87. CFStringRef coutputStr;
  88. std::string str;
  89. // Get real input/output number
  90. fRealCaptureChannels = MIDIGetNumberOfSources();
  91. fRealPlaybackChannels = MIDIGetNumberOfDestinations();
  92. // Generic JackMidiDriver Open
  93. if (JackMidiDriver::Open(capturing, playing, inchannels + fRealCaptureChannels, outchannels + fRealPlaybackChannels, monitor, capture_driver_name, playback_driver_name, capture_latency, playback_latency) != 0)
  94. return -1;
  95. coutputStr = CFStringCreateWithCString(0, "JackMidi", CFStringGetSystemEncoding());
  96. err = MIDIClientCreate(coutputStr, NotifyProc, this, &fMidiClient);
  97. CFRelease(coutputStr);
  98. if (!fMidiClient) {
  99. jack_error("Cannot create CoreMidi client");
  100. goto error;
  101. }
  102. err = MIDIInputPortCreate(fMidiClient, CFSTR("Input port"), ReadProc, this, &fInputPort);
  103. if (!fInputPort) {
  104. jack_error("Cannot open CoreMidi in port\n");
  105. goto error;
  106. }
  107. err = MIDIOutputPortCreate(fMidiClient, CFSTR("Output port"), &fOutputPort);
  108. if (!fOutputPort) {
  109. jack_error("Cannot open CoreMidi out port\n");
  110. goto error;
  111. }
  112. fMidiDestination = new MIDIEndpointRef[inchannels + fRealCaptureChannels];
  113. assert(fMidiDestination);
  114. // Virtual input
  115. for (int i = 0; i < inchannels; i++) {
  116. std::stringstream num;
  117. num << i;
  118. str = "JackMidi" + num.str();
  119. coutputStr = CFStringCreateWithCString(0, str.c_str(), CFStringGetSystemEncoding());
  120. err = MIDIDestinationCreate(fMidiClient, coutputStr, ReadVirtualProc, fRingBuffer[i], &fMidiDestination[i]);
  121. CFRelease(coutputStr);
  122. if (!fMidiDestination[i]) {
  123. jack_error("Cannot create CoreMidi destination");
  124. goto error;
  125. }
  126. }
  127. // Real input
  128. for (int i = 0; i < fRealCaptureChannels; i++) {
  129. fMidiDestination[i + inchannels] = MIDIGetSource(i);
  130. MIDIPortConnectSource(fInputPort, fMidiDestination[i + inchannels], fRingBuffer[i + inchannels]);
  131. }
  132. fMidiSource = new MIDIEndpointRef[outchannels + fRealPlaybackChannels];
  133. assert(fMidiSource);
  134. // Virtual output
  135. for (int i = 0; i < outchannels; i++) {
  136. std::stringstream num;
  137. num << i;
  138. str = "JackMidi" + num.str();
  139. coutputStr = CFStringCreateWithCString(0, str.c_str(), CFStringGetSystemEncoding());
  140. err = MIDISourceCreate(fMidiClient, coutputStr, &fMidiSource[i]);
  141. CFRelease(coutputStr);
  142. if (!fMidiSource[i]) {
  143. jack_error("Cannot create CoreMidi source");
  144. goto error;
  145. }
  146. }
  147. // Real output
  148. for (int i = 0; i < fRealPlaybackChannels; i++) {
  149. fMidiSource[i + outchannels] = MIDIGetDestination(i);
  150. }
  151. return 0;
  152. error:
  153. Close();
  154. return -1;
  155. }
  156. int JackCoreMidiDriver::Close()
  157. {
  158. if (fInputPort)
  159. MIDIPortDispose(fInputPort);
  160. if (fOutputPort)
  161. MIDIPortDispose(fOutputPort);
  162. // Only dispose "virtual" endpoints
  163. for (int i = 0; i < fCaptureChannels - fRealCaptureChannels; i++) {
  164. if (fMidiDestination)
  165. MIDIEndpointDispose(fMidiDestination[i]);
  166. }
  167. delete[] fMidiDestination;
  168. // Only dispose "virtual" endpoints
  169. for (int i = 0; i < fPlaybackChannels - fRealPlaybackChannels; i++) {
  170. if (fMidiSource[i])
  171. MIDIEndpointDispose(fMidiSource[i]);
  172. }
  173. delete[] fMidiSource;
  174. if (fMidiClient)
  175. MIDIClientDispose(fMidiClient);
  176. return 0;
  177. }
  178. int JackCoreMidiDriver::Attach()
  179. {
  180. OSStatus err;
  181. JackPort* port;
  182. CFStringRef pname;
  183. jack_port_id_t port_index;
  184. char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  185. char endpoint_name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  186. char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  187. unsigned long port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  188. int i;
  189. jack_log("JackCoreMidiDriver::Attach fBufferSize = %ld fSampleRate = %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  190. for (i = 0; i < fCaptureChannels; i++) {
  191. err = MIDIObjectGetStringProperty(fMidiDestination[i], kMIDIPropertyName, &pname);
  192. if (err == noErr) {
  193. CFStringGetCString(pname, endpoint_name, sizeof(endpoint_name), 0);
  194. CFRelease(pname);
  195. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%d", fAliasName, endpoint_name, i + 1);
  196. } else {
  197. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%d", fAliasName, fCaptureDriverName, i + 1);
  198. }
  199. snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
  200. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_MIDI_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  201. jack_error("driver: cannot register port for %s", name);
  202. return -1;
  203. }
  204. port = fGraphManager->GetPort(port_index);
  205. port->SetAlias(alias);
  206. fCapturePortList[i] = port_index;
  207. jack_log("JackCoreMidiDriver::Attach fCapturePortList[i] port_index = %ld", port_index);
  208. }
  209. port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
  210. for (i = 0; i < fPlaybackChannels; i++) {
  211. err = MIDIObjectGetStringProperty(fMidiSource[i], kMIDIPropertyName, &pname);
  212. if (err == noErr) {
  213. CFStringGetCString(pname, endpoint_name, sizeof(endpoint_name), 0);
  214. CFRelease(pname);
  215. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%d", fAliasName, endpoint_name, i + 1);
  216. } else {
  217. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%d", fAliasName, fPlaybackDriverName, i + 1);
  218. }
  219. snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
  220. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_MIDI_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  221. jack_error("driver: cannot register port for %s", name);
  222. return -1;
  223. }
  224. port = fGraphManager->GetPort(port_index);
  225. port->SetAlias(alias);
  226. fPlaybackPortList[i] = port_index;
  227. jack_log("JackCoreMidiDriver::Attach fPlaybackPortList[i] port_index = %ld", port_index);
  228. }
  229. return 0;
  230. }
  231. int JackCoreMidiDriver::Read()
  232. {
  233. for (int chan = 0; chan < fCaptureChannels; chan++) {
  234. if (fGraphManager->GetConnectionsNum(fCapturePortList[chan]) > 0) {
  235. // Get JACK port
  236. JackMidiBuffer* midi_buffer = GetInputBuffer(chan);
  237. if (jack_ringbuffer_read_space(fRingBuffer[chan]) == 0) {
  238. // Reset buffer
  239. midi_buffer->Reset(midi_buffer->nframes);
  240. } else {
  241. while (jack_ringbuffer_read_space(fRingBuffer[chan]) > 0) {
  242. // Read event number
  243. int ev_count = 0;
  244. jack_ringbuffer_read(fRingBuffer[chan], (char*)&ev_count, sizeof(int));
  245. for (int j = 0; j < ev_count; j++) {
  246. // Read event length
  247. UInt16 event_len;
  248. jack_ringbuffer_read(fRingBuffer[chan], (char*)&event_len, sizeof(UInt16));
  249. // Read event actual data
  250. jack_midi_data_t* dest = midi_buffer->ReserveEvent(0, event_len);
  251. jack_ringbuffer_read(fRingBuffer[chan], (char*)dest, event_len);
  252. }
  253. }
  254. }
  255. } else {
  256. // Consume ring buffer
  257. jack_ringbuffer_read_advance(fRingBuffer[chan], jack_ringbuffer_read_space(fRingBuffer[chan]));
  258. }
  259. }
  260. return 0;
  261. }
  262. int JackCoreMidiDriver::Write()
  263. {
  264. MIDIPacketList* pktlist = (MIDIPacketList*)fMIDIBuffer;
  265. for (int chan = 0; chan < fPlaybackChannels; chan++) {
  266. if (fGraphManager->GetConnectionsNum(fPlaybackPortList[chan]) > 0) {
  267. MIDIPacket* packet = MIDIPacketListInit(pktlist);
  268. JackMidiBuffer* midi_buffer = GetOutputBuffer(chan);
  269. // TODO : use timestamp
  270. for (unsigned int j = 0; j < midi_buffer->event_count; j++) {
  271. JackMidiEvent* ev = &midi_buffer->events[j];
  272. packet = MIDIPacketListAdd(pktlist, sizeof(fMIDIBuffer), packet, MIDIGetCurrentHostTime(), ev->size, ev->GetData(midi_buffer));
  273. }
  274. if (packet) {
  275. if (chan < fPlaybackChannels - fRealPlaybackChannels) {
  276. OSStatus err = MIDIReceived(fMidiSource[chan], pktlist);
  277. if (err != noErr)
  278. jack_error("MIDIReceived error");
  279. } else {
  280. OSStatus err = MIDISend(fOutputPort, fMidiSource[chan], pktlist);
  281. if (err != noErr)
  282. jack_error("MIDISend error");
  283. }
  284. }
  285. }
  286. }
  287. return 0;
  288. }
  289. } // end of namespace
  290. #ifdef __cplusplus
  291. extern "C"
  292. {
  293. #endif
  294. SERVER_EXPORT jack_driver_desc_t * driver_get_descriptor()
  295. {
  296. jack_driver_desc_t * desc;
  297. unsigned int i;
  298. desc = (jack_driver_desc_t*)calloc (1, sizeof (jack_driver_desc_t));
  299. strcpy(desc->name, "coremidi"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
  300. strcpy(desc->desc, "Apple CoreMIDI API based MIDI backend"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
  301. desc->nparams = 2;
  302. desc->params = (jack_driver_param_desc_t*)calloc (desc->nparams, sizeof (jack_driver_param_desc_t));
  303. i = 0;
  304. strcpy(desc->params[i].name, "inchannels");
  305. desc->params[i].character = 'i';
  306. desc->params[i].type = JackDriverParamInt;
  307. desc->params[i].value.ui = 0;
  308. strcpy(desc->params[i].short_desc, "CoreMIDI virtual bus");
  309. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  310. i++;
  311. strcpy(desc->params[i].name, "outchannels");
  312. desc->params[i].character = 'o';
  313. desc->params[i].type = JackDriverParamInt;
  314. desc->params[i].value.ui = 0;
  315. strcpy(desc->params[i].short_desc, "CoreMIDI virtual bus");
  316. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  317. return desc;
  318. }
  319. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  320. {
  321. const JSList * node;
  322. const jack_driver_param_t * param;
  323. int virtual_in = 0;
  324. int virtual_out = 0;
  325. for (node = params; node; node = jack_slist_next (node)) {
  326. param = (const jack_driver_param_t *) node->data;
  327. switch (param->character) {
  328. case 'i':
  329. virtual_in = param->value.ui;
  330. break;
  331. case 'o':
  332. virtual_out = param->value.ui;
  333. break;
  334. }
  335. }
  336. Jack::JackDriverClientInterface* driver = new Jack::JackCoreMidiDriver("system_midi", "coremidi", engine, table);
  337. if (driver->Open(1, 1, virtual_in, virtual_out, false, "in", "out", 0, 0) == 0) {
  338. return driver;
  339. } else {
  340. delete driver;
  341. return NULL;
  342. }
  343. }
  344. #ifdef __cplusplus
  345. }
  346. #endif