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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. if (handle != nullptr)
  225. {
  226. snd_seq_nonblock (handle, SND_SEQ_NONBLOCK);
  227. snd_seq_set_client_name (handle, JUCE_ALSA_MIDI_NAME);
  228. clientId = snd_seq_client_id(handle);
  229. // It's good idea to pre-allocate a good number of elements
  230. ports.ensureStorageAllocated (32);
  231. }
  232. }
  233. ~AlsaClient()
  234. {
  235. jassert (instance != nullptr);
  236. instance = nullptr;
  237. if (handle != nullptr)
  238. snd_seq_close (handle);
  239. jassert (activeCallbacks.get() == 0);
  240. if (inputThread)
  241. inputThread->stopThread (3000);
  242. }
  243. //==============================================================================
  244. class MidiInputThread : public Thread
  245. {
  246. public:
  247. MidiInputThread (AlsaClient& c)
  248. : Thread ("Juce MIDI Input"), client (c), concatenator (2048)
  249. {
  250. jassert (client.get() != nullptr);
  251. }
  252. void run() override
  253. {
  254. const int maxEventSize = 16 * 1024;
  255. snd_midi_event_t* midiParser;
  256. snd_seq_t* seqHandle = client.get();
  257. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  258. {
  259. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  260. HeapBlock<pollfd> pfd ((size_t) numPfds);
  261. snd_seq_poll_descriptors (seqHandle, pfd, (unsigned int) numPfds, POLLIN);
  262. HeapBlock<uint8> buffer (maxEventSize);
  263. while (! threadShouldExit())
  264. {
  265. 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
  266. {
  267. if (threadShouldExit())
  268. break;
  269. do
  270. {
  271. snd_seq_event_t* inputEvent = nullptr;
  272. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  273. {
  274. // xxx what about SYSEXes that are too big for the buffer?
  275. const long numBytes = snd_midi_event_decode (midiParser, buffer,
  276. maxEventSize, inputEvent);
  277. snd_midi_event_reset_decode (midiParser);
  278. concatenator.pushMidiData (buffer, (int) numBytes,
  279. Time::getMillisecondCounter() * 0.001,
  280. inputEvent, client);
  281. snd_seq_free_event (inputEvent);
  282. }
  283. }
  284. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  285. }
  286. }
  287. snd_midi_event_free (midiParser);
  288. }
  289. }
  290. private:
  291. AlsaClient& client;
  292. MidiDataConcatenator concatenator;
  293. };
  294. ScopedPointer<MidiInputThread> inputThread;
  295. };
  296. AlsaClient* AlsaClient::instance = nullptr;
  297. //==============================================================================
  298. static AlsaClient::Port* iterateMidiClient (const AlsaClient::Ptr& client,
  299. snd_seq_client_info_t* clientInfo,
  300. const bool forInput,
  301. StringArray& deviceNamesFound,
  302. const int deviceIndexToOpen)
  303. {
  304. AlsaClient::Port* port = nullptr;
  305. snd_seq_t* seqHandle = client->get();
  306. snd_seq_port_info_t* portInfo = nullptr;
  307. snd_seq_port_info_alloca (&portInfo);
  308. jassert (portInfo);
  309. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  310. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  311. snd_seq_port_info_set_client (portInfo, sourceClient);
  312. snd_seq_port_info_set_port (portInfo, -1);
  313. while (--numPorts >= 0)
  314. {
  315. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  316. && (snd_seq_port_info_get_capability (portInfo)
  317. & (forInput ? SND_SEQ_PORT_CAP_SUBS_WRITE : SND_SEQ_PORT_CAP_SUBS_READ)) != 0)
  318. {
  319. const String portName = snd_seq_port_info_get_name(portInfo);
  320. deviceNamesFound.add (portName);
  321. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  322. {
  323. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  324. if (sourcePort != -1)
  325. {
  326. port = client->createPort (portName, forInput, false);
  327. jassert (port->isValid());
  328. port->connectWith (sourceClient, sourcePort);
  329. break;
  330. }
  331. }
  332. }
  333. }
  334. return port;
  335. }
  336. static AlsaClient::Port* iterateMidiDevices (const bool forInput,
  337. StringArray& deviceNamesFound,
  338. const int deviceIndexToOpen)
  339. {
  340. AlsaClient::Port* port = nullptr;
  341. const AlsaClient::Ptr client (AlsaClient::getInstance());
  342. if (snd_seq_t* const seqHandle = client->get())
  343. {
  344. snd_seq_system_info_t* systemInfo = nullptr;
  345. snd_seq_client_info_t* clientInfo = nullptr;
  346. snd_seq_system_info_alloca (&systemInfo);
  347. jassert(systemInfo);
  348. if (snd_seq_system_info (seqHandle, systemInfo) == 0)
  349. {
  350. snd_seq_client_info_alloca (&clientInfo);
  351. jassert(clientInfo);
  352. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  353. while (--numClients >= 0)
  354. {
  355. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  356. {
  357. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  358. if (sourceClient != client->getId()
  359. && sourceClient != SND_SEQ_CLIENT_SYSTEM)
  360. {
  361. port = iterateMidiClient (client, clientInfo, forInput,
  362. deviceNamesFound, deviceIndexToOpen);
  363. if (port)
  364. break;
  365. }
  366. }
  367. }
  368. }
  369. }
  370. deviceNamesFound.appendNumbersToDuplicates (true, true);
  371. return port;
  372. }
  373. } // namespace
  374. StringArray MidiOutput::getDevices()
  375. {
  376. StringArray devices;
  377. iterateMidiDevices (false, devices, -1);
  378. return devices;
  379. }
  380. int MidiOutput::getDefaultDeviceIndex()
  381. {
  382. return 0;
  383. }
  384. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  385. {
  386. MidiOutput* newDevice = nullptr;
  387. StringArray devices;
  388. AlsaClient::Port* port = iterateMidiDevices (false, devices, deviceIndex);
  389. if (port == nullptr)
  390. return nullptr;
  391. jassert (port->isValid());
  392. newDevice = new MidiOutput (devices [deviceIndex]);
  393. port->setupOutput();
  394. newDevice->internal = port;
  395. return newDevice;
  396. }
  397. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  398. {
  399. MidiOutput* newDevice = nullptr;
  400. const AlsaClient::Ptr client (AlsaClient::getInstance());
  401. AlsaClient::Port* port = client->createPort (deviceName, false, true);
  402. jassert (port->isValid());
  403. newDevice = new MidiOutput (deviceName);
  404. port->setupOutput();
  405. newDevice->internal = port;
  406. return newDevice;
  407. }
  408. MidiOutput::~MidiOutput()
  409. {
  410. stopBackgroundThread();
  411. AlsaClient::Ptr client (AlsaClient::getInstance());
  412. client->deletePort (static_cast<AlsaClient::Port*> (internal));
  413. }
  414. void MidiOutput::sendMessageNow (const MidiMessage& message)
  415. {
  416. static_cast<AlsaClient::Port*> (internal)->sendMessageNow (message);
  417. }
  418. //==============================================================================
  419. MidiInput::MidiInput (const String& nm)
  420. : name (nm), internal (nullptr)
  421. {
  422. }
  423. MidiInput::~MidiInput()
  424. {
  425. stop();
  426. AlsaClient::Ptr client (AlsaClient::getInstance());
  427. client->deletePort (static_cast<AlsaClient::Port*> (internal));
  428. }
  429. void MidiInput::start()
  430. {
  431. static_cast<AlsaClient::Port*> (internal)->enableCallback (true);
  432. }
  433. void MidiInput::stop()
  434. {
  435. static_cast<AlsaClient::Port*> (internal)->enableCallback (false);
  436. }
  437. int MidiInput::getDefaultDeviceIndex()
  438. {
  439. return 0;
  440. }
  441. StringArray MidiInput::getDevices()
  442. {
  443. StringArray devices;
  444. iterateMidiDevices (true, devices, -1);
  445. return devices;
  446. }
  447. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  448. {
  449. MidiInput* newDevice = nullptr;
  450. StringArray devices;
  451. AlsaClient::Port* port = iterateMidiDevices (true, devices, deviceIndex);
  452. if (port == nullptr)
  453. return nullptr;
  454. jassert (port->isValid());
  455. newDevice = new MidiInput (devices [deviceIndex]);
  456. port->setupInput (newDevice, callback);
  457. newDevice->internal = port;
  458. return newDevice;
  459. }
  460. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  461. {
  462. MidiInput* newDevice = nullptr;
  463. AlsaClient::Ptr client (AlsaClient::getInstance());
  464. AlsaClient::Port* port = client->createPort (deviceName, true, true);
  465. jassert (port->isValid());
  466. newDevice = new MidiInput (deviceName);
  467. port->setupInput (newDevice, callback);
  468. newDevice->internal = port;
  469. return newDevice;
  470. }
  471. //==============================================================================
  472. #else
  473. // (These are just stub functions if ALSA is unavailable...)
  474. StringArray MidiOutput::getDevices() { return {}; }
  475. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  476. MidiOutput* MidiOutput::openDevice (int) { return nullptr; }
  477. MidiOutput* MidiOutput::createNewDevice (const String&) { return nullptr; }
  478. MidiOutput::~MidiOutput() {}
  479. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  480. MidiInput::MidiInput (const String& nm) : name (nm), internal (nullptr) {}
  481. MidiInput::~MidiInput() {}
  482. void MidiInput::start() {}
  483. void MidiInput::stop() {}
  484. int MidiInput::getDefaultDeviceIndex() { return 0; }
  485. StringArray MidiInput::getDevices() { return {}; }
  486. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return nullptr; }
  487. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return nullptr; }
  488. #endif
  489. } // namespace juce