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.

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