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 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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. //==============================================================================
  21. class AlsaClient : public ReferenceCountedObject
  22. {
  23. public:
  24. AlsaClient()
  25. {
  26. jassert (instance == nullptr);
  27. snd_seq_open (&handle, "default", SND_SEQ_OPEN_DUPLEX, 0);
  28. if (handle != nullptr)
  29. {
  30. snd_seq_nonblock (handle, SND_SEQ_NONBLOCK);
  31. snd_seq_set_client_name (handle, getAlsaMidiName().toRawUTF8());
  32. clientId = snd_seq_client_id (handle);
  33. // It's good idea to pre-allocate a good number of elements
  34. ports.ensureStorageAllocated (32);
  35. }
  36. }
  37. ~AlsaClient()
  38. {
  39. jassert (instance != nullptr);
  40. instance = nullptr;
  41. if (handle != nullptr)
  42. snd_seq_close (handle);
  43. jassert (activeCallbacks.get() == 0);
  44. if (inputThread)
  45. inputThread->stopThread (3000);
  46. }
  47. static String getAlsaMidiName()
  48. {
  49. #ifdef JUCE_ALSA_MIDI_NAME
  50. return JUCE_ALSA_MIDI_NAME;
  51. #else
  52. if (auto* app = JUCEApplicationBase::getInstance())
  53. return app->getApplicationName();
  54. return "JUCE";
  55. #endif
  56. }
  57. using Ptr = ReferenceCountedObjectPtr<AlsaClient>;
  58. //==============================================================================
  59. // represents an input or output port of the supplied AlsaClient
  60. struct Port
  61. {
  62. Port (AlsaClient& c, bool forInput) noexcept
  63. : client (c), isInput (forInput)
  64. {}
  65. ~Port()
  66. {
  67. if (isValid())
  68. {
  69. if (isInput)
  70. enableCallback (false);
  71. else
  72. snd_midi_event_free (midiParser);
  73. snd_seq_delete_simple_port (client.get(), portId);
  74. }
  75. }
  76. void connectWith (int sourceClient, int sourcePort) const noexcept
  77. {
  78. if (isInput)
  79. snd_seq_connect_from (client.get(), portId, sourceClient, sourcePort);
  80. else
  81. snd_seq_connect_to (client.get(), portId, sourceClient, sourcePort);
  82. }
  83. bool isValid() const noexcept
  84. {
  85. return client.get() != nullptr && portId >= 0;
  86. }
  87. void setupInput (MidiInput* input, MidiInputCallback* cb)
  88. {
  89. jassert (cb != nullptr && input != nullptr);
  90. callback = cb;
  91. midiInput = input;
  92. }
  93. void setupOutput()
  94. {
  95. jassert (! isInput);
  96. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  97. }
  98. void enableCallback (bool enable)
  99. {
  100. if (callbackEnabled != enable)
  101. {
  102. callbackEnabled = enable;
  103. if (enable)
  104. client.registerCallback();
  105. else
  106. client.unregisterCallback();
  107. }
  108. }
  109. bool sendMessageNow (const MidiMessage& message)
  110. {
  111. if (message.getRawDataSize() > maxEventSize)
  112. {
  113. maxEventSize = message.getRawDataSize();
  114. snd_midi_event_free (midiParser);
  115. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  116. }
  117. snd_seq_event_t event;
  118. snd_seq_ev_clear (&event);
  119. auto numBytes = (long) message.getRawDataSize();
  120. auto* data = message.getRawData();
  121. auto seqHandle = client.get();
  122. bool success = true;
  123. while (numBytes > 0)
  124. {
  125. auto numSent = snd_midi_event_encode (midiParser, data, numBytes, &event);
  126. if (numSent <= 0)
  127. {
  128. success = numSent == 0;
  129. break;
  130. }
  131. numBytes -= numSent;
  132. data += numSent;
  133. snd_seq_ev_set_source (&event, (unsigned char) portId);
  134. snd_seq_ev_set_subs (&event);
  135. snd_seq_ev_set_direct (&event);
  136. if (snd_seq_event_output_direct (seqHandle, &event) < 0)
  137. {
  138. success = false;
  139. break;
  140. }
  141. }
  142. snd_midi_event_reset_encode (midiParser);
  143. return success;
  144. }
  145. bool operator== (const Port& lhs) const noexcept
  146. {
  147. return portId != -1 && portId == lhs.portId;
  148. }
  149. void createPort (const String& name, bool enableSubscription)
  150. {
  151. if (auto seqHandle = client.get())
  152. {
  153. const unsigned int caps =
  154. isInput ? (SND_SEQ_PORT_CAP_WRITE | (enableSubscription ? SND_SEQ_PORT_CAP_SUBS_WRITE : 0))
  155. : (SND_SEQ_PORT_CAP_READ | (enableSubscription ? SND_SEQ_PORT_CAP_SUBS_READ : 0));
  156. portName = name;
  157. portId = snd_seq_create_simple_port (seqHandle, portName.toUTF8(), caps,
  158. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  159. SND_SEQ_PORT_TYPE_APPLICATION);
  160. }
  161. }
  162. void handleIncomingMidiMessage (const MidiMessage& message) const
  163. {
  164. callback->handleIncomingMidiMessage (midiInput, message);
  165. }
  166. void handlePartialSysexMessage (const uint8* messageData, int numBytesSoFar, double timeStamp)
  167. {
  168. callback->handlePartialSysexMessage (midiInput, messageData, numBytesSoFar, timeStamp);
  169. }
  170. AlsaClient& client;
  171. MidiInputCallback* callback = nullptr;
  172. snd_midi_event_t* midiParser = nullptr;
  173. MidiInput* midiInput = nullptr;
  174. String portName;
  175. int maxEventSize = 4096, portId = -1;
  176. bool callbackEnabled = false, isInput = false;
  177. };
  178. static Ptr getInstance()
  179. {
  180. if (instance == nullptr)
  181. instance = new AlsaClient();
  182. return instance;
  183. }
  184. void registerCallback()
  185. {
  186. if (inputThread == nullptr)
  187. inputThread.reset (new MidiInputThread (*this));
  188. if (++activeCallbacks == 1)
  189. inputThread->startThread();
  190. }
  191. void unregisterCallback()
  192. {
  193. jassert (activeCallbacks.get() > 0);
  194. if (--activeCallbacks == 0 && inputThread->isThreadRunning())
  195. inputThread->signalThreadShouldExit();
  196. }
  197. void handleIncomingMidiMessage (snd_seq_event* event, const MidiMessage& message)
  198. {
  199. if (event->dest.port < ports.size() && ports[event->dest.port]->callbackEnabled)
  200. ports[event->dest.port]->handleIncomingMidiMessage (message);
  201. }
  202. void handlePartialSysexMessage (snd_seq_event* event, const uint8* messageData, int numBytesSoFar, double timeStamp)
  203. {
  204. if (event->dest.port < ports.size()
  205. && ports[event->dest.port]->callbackEnabled)
  206. ports[event->dest.port]->handlePartialSysexMessage (messageData, numBytesSoFar, timeStamp);
  207. }
  208. snd_seq_t* get() const noexcept { return handle; }
  209. int getId() const noexcept { return clientId; }
  210. Port* createPort (const String& name, bool forInput, bool enableSubscription)
  211. {
  212. auto port = new Port (*this, forInput);
  213. port->createPort (name, enableSubscription);
  214. ports.set (port->portId, port);
  215. incReferenceCount();
  216. return port;
  217. }
  218. void deletePort (Port* port)
  219. {
  220. ports.set (port->portId, nullptr);
  221. decReferenceCount();
  222. }
  223. private:
  224. snd_seq_t* handle = nullptr;
  225. int clientId = 0;
  226. OwnedArray<Port> ports;
  227. Atomic<int> activeCallbacks;
  228. CriticalSection callbackLock;
  229. static AlsaClient* instance;
  230. //==============================================================================
  231. class MidiInputThread : public Thread
  232. {
  233. public:
  234. MidiInputThread (AlsaClient& c)
  235. : Thread ("JUCE MIDI Input"), client (c)
  236. {
  237. jassert (client.get() != nullptr);
  238. }
  239. void run() override
  240. {
  241. auto seqHandle = client.get();
  242. const int maxEventSize = 16 * 1024;
  243. snd_midi_event_t* midiParser;
  244. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  245. {
  246. auto numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  247. HeapBlock<pollfd> pfd (numPfds);
  248. snd_seq_poll_descriptors (seqHandle, pfd, (unsigned int) numPfds, POLLIN);
  249. HeapBlock<uint8> buffer (maxEventSize);
  250. while (! threadShouldExit())
  251. {
  252. 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
  253. {
  254. if (threadShouldExit())
  255. break;
  256. do
  257. {
  258. snd_seq_event_t* inputEvent = nullptr;
  259. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  260. {
  261. // xxx what about SYSEXes that are too big for the buffer?
  262. auto numBytes = snd_midi_event_decode (midiParser, buffer,
  263. maxEventSize, inputEvent);
  264. snd_midi_event_reset_decode (midiParser);
  265. concatenator.pushMidiData (buffer, (int) numBytes,
  266. Time::getMillisecondCounter() * 0.001,
  267. inputEvent, client);
  268. snd_seq_free_event (inputEvent);
  269. }
  270. }
  271. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  272. }
  273. }
  274. snd_midi_event_free (midiParser);
  275. }
  276. }
  277. private:
  278. AlsaClient& client;
  279. MidiDataConcatenator concatenator { 2048 };
  280. };
  281. std::unique_ptr<MidiInputThread> inputThread;
  282. };
  283. AlsaClient* AlsaClient::instance = nullptr;
  284. //==============================================================================
  285. static String getFormattedPortIdentifier (int clientId, int portId)
  286. {
  287. return String (clientId) + "-" + String (portId);
  288. }
  289. static AlsaClient::Port* iterateMidiClient (const AlsaClient::Ptr& client,
  290. snd_seq_client_info_t* clientInfo,
  291. bool forInput,
  292. Array<MidiDeviceInfo>& devices,
  293. const String& deviceIdentifierToOpen)
  294. {
  295. AlsaClient::Port* port = nullptr;
  296. auto seqHandle = client->get();
  297. snd_seq_port_info_t* portInfo = nullptr;
  298. snd_seq_port_info_alloca (&portInfo);
  299. jassert (portInfo != nullptr);
  300. auto numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  301. auto sourceClient = snd_seq_client_info_get_client (clientInfo);
  302. snd_seq_port_info_set_client (portInfo, sourceClient);
  303. snd_seq_port_info_set_port (portInfo, -1);
  304. while (--numPorts >= 0)
  305. {
  306. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  307. && (snd_seq_port_info_get_capability (portInfo)
  308. & (forInput ? SND_SEQ_PORT_CAP_SUBS_READ : SND_SEQ_PORT_CAP_SUBS_WRITE)) != 0)
  309. {
  310. String portName (snd_seq_port_info_get_name (portInfo));
  311. auto portID = snd_seq_port_info_get_port (portInfo);
  312. MidiDeviceInfo device (portName, getFormattedPortIdentifier (sourceClient, portID));
  313. devices.add (device);
  314. if (deviceIdentifierToOpen.isNotEmpty() && deviceIdentifierToOpen == device.identifier)
  315. {
  316. if (portID != -1)
  317. {
  318. port = client->createPort (portName, forInput, false);
  319. jassert (port->isValid());
  320. port->connectWith (sourceClient, portID);
  321. break;
  322. }
  323. }
  324. }
  325. }
  326. return port;
  327. }
  328. static AlsaClient::Port* iterateMidiDevices (bool forInput,
  329. Array<MidiDeviceInfo>& devices,
  330. const String& deviceIdentifierToOpen)
  331. {
  332. AlsaClient::Port* port = nullptr;
  333. auto client = AlsaClient::getInstance();
  334. if (auto seqHandle = client->get())
  335. {
  336. snd_seq_system_info_t* systemInfo = nullptr;
  337. snd_seq_client_info_t* clientInfo = nullptr;
  338. snd_seq_system_info_alloca (&systemInfo);
  339. jassert (systemInfo != nullptr);
  340. if (snd_seq_system_info (seqHandle, systemInfo) == 0)
  341. {
  342. snd_seq_client_info_alloca (&clientInfo);
  343. jassert (clientInfo != nullptr);
  344. auto numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  345. while (--numClients >= 0)
  346. {
  347. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  348. {
  349. port = iterateMidiClient (client, clientInfo, forInput,
  350. devices, deviceIdentifierToOpen);
  351. if (port != nullptr)
  352. break;
  353. }
  354. }
  355. }
  356. }
  357. return port;
  358. }
  359. struct AlsaPortPtr
  360. {
  361. explicit AlsaPortPtr (AlsaClient::Port* p)
  362. : ptr (p) {}
  363. ~AlsaPortPtr() noexcept { AlsaClient::getInstance()->deletePort (ptr); }
  364. AlsaClient::Port* ptr = nullptr;
  365. };
  366. //==============================================================================
  367. class MidiInput::Pimpl : public AlsaPortPtr
  368. {
  369. public:
  370. using AlsaPortPtr::AlsaPortPtr;
  371. };
  372. Array<MidiDeviceInfo> MidiInput::getAvailableDevices()
  373. {
  374. Array<MidiDeviceInfo> devices;
  375. iterateMidiDevices (true, devices, {});
  376. return devices;
  377. }
  378. MidiDeviceInfo MidiInput::getDefaultDevice()
  379. {
  380. return getAvailableDevices().getFirst();
  381. }
  382. std::unique_ptr<MidiInput> MidiInput::openDevice (const String& deviceIdentifier, MidiInputCallback* callback)
  383. {
  384. if (deviceIdentifier.isEmpty())
  385. return {};
  386. Array<MidiDeviceInfo> devices;
  387. auto* port = iterateMidiDevices (true, devices, deviceIdentifier);
  388. if (port == nullptr || ! port->isValid())
  389. return {};
  390. jassert (port->isValid());
  391. std::unique_ptr<MidiInput> midiInput (new MidiInput (port->portName, deviceIdentifier));
  392. port->setupInput (midiInput.get(), callback);
  393. midiInput->internal = std::make_unique<Pimpl> (port);
  394. return midiInput;
  395. }
  396. std::unique_ptr<MidiInput> MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  397. {
  398. auto client = AlsaClient::getInstance();
  399. auto* port = client->createPort (deviceName, true, true);
  400. if (port == nullptr || ! port->isValid())
  401. return {};
  402. std::unique_ptr<MidiInput> midiInput (new MidiInput (deviceName, getFormattedPortIdentifier (client->getId(), port->portId)));
  403. port->setupInput (midiInput.get(), callback);
  404. midiInput->internal = std::make_unique<Pimpl> (port);
  405. return midiInput;
  406. }
  407. StringArray MidiInput::getDevices()
  408. {
  409. StringArray deviceNames;
  410. for (auto& d : getAvailableDevices())
  411. deviceNames.add (d.name);
  412. deviceNames.appendNumbersToDuplicates (true, true);
  413. return deviceNames;
  414. }
  415. int MidiInput::getDefaultDeviceIndex()
  416. {
  417. return 0;
  418. }
  419. std::unique_ptr<MidiInput> MidiInput::openDevice (int index, MidiInputCallback* callback)
  420. {
  421. return openDevice (getAvailableDevices()[index].identifier, callback);
  422. }
  423. MidiInput::MidiInput (const String& deviceName, const String& deviceIdentifier)
  424. : deviceInfo (deviceName, deviceIdentifier)
  425. {
  426. }
  427. MidiInput::~MidiInput()
  428. {
  429. stop();
  430. }
  431. void MidiInput::start()
  432. {
  433. internal->ptr->enableCallback (true);
  434. }
  435. void MidiInput::stop()
  436. {
  437. internal->ptr->enableCallback (false);
  438. }
  439. //==============================================================================
  440. class MidiOutput::Pimpl : public AlsaPortPtr
  441. {
  442. public:
  443. using AlsaPortPtr::AlsaPortPtr;
  444. };
  445. Array<MidiDeviceInfo> MidiOutput::getAvailableDevices()
  446. {
  447. Array<MidiDeviceInfo> devices;
  448. iterateMidiDevices (false, devices, {});
  449. return devices;
  450. }
  451. MidiDeviceInfo MidiOutput::getDefaultDevice()
  452. {
  453. return getAvailableDevices().getFirst();
  454. }
  455. std::unique_ptr<MidiOutput> MidiOutput::openDevice (const String& deviceIdentifier)
  456. {
  457. if (deviceIdentifier.isEmpty())
  458. return {};
  459. Array<MidiDeviceInfo> devices;
  460. auto* port = iterateMidiDevices (false, devices, deviceIdentifier);
  461. if (port == nullptr || ! port->isValid())
  462. return {};
  463. std::unique_ptr<MidiOutput> midiOutput (new MidiOutput (port->portName, deviceIdentifier));
  464. port->setupOutput();
  465. midiOutput->internal = std::make_unique<Pimpl> (port);
  466. return midiOutput;
  467. }
  468. std::unique_ptr<MidiOutput> MidiOutput::createNewDevice (const String& deviceName)
  469. {
  470. auto client = AlsaClient::getInstance();
  471. auto* port = client->createPort (deviceName, false, true);
  472. if (port == nullptr || ! port->isValid())
  473. return {};
  474. std::unique_ptr<MidiOutput> midiOutput (new MidiOutput (deviceName, getFormattedPortIdentifier (client->getId(), port->portId)));
  475. port->setupOutput();
  476. midiOutput->internal = std::make_unique<Pimpl> (port);
  477. return midiOutput;
  478. }
  479. StringArray MidiOutput::getDevices()
  480. {
  481. StringArray deviceNames;
  482. for (auto& d : getAvailableDevices())
  483. deviceNames.add (d.name);
  484. deviceNames.appendNumbersToDuplicates (true, true);
  485. return deviceNames;
  486. }
  487. int MidiOutput::getDefaultDeviceIndex()
  488. {
  489. return 0;
  490. }
  491. std::unique_ptr<MidiOutput> MidiOutput::openDevice (int index)
  492. {
  493. return openDevice (getAvailableDevices()[index].identifier);
  494. }
  495. MidiOutput::~MidiOutput()
  496. {
  497. stopBackgroundThread();
  498. }
  499. void MidiOutput::sendMessageNow (const MidiMessage& message)
  500. {
  501. internal->ptr->sendMessageNow (message);
  502. }
  503. //==============================================================================
  504. #else
  505. class MidiInput::Pimpl {};
  506. // (These are just stub functions if ALSA is unavailable...)
  507. MidiInput::MidiInput (const String& deviceName, const String& deviceID)
  508. : deviceInfo (deviceName, deviceID)
  509. {
  510. }
  511. MidiInput::~MidiInput() {}
  512. void MidiInput::start() {}
  513. void MidiInput::stop() {}
  514. Array<MidiDeviceInfo> MidiInput::getAvailableDevices() { return {}; }
  515. MidiDeviceInfo MidiInput::getDefaultDevice() { return {}; }
  516. std::unique_ptr<MidiInput> MidiInput::openDevice (const String&, MidiInputCallback*) { return {}; }
  517. std::unique_ptr<MidiInput> MidiInput::createNewDevice (const String&, MidiInputCallback*) { return {}; }
  518. StringArray MidiInput::getDevices() { return {}; }
  519. int MidiInput::getDefaultDeviceIndex() { return 0;}
  520. std::unique_ptr<MidiInput> MidiInput::openDevice (int, MidiInputCallback*) { return {}; }
  521. class MidiOutput::Pimpl {};
  522. MidiOutput::~MidiOutput() {}
  523. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  524. Array<MidiDeviceInfo> MidiOutput::getAvailableDevices() { return {}; }
  525. MidiDeviceInfo MidiOutput::getDefaultDevice() { return {}; }
  526. std::unique_ptr<MidiOutput> MidiOutput::openDevice (const String&) { return {}; }
  527. std::unique_ptr<MidiOutput> MidiOutput::createNewDevice (const String&) { return {}; }
  528. StringArray MidiOutput::getDevices() { return {}; }
  529. int MidiOutput::getDefaultDeviceIndex() { return 0;}
  530. std::unique_ptr<MidiOutput> MidiOutput::openDevice (int) { return {}; }
  531. #endif
  532. } // namespace juce