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.

628 lines
19KB

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