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.

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