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.

422 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. int i;
  186. jack_log("JackCoreMidiDriver::Attach fBufferSize = %ld fSampleRate = %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  187. for (i = 0; i < fCaptureChannels; i++) {
  188. err = MIDIObjectGetStringProperty(fMidiDestination[i], kMIDIPropertyName, &pname);
  189. if (err == noErr) {
  190. CFStringGetCString(pname, endpoint_name, sizeof(endpoint_name), 0);
  191. CFRelease(pname);
  192. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%d", fAliasName, endpoint_name, i + 1);
  193. } else {
  194. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%d", fAliasName, fCaptureDriverName, i + 1);
  195. }
  196. snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
  197. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_MIDI_TYPE, CaptureDriverFlags, fEngineControl->fBufferSize)) == NO_PORT) {
  198. jack_error("driver: cannot register port for %s", name);
  199. return -1;
  200. }
  201. port = fGraphManager->GetPort(port_index);
  202. port->SetAlias(alias);
  203. fCapturePortList[i] = port_index;
  204. jack_log("JackCoreMidiDriver::Attach fCapturePortList[i] port_index = %ld", port_index);
  205. }
  206. for (i = 0; i < fPlaybackChannels; i++) {
  207. err = MIDIObjectGetStringProperty(fMidiSource[i], kMIDIPropertyName, &pname);
  208. if (err == noErr) {
  209. CFStringGetCString(pname, endpoint_name, sizeof(endpoint_name), 0);
  210. CFRelease(pname);
  211. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%d", fAliasName, endpoint_name, i + 1);
  212. } else {
  213. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%d", fAliasName, fPlaybackDriverName, i + 1);
  214. }
  215. snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
  216. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_MIDI_TYPE, PlaybackDriverFlags, fEngineControl->fBufferSize)) == NO_PORT) {
  217. jack_error("driver: cannot register port for %s", name);
  218. return -1;
  219. }
  220. port = fGraphManager->GetPort(port_index);
  221. port->SetAlias(alias);
  222. fPlaybackPortList[i] = port_index;
  223. jack_log("JackCoreMidiDriver::Attach fPlaybackPortList[i] port_index = %ld", port_index);
  224. }
  225. return 0;
  226. }
  227. int JackCoreMidiDriver::Read()
  228. {
  229. for (int chan = 0; chan < fCaptureChannels; chan++) {
  230. if (fGraphManager->GetConnectionsNum(fCapturePortList[chan]) > 0) {
  231. // Get JACK port
  232. JackMidiBuffer* midi_buffer = GetInputBuffer(chan);
  233. if (jack_ringbuffer_read_space(fRingBuffer[chan]) == 0) {
  234. // Reset buffer
  235. midi_buffer->Reset(midi_buffer->nframes);
  236. } else {
  237. while (jack_ringbuffer_read_space(fRingBuffer[chan]) > 0) {
  238. // Read event number
  239. int ev_count = 0;
  240. jack_ringbuffer_read(fRingBuffer[chan], (char*)&ev_count, sizeof(int));
  241. for (int j = 0; j < ev_count; j++) {
  242. // Read event length
  243. UInt16 event_len;
  244. jack_ringbuffer_read(fRingBuffer[chan], (char*)&event_len, sizeof(UInt16));
  245. // Read event actual data
  246. jack_midi_data_t* dest = midi_buffer->ReserveEvent(0, event_len);
  247. jack_ringbuffer_read(fRingBuffer[chan], (char*)dest, event_len);
  248. }
  249. }
  250. }
  251. } else {
  252. // Consume ring buffer
  253. jack_ringbuffer_read_advance(fRingBuffer[chan], jack_ringbuffer_read_space(fRingBuffer[chan]));
  254. }
  255. }
  256. return 0;
  257. }
  258. int JackCoreMidiDriver::Write()
  259. {
  260. MIDIPacketList* pktlist = (MIDIPacketList*)fMIDIBuffer;
  261. for (int chan = 0; chan < fPlaybackChannels; chan++) {
  262. if (fGraphManager->GetConnectionsNum(fPlaybackPortList[chan]) > 0) {
  263. MIDIPacket* packet = MIDIPacketListInit(pktlist);
  264. JackMidiBuffer* midi_buffer = GetOutputBuffer(chan);
  265. // TODO : use timestamp
  266. for (unsigned int j = 0; j < midi_buffer->event_count; j++) {
  267. JackMidiEvent* ev = &midi_buffer->events[j];
  268. packet = MIDIPacketListAdd(pktlist, sizeof(fMIDIBuffer), packet, MIDIGetCurrentHostTime(), ev->size, ev->GetData(midi_buffer));
  269. }
  270. if (packet) {
  271. if (chan < fPlaybackChannels - fRealPlaybackChannels) {
  272. OSStatus err = MIDIReceived(fMidiSource[chan], pktlist);
  273. if (err != noErr)
  274. jack_error("MIDIReceived error");
  275. } else {
  276. OSStatus err = MIDISend(fOutputPort, fMidiSource[chan], pktlist);
  277. if (err != noErr)
  278. jack_error("MIDISend error");
  279. }
  280. }
  281. }
  282. }
  283. return 0;
  284. }
  285. } // end of namespace
  286. #ifdef __cplusplus
  287. extern "C"
  288. {
  289. #endif
  290. SERVER_EXPORT jack_driver_desc_t * driver_get_descriptor()
  291. {
  292. jack_driver_desc_t * desc;
  293. unsigned int i;
  294. desc = (jack_driver_desc_t*)calloc (1, sizeof (jack_driver_desc_t));
  295. strcpy(desc->name, "coremidi"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
  296. strcpy(desc->desc, "Apple CoreMIDI API based MIDI backend"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
  297. desc->nparams = 2;
  298. desc->params = (jack_driver_param_desc_t*)calloc (desc->nparams, sizeof (jack_driver_param_desc_t));
  299. i = 0;
  300. strcpy(desc->params[i].name, "inchannels");
  301. desc->params[i].character = 'i';
  302. desc->params[i].type = JackDriverParamInt;
  303. desc->params[i].value.ui = 0;
  304. strcpy(desc->params[i].short_desc, "CoreMIDI virtual bus");
  305. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  306. i++;
  307. strcpy(desc->params[i].name, "outchannels");
  308. desc->params[i].character = 'o';
  309. desc->params[i].type = JackDriverParamInt;
  310. desc->params[i].value.ui = 0;
  311. strcpy(desc->params[i].short_desc, "CoreMIDI virtual bus");
  312. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  313. return desc;
  314. }
  315. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  316. {
  317. const JSList * node;
  318. const jack_driver_param_t * param;
  319. int virtual_in = 0;
  320. int virtual_out = 0;
  321. for (node = params; node; node = jack_slist_next (node)) {
  322. param = (const jack_driver_param_t *) node->data;
  323. switch (param->character) {
  324. case 'i':
  325. virtual_in = param->value.ui;
  326. break;
  327. case 'o':
  328. virtual_out = param->value.ui;
  329. break;
  330. }
  331. }
  332. Jack::JackDriverClientInterface* driver = new Jack::JackCoreMidiDriver("system_midi", "coremidi", engine, table);
  333. if (driver->Open(1, 1, virtual_in, virtual_out, false, "in", "out", 0, 0) == 0) {
  334. return driver;
  335. } else {
  336. delete driver;
  337. return NULL;
  338. }
  339. }
  340. #ifdef __cplusplus
  341. }
  342. #endif