The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

592 lines
18KB

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