Audio plugin host https://kx.studio/carla
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.

juce_linux_Midi.cpp 19KB

7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. #if JUCE_ALSA
  20. // You can define these strings in your app if you want to override the default names:
  21. #ifndef JUCE_ALSA_MIDI_NAME
  22. #define JUCE_ALSA_MIDI_NAME JUCEApplicationBase::getInstance()->getApplicationName().toUTF8()
  23. #endif
  24. //==============================================================================
  25. namespace
  26. {
  27. //==============================================================================
  28. class AlsaClient : public ReferenceCountedObject
  29. {
  30. public:
  31. typedef ReferenceCountedObjectPtr<AlsaClient> Ptr;
  32. //==============================================================================
  33. // represents an input or output port of the supplied AlsaClient
  34. class Port
  35. {
  36. public:
  37. Port (AlsaClient& c, bool forInput) noexcept
  38. : portId (-1),
  39. callbackEnabled (false),
  40. client (c),
  41. isInput (forInput),
  42. callback (nullptr),
  43. maxEventSize (4 * 1024),
  44. midiInput (nullptr)
  45. {}
  46. ~Port()
  47. {
  48. if (isValid())
  49. {
  50. if (isInput)
  51. enableCallback (false);
  52. else
  53. snd_midi_event_free (midiParser);
  54. snd_seq_delete_simple_port (client.get(), portId);
  55. }
  56. }
  57. void connectWith (int sourceClient, int sourcePort) const noexcept
  58. {
  59. if (isInput)
  60. snd_seq_connect_from (client.get(), portId, sourceClient, sourcePort);
  61. else
  62. snd_seq_connect_to (client.get(), portId, sourceClient, sourcePort);
  63. }
  64. bool isValid() const noexcept
  65. {
  66. return client.get() != nullptr && portId >= 0;
  67. }
  68. void setupInput(MidiInput* input, MidiInputCallback* cb)
  69. {
  70. jassert (cb && input);
  71. callback = cb;
  72. midiInput = input;
  73. }
  74. void setupOutput()
  75. {
  76. jassert (! isInput);
  77. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  78. }
  79. void enableCallback (bool enable)
  80. {
  81. if (callbackEnabled != enable)
  82. {
  83. callbackEnabled = enable;
  84. if (enable)
  85. client.registerCallback();
  86. else
  87. client.unregisterCallback();
  88. }
  89. }
  90. bool sendMessageNow (const MidiMessage& message)
  91. {
  92. if (message.getRawDataSize() > maxEventSize)
  93. {
  94. maxEventSize = message.getRawDataSize();
  95. snd_midi_event_free (midiParser);
  96. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  97. }
  98. snd_seq_event_t event;
  99. snd_seq_ev_clear (&event);
  100. long numBytes = (long) message.getRawDataSize();
  101. const uint8* data = message.getRawData();
  102. snd_seq_t* seqHandle = client.get();
  103. bool success = true;
  104. while (numBytes > 0)
  105. {
  106. const long numSent = snd_midi_event_encode (midiParser, data, numBytes, &event);
  107. if (numSent <= 0)
  108. {
  109. success = numSent == 0;
  110. break;
  111. }
  112. numBytes -= numSent;
  113. data += numSent;
  114. snd_seq_ev_set_source (&event, (unsigned char) portId);
  115. snd_seq_ev_set_subs (&event);
  116. snd_seq_ev_set_direct (&event);
  117. if (snd_seq_event_output_direct (seqHandle, &event) < 0)
  118. {
  119. success = false;
  120. break;
  121. }
  122. }
  123. snd_midi_event_reset_encode (midiParser);
  124. return success;
  125. }
  126. bool operator== (const Port& lhs) const noexcept
  127. {
  128. return portId != -1 && portId == lhs.portId;
  129. }
  130. int portId;
  131. bool callbackEnabled;
  132. private:
  133. friend class AlsaClient;
  134. AlsaClient& client;
  135. bool isInput;
  136. MidiInputCallback* callback;
  137. snd_midi_event_t* midiParser;
  138. int maxEventSize;
  139. MidiInput* midiInput;
  140. void createPort (const String& name, bool enableSubscription)
  141. {
  142. if (snd_seq_t* seqHandle = client.get())
  143. {
  144. const unsigned int caps =
  145. isInput
  146. ? (SND_SEQ_PORT_CAP_WRITE | (enableSubscription ? SND_SEQ_PORT_CAP_SUBS_WRITE : 0))
  147. : (SND_SEQ_PORT_CAP_WRITE | (enableSubscription ? SND_SEQ_PORT_CAP_SUBS_READ : 0));
  148. portId = snd_seq_create_simple_port (seqHandle, name.toUTF8(), caps,
  149. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  150. SND_SEQ_PORT_TYPE_APPLICATION);
  151. }
  152. }
  153. void handleIncomingMidiMessage (const MidiMessage& message) const
  154. {
  155. callback->handleIncomingMidiMessage (midiInput, message);
  156. }
  157. void handlePartialSysexMessage (const uint8* messageData, int numBytesSoFar, double timeStamp)
  158. {
  159. callback->handlePartialSysexMessage (midiInput, messageData, numBytesSoFar, timeStamp);
  160. }
  161. };
  162. static Ptr getInstance()
  163. {
  164. if (instance == nullptr)
  165. instance = new AlsaClient();
  166. return instance;
  167. }
  168. void registerCallback()
  169. {
  170. if (inputThread == nullptr)
  171. inputThread = new MidiInputThread (*this);
  172. if (++activeCallbacks - 1 == 0)
  173. inputThread->startThread();
  174. }
  175. void unregisterCallback()
  176. {
  177. jassert (activeCallbacks.get() > 0);
  178. if (--activeCallbacks == 0 && inputThread->isThreadRunning())
  179. inputThread->signalThreadShouldExit();
  180. }
  181. void handleIncomingMidiMessage (snd_seq_event* event, const MidiMessage& message)
  182. {
  183. if (event->dest.port < ports.size()
  184. && ports[event->dest.port]->callbackEnabled)
  185. ports[event->dest.port]->handleIncomingMidiMessage (message);
  186. }
  187. void handlePartialSysexMessage (snd_seq_event* event, const uint8* messageData, int numBytesSoFar, double timeStamp)
  188. {
  189. if (event->dest.port < ports.size()
  190. && ports[event->dest.port]->callbackEnabled)
  191. ports[event->dest.port]->handlePartialSysexMessage (messageData, numBytesSoFar, timeStamp);
  192. }
  193. snd_seq_t* get() const noexcept { return handle; }
  194. int getId() const noexcept { return clientId; }
  195. Port* createPort (const String& name, bool forInput, bool enableSubscription)
  196. {
  197. Port* port = new Port (*this, forInput);
  198. port->createPort (name, enableSubscription);
  199. ports.set (port->portId, port);
  200. incReferenceCount();
  201. return port;
  202. }
  203. void deletePort (Port* port)
  204. {
  205. ports.remove (port->portId);
  206. decReferenceCount();
  207. }
  208. private:
  209. snd_seq_t* handle;
  210. int clientId;
  211. OwnedArray<Port> ports;
  212. Atomic<int> activeCallbacks;
  213. CriticalSection callbackLock;
  214. static AlsaClient* instance;
  215. //==============================================================================
  216. friend class ReferenceCountedObjectPtr<AlsaClient>;
  217. friend struct ContainerDeletePolicy<AlsaClient>;
  218. AlsaClient()
  219. : handle (nullptr),
  220. inputThread (nullptr)
  221. {
  222. jassert (instance == nullptr);
  223. snd_seq_open (&handle, "default", SND_SEQ_OPEN_DUPLEX, 0);
  224. snd_seq_nonblock (handle, SND_SEQ_NONBLOCK);
  225. snd_seq_set_client_name (handle, JUCE_ALSA_MIDI_NAME);
  226. clientId = snd_seq_client_id(handle);
  227. // It's good idea to pre-allocate a good number of elements
  228. ports.ensureStorageAllocated (32);
  229. }
  230. ~AlsaClient()
  231. {
  232. jassert (instance != nullptr);
  233. instance = nullptr;
  234. if (handle != nullptr)
  235. snd_seq_close (handle);
  236. jassert (activeCallbacks.get() == 0);
  237. if (inputThread)
  238. inputThread->stopThread (3000);
  239. }
  240. //==============================================================================
  241. class MidiInputThread : public Thread
  242. {
  243. public:
  244. MidiInputThread (AlsaClient& c)
  245. : Thread ("Juce MIDI Input"), client (c), concatenator (2048)
  246. {
  247. jassert (client.get() != nullptr);
  248. }
  249. void run() override
  250. {
  251. const int maxEventSize = 16 * 1024;
  252. snd_midi_event_t* midiParser;
  253. snd_seq_t* seqHandle = client.get();
  254. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  255. {
  256. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  257. HeapBlock<pollfd> pfd ((size_t) numPfds);
  258. snd_seq_poll_descriptors (seqHandle, pfd, (unsigned int) numPfds, POLLIN);
  259. HeapBlock<uint8> buffer (maxEventSize);
  260. while (! threadShouldExit())
  261. {
  262. if (poll (pfd, (nfds_t) numPfds, 100) > 0) // there was a "500" here which is a bit long when we exit the program and have to wait for a timeout on this poll call
  263. {
  264. if (threadShouldExit())
  265. break;
  266. do
  267. {
  268. snd_seq_event_t* inputEvent = nullptr;
  269. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  270. {
  271. // xxx what about SYSEXes that are too big for the buffer?
  272. const long numBytes = snd_midi_event_decode (midiParser, buffer,
  273. maxEventSize, inputEvent);
  274. snd_midi_event_reset_decode (midiParser);
  275. concatenator.pushMidiData (buffer, (int) numBytes,
  276. Time::getMillisecondCounter() * 0.001,
  277. inputEvent, client);
  278. snd_seq_free_event (inputEvent);
  279. }
  280. }
  281. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  282. }
  283. }
  284. snd_midi_event_free (midiParser);
  285. }
  286. }
  287. private:
  288. AlsaClient& client;
  289. MidiDataConcatenator concatenator;
  290. };
  291. ScopedPointer<MidiInputThread> inputThread;
  292. };
  293. AlsaClient* AlsaClient::instance = nullptr;
  294. //==============================================================================
  295. static AlsaClient::Port* iterateMidiClient (const AlsaClient::Ptr& client,
  296. snd_seq_client_info_t* clientInfo,
  297. const bool forInput,
  298. StringArray& deviceNamesFound,
  299. const int deviceIndexToOpen)
  300. {
  301. AlsaClient::Port* port = nullptr;
  302. snd_seq_t* seqHandle = client->get();
  303. snd_seq_port_info_t* portInfo = nullptr;
  304. snd_seq_port_info_alloca (&portInfo);
  305. jassert (portInfo);
  306. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  307. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  308. snd_seq_port_info_set_client (portInfo, sourceClient);
  309. snd_seq_port_info_set_port (portInfo, -1);
  310. while (--numPorts >= 0)
  311. {
  312. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  313. && (snd_seq_port_info_get_capability (portInfo)
  314. & (forInput ? SND_SEQ_PORT_CAP_SUBS_WRITE : SND_SEQ_PORT_CAP_SUBS_READ)) != 0)
  315. {
  316. const String portName = snd_seq_port_info_get_name(portInfo);
  317. deviceNamesFound.add (portName);
  318. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  319. {
  320. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  321. if (sourcePort != -1)
  322. {
  323. port = client->createPort (portName, forInput, false);
  324. jassert (port->isValid());
  325. port->connectWith (sourceClient, sourcePort);
  326. break;
  327. }
  328. }
  329. }
  330. }
  331. return port;
  332. }
  333. static AlsaClient::Port* iterateMidiDevices (const bool forInput,
  334. StringArray& deviceNamesFound,
  335. const int deviceIndexToOpen)
  336. {
  337. AlsaClient::Port* port = nullptr;
  338. const AlsaClient::Ptr client (AlsaClient::getInstance());
  339. if (snd_seq_t* const seqHandle = client->get())
  340. {
  341. snd_seq_system_info_t* systemInfo = nullptr;
  342. snd_seq_client_info_t* clientInfo = nullptr;
  343. snd_seq_system_info_alloca (&systemInfo);
  344. jassert(systemInfo);
  345. if (snd_seq_system_info (seqHandle, systemInfo) == 0)
  346. {
  347. snd_seq_client_info_alloca (&clientInfo);
  348. jassert(clientInfo);
  349. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  350. while (--numClients >= 0)
  351. {
  352. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  353. {
  354. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  355. if (sourceClient != client->getId()
  356. && sourceClient != SND_SEQ_CLIENT_SYSTEM)
  357. {
  358. port = iterateMidiClient (client, clientInfo, forInput,
  359. deviceNamesFound, deviceIndexToOpen);
  360. if (port)
  361. break;
  362. }
  363. }
  364. }
  365. }
  366. }
  367. deviceNamesFound.appendNumbersToDuplicates (true, true);
  368. return port;
  369. }
  370. } // namespace
  371. StringArray MidiOutput::getDevices()
  372. {
  373. StringArray devices;
  374. iterateMidiDevices (false, devices, -1);
  375. return devices;
  376. }
  377. int MidiOutput::getDefaultDeviceIndex()
  378. {
  379. return 0;
  380. }
  381. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  382. {
  383. MidiOutput* newDevice = nullptr;
  384. StringArray devices;
  385. AlsaClient::Port* port = iterateMidiDevices (false, devices, deviceIndex);
  386. if (port == nullptr)
  387. return nullptr;
  388. jassert (port->isValid());
  389. newDevice = new MidiOutput (devices [deviceIndex]);
  390. port->setupOutput();
  391. newDevice->internal = port;
  392. return newDevice;
  393. }
  394. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  395. {
  396. MidiOutput* newDevice = nullptr;
  397. const AlsaClient::Ptr client (AlsaClient::getInstance());
  398. AlsaClient::Port* port = client->createPort (deviceName, false, true);
  399. jassert (port->isValid());
  400. newDevice = new MidiOutput (deviceName);
  401. port->setupOutput();
  402. newDevice->internal = port;
  403. return newDevice;
  404. }
  405. MidiOutput::~MidiOutput()
  406. {
  407. stopBackgroundThread();
  408. AlsaClient::Ptr client (AlsaClient::getInstance());
  409. client->deletePort (static_cast<AlsaClient::Port*> (internal));
  410. }
  411. void MidiOutput::sendMessageNow (const MidiMessage& message)
  412. {
  413. static_cast<AlsaClient::Port*> (internal)->sendMessageNow (message);
  414. }
  415. //==============================================================================
  416. MidiInput::MidiInput (const String& nm)
  417. : name (nm), internal (nullptr)
  418. {
  419. }
  420. MidiInput::~MidiInput()
  421. {
  422. stop();
  423. AlsaClient::Ptr client (AlsaClient::getInstance());
  424. client->deletePort (static_cast<AlsaClient::Port*> (internal));
  425. }
  426. void MidiInput::start()
  427. {
  428. static_cast<AlsaClient::Port*> (internal)->enableCallback (true);
  429. }
  430. void MidiInput::stop()
  431. {
  432. static_cast<AlsaClient::Port*> (internal)->enableCallback (false);
  433. }
  434. int MidiInput::getDefaultDeviceIndex()
  435. {
  436. return 0;
  437. }
  438. StringArray MidiInput::getDevices()
  439. {
  440. StringArray devices;
  441. iterateMidiDevices (true, devices, -1);
  442. return devices;
  443. }
  444. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  445. {
  446. MidiInput* newDevice = nullptr;
  447. StringArray devices;
  448. AlsaClient::Port* port = iterateMidiDevices (true, devices, deviceIndex);
  449. if (port == nullptr)
  450. return nullptr;
  451. jassert (port->isValid());
  452. newDevice = new MidiInput (devices [deviceIndex]);
  453. port->setupInput (newDevice, callback);
  454. newDevice->internal = port;
  455. return newDevice;
  456. }
  457. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  458. {
  459. MidiInput* newDevice = nullptr;
  460. AlsaClient::Ptr client (AlsaClient::getInstance());
  461. AlsaClient::Port* port = client->createPort (deviceName, true, true);
  462. jassert (port->isValid());
  463. newDevice = new MidiInput (deviceName);
  464. port->setupInput (newDevice, callback);
  465. newDevice->internal = port;
  466. return newDevice;
  467. }
  468. //==============================================================================
  469. #else
  470. // (These are just stub functions if ALSA is unavailable...)
  471. StringArray MidiOutput::getDevices() { return {}; }
  472. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  473. MidiOutput* MidiOutput::openDevice (int) { return nullptr; }
  474. MidiOutput* MidiOutput::createNewDevice (const String&) { return nullptr; }
  475. MidiOutput::~MidiOutput() {}
  476. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  477. MidiInput::MidiInput (const String& nm) : name (nm), internal (nullptr) {}
  478. MidiInput::~MidiInput() {}
  479. void MidiInput::start() {}
  480. void MidiInput::stop() {}
  481. int MidiInput::getDefaultDeviceIndex() { return 0; }
  482. StringArray MidiInput::getDevices() { return {}; }
  483. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return nullptr; }
  484. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return nullptr; }
  485. #endif
  486. } // namespace juce