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.

633 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. }
  40. ~AlsaClient()
  41. {
  42. if (handle != nullptr)
  43. {
  44. snd_seq_close (handle);
  45. handle = nullptr;
  46. }
  47. jassert (activeCallbacks.size() == 0);
  48. if (inputThread)
  49. {
  50. inputThread->stopThread (3000);
  51. inputThread = nullptr;
  52. }
  53. }
  54. bool isInput() const noexcept { return input; }
  55. void setName (const String& name)
  56. {
  57. snd_seq_set_client_name (handle, name.toUTF8());
  58. }
  59. void registerCallback (AlsaPortAndCallback* cb)
  60. {
  61. if (cb != nullptr)
  62. {
  63. {
  64. const ScopedLock sl (callbackLock);
  65. activeCallbacks.add (cb);
  66. if (inputThread == nullptr)
  67. inputThread = new MidiInputThread (*this);
  68. }
  69. inputThread->startThread();
  70. }
  71. }
  72. void unregisterCallback (AlsaPortAndCallback* cb)
  73. {
  74. const ScopedLock sl (callbackLock);
  75. jassert (activeCallbacks.contains (cb));
  76. activeCallbacks.removeAllInstancesOf (cb);
  77. if (activeCallbacks.size() == 0 && inputThread->isThreadRunning())
  78. inputThread->signalThreadShouldExit();
  79. }
  80. void handleIncomingMidiMessage (snd_seq_event*, const MidiMessage&);
  81. void handlePartialSysexMessage (snd_seq_event*, const uint8*, int, double);
  82. snd_seq_t* get() const noexcept { return handle; }
  83. private:
  84. bool input;
  85. snd_seq_t* handle;
  86. Array<AlsaPortAndCallback*> activeCallbacks;
  87. CriticalSection callbackLock;
  88. //==============================================================================
  89. class MidiInputThread : public Thread
  90. {
  91. public:
  92. MidiInputThread (AlsaClient& c)
  93. : Thread ("Juce MIDI Input"), client (c), concatenator (2048)
  94. {
  95. jassert (client.input && client.get() != nullptr);
  96. }
  97. void run() override
  98. {
  99. const int maxEventSize = 16 * 1024;
  100. snd_midi_event_t* midiParser;
  101. snd_seq_t* seqHandle = client.get();
  102. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  103. {
  104. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  105. HeapBlock<pollfd> pfd ((size_t) numPfds);
  106. snd_seq_poll_descriptors (seqHandle, pfd, (unsigned int) numPfds, POLLIN);
  107. HeapBlock<uint8> buffer (maxEventSize);
  108. while (! threadShouldExit())
  109. {
  110. 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
  111. {
  112. if (threadShouldExit())
  113. break;
  114. snd_seq_nonblock (seqHandle, 1);
  115. do
  116. {
  117. snd_seq_event_t* inputEvent = nullptr;
  118. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  119. {
  120. // xxx what about SYSEXes that are too big for the buffer?
  121. const long numBytes = snd_midi_event_decode (midiParser, buffer,
  122. maxEventSize, inputEvent);
  123. snd_midi_event_reset_decode (midiParser);
  124. concatenator.pushMidiData (buffer, (int) numBytes,
  125. Time::getMillisecondCounter() * 0.001,
  126. inputEvent, client);
  127. snd_seq_free_event (inputEvent);
  128. }
  129. }
  130. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  131. }
  132. }
  133. snd_midi_event_free (midiParser);
  134. }
  135. };
  136. private:
  137. AlsaClient& client;
  138. MidiDataConcatenator concatenator;
  139. };
  140. ScopedPointer<MidiInputThread> inputThread;
  141. };
  142. static AlsaClient::Ptr globalAlsaSequencerIn()
  143. {
  144. static AlsaClient::Ptr global (new AlsaClient (true));
  145. return global;
  146. }
  147. static AlsaClient::Ptr globalAlsaSequencerOut()
  148. {
  149. static AlsaClient::Ptr global (new AlsaClient (false));
  150. return global;
  151. }
  152. static AlsaClient::Ptr globalAlsaSequencer (bool input)
  153. {
  154. return input ? globalAlsaSequencerIn()
  155. : globalAlsaSequencerOut();
  156. }
  157. //==============================================================================
  158. // represents an input or output port of the supplied AlsaClient
  159. class AlsaPort
  160. {
  161. public:
  162. AlsaPort() noexcept : portId (-1) {}
  163. AlsaPort (const AlsaClient::Ptr& c, int port) noexcept : client (c), portId (port) {}
  164. void createPort (const AlsaClient::Ptr& c, const String& name, bool forInput)
  165. {
  166. client = c;
  167. if (snd_seq_t* handle = client->get())
  168. portId = snd_seq_create_simple_port (handle, name.toUTF8(),
  169. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  170. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  171. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  172. }
  173. void deletePort()
  174. {
  175. if (isValid())
  176. {
  177. snd_seq_delete_simple_port (client->get(), portId);
  178. portId = -1;
  179. }
  180. }
  181. void connectWith (int sourceClient, int sourcePort)
  182. {
  183. if (client->isInput())
  184. snd_seq_connect_from (client->get(), portId, sourceClient, sourcePort);
  185. else
  186. snd_seq_connect_to (client->get(), portId, sourceClient, sourcePort);
  187. }
  188. bool isValid() const noexcept
  189. {
  190. return client != nullptr && client->get() != nullptr && portId >= 0;
  191. }
  192. AlsaClient::Ptr client;
  193. int portId;
  194. };
  195. //==============================================================================
  196. class AlsaPortAndCallback
  197. {
  198. public:
  199. AlsaPortAndCallback (AlsaPort p, MidiInput* in, MidiInputCallback* cb)
  200. : port (p), midiInput (in), callback (cb), callbackEnabled (false)
  201. {
  202. }
  203. ~AlsaPortAndCallback()
  204. {
  205. enableCallback (false);
  206. port.deletePort();
  207. }
  208. void enableCallback (bool enable)
  209. {
  210. if (callbackEnabled != enable)
  211. {
  212. callbackEnabled = enable;
  213. if (enable)
  214. port.client->registerCallback (this);
  215. else
  216. port.client->unregisterCallback (this);
  217. }
  218. }
  219. void handleIncomingMidiMessage (const MidiMessage& message) const
  220. {
  221. callback->handleIncomingMidiMessage (midiInput, message);
  222. }
  223. void handlePartialSysexMessage (const uint8* messageData, int numBytesSoFar, double timeStamp)
  224. {
  225. callback->handlePartialSysexMessage (midiInput, messageData, numBytesSoFar, timeStamp);
  226. }
  227. private:
  228. AlsaPort port;
  229. MidiInput* midiInput;
  230. MidiInputCallback* callback;
  231. bool callbackEnabled;
  232. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlsaPortAndCallback)
  233. };
  234. void AlsaClient::handleIncomingMidiMessage (snd_seq_event_t* event, const MidiMessage& message)
  235. {
  236. const ScopedLock sl (callbackLock);
  237. if (AlsaPortAndCallback* const cb = activeCallbacks[event->dest.port])
  238. cb->handleIncomingMidiMessage (message);
  239. }
  240. void AlsaClient::handlePartialSysexMessage (snd_seq_event* event, const uint8* messageData, int numBytesSoFar, double timeStamp)
  241. {
  242. const ScopedLock sl (callbackLock);
  243. if (AlsaPortAndCallback* const cb = activeCallbacks[event->dest.port])
  244. cb->handlePartialSysexMessage (messageData, numBytesSoFar, timeStamp);
  245. }
  246. //==============================================================================
  247. static AlsaPort iterateMidiClient (const AlsaClient::Ptr& seq,
  248. snd_seq_client_info_t* clientInfo,
  249. const bool forInput,
  250. StringArray& deviceNamesFound,
  251. const int deviceIndexToOpen)
  252. {
  253. AlsaPort port;
  254. snd_seq_t* seqHandle = seq->get();
  255. snd_seq_port_info_t* portInfo = nullptr;
  256. if (snd_seq_port_info_malloc (&portInfo) == 0)
  257. {
  258. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  259. const int client = snd_seq_client_info_get_client (clientInfo);
  260. snd_seq_port_info_set_client (portInfo, client);
  261. snd_seq_port_info_set_port (portInfo, -1);
  262. while (--numPorts >= 0)
  263. {
  264. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  265. && (snd_seq_port_info_get_capability (portInfo) & (forInput ? SND_SEQ_PORT_CAP_READ
  266. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  267. {
  268. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  269. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  270. {
  271. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  272. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  273. if (sourcePort != -1)
  274. {
  275. const String name (forInput ? JUCE_ALSA_MIDI_INPUT_NAME
  276. : JUCE_ALSA_MIDI_OUTPUT_NAME);
  277. seq->setName (name);
  278. port.createPort (seq, name, 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. AlsaPort createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  317. {
  318. AlsaPort port;
  319. AlsaClient::Ptr client (new AlsaClient (forInput));
  320. if (client->get())
  321. {
  322. client->setName (deviceNameToOpen + (forInput ? " Input" : " Output"));
  323. port.createPort (client, forInput ? "in" : "out", forInput);
  324. }
  325. return port;
  326. }
  327. //==============================================================================
  328. class MidiOutputDevice
  329. {
  330. public:
  331. MidiOutputDevice (MidiOutput* const output, const AlsaPort& p)
  332. : midiOutput (output), port (p),
  333. maxEventSize (16 * 1024)
  334. {
  335. jassert (port.isValid() && midiOutput != nullptr);
  336. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  337. }
  338. ~MidiOutputDevice()
  339. {
  340. snd_midi_event_free (midiParser);
  341. port.deletePort();
  342. }
  343. bool sendMessageNow (const MidiMessage& message)
  344. {
  345. if (message.getRawDataSize() > maxEventSize)
  346. {
  347. maxEventSize = message.getRawDataSize();
  348. snd_midi_event_free (midiParser);
  349. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  350. }
  351. snd_seq_event_t event;
  352. snd_seq_ev_clear (&event);
  353. long numBytes = (long) message.getRawDataSize();
  354. const uint8* data = message.getRawData();
  355. snd_seq_t* seqHandle = port.client->get();
  356. bool success = true;
  357. while (numBytes > 0)
  358. {
  359. const long numSent = snd_midi_event_encode (midiParser, data, numBytes, &event);
  360. if (numSent <= 0)
  361. {
  362. success = numSent == 0;
  363. break;
  364. }
  365. numBytes -= numSent;
  366. data += numSent;
  367. snd_seq_ev_set_source (&event, 0);
  368. snd_seq_ev_set_subs (&event);
  369. snd_seq_ev_set_direct (&event);
  370. if (snd_seq_event_output_direct (seqHandle, &event) < 0)
  371. {
  372. success = false;
  373. break;
  374. }
  375. }
  376. snd_midi_event_reset_encode (midiParser);
  377. return success;
  378. }
  379. private:
  380. MidiOutput* const midiOutput;
  381. AlsaPort port;
  382. snd_midi_event_t* midiParser;
  383. int maxEventSize;
  384. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice)
  385. };
  386. } // namespace
  387. StringArray MidiOutput::getDevices()
  388. {
  389. StringArray devices;
  390. iterateMidiDevices (false, devices, -1);
  391. return devices;
  392. }
  393. int MidiOutput::getDefaultDeviceIndex()
  394. {
  395. return 0;
  396. }
  397. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  398. {
  399. MidiOutput* newDevice = nullptr;
  400. StringArray devices;
  401. AlsaPort port (iterateMidiDevices (false, devices, deviceIndex));
  402. if (port.isValid())
  403. {
  404. newDevice = new MidiOutput (devices [deviceIndex]);
  405. newDevice->internal = new MidiOutputDevice (newDevice, port);
  406. }
  407. return newDevice;
  408. }
  409. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  410. {
  411. MidiOutput* newDevice = nullptr;
  412. AlsaPort port (createMidiDevice (false, deviceName));
  413. if (port.isValid())
  414. {
  415. newDevice = new MidiOutput (deviceName);
  416. newDevice->internal = new MidiOutputDevice (newDevice, port);
  417. }
  418. return newDevice;
  419. }
  420. MidiOutput::~MidiOutput()
  421. {
  422. stopBackgroundThread();
  423. delete static_cast<MidiOutputDevice*> (internal);
  424. }
  425. void MidiOutput::sendMessageNow (const MidiMessage& message)
  426. {
  427. static_cast<MidiOutputDevice*> (internal)->sendMessageNow (message);
  428. }
  429. //==============================================================================
  430. MidiInput::MidiInput (const String& nm)
  431. : name (nm), internal (nullptr)
  432. {
  433. }
  434. MidiInput::~MidiInput()
  435. {
  436. stop();
  437. delete static_cast<AlsaPortAndCallback*> (internal);
  438. }
  439. void MidiInput::start()
  440. {
  441. static_cast<AlsaPortAndCallback*> (internal)->enableCallback (true);
  442. }
  443. void MidiInput::stop()
  444. {
  445. static_cast<AlsaPortAndCallback*> (internal)->enableCallback (false);
  446. }
  447. int MidiInput::getDefaultDeviceIndex()
  448. {
  449. return 0;
  450. }
  451. StringArray MidiInput::getDevices()
  452. {
  453. StringArray devices;
  454. iterateMidiDevices (true, devices, -1);
  455. return devices;
  456. }
  457. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  458. {
  459. MidiInput* newDevice = nullptr;
  460. StringArray devices;
  461. AlsaPort port (iterateMidiDevices (true, devices, deviceIndex));
  462. if (port.isValid())
  463. {
  464. newDevice = new MidiInput (devices [deviceIndex]);
  465. newDevice->internal = new AlsaPortAndCallback (port, newDevice, callback);
  466. }
  467. return newDevice;
  468. }
  469. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  470. {
  471. MidiInput* newDevice = nullptr;
  472. AlsaPort port (createMidiDevice (true, deviceName));
  473. if (port.isValid())
  474. {
  475. newDevice = new MidiInput (deviceName);
  476. newDevice->internal = new AlsaPortAndCallback (port, newDevice, callback);
  477. }
  478. return newDevice;
  479. }
  480. //==============================================================================
  481. #else
  482. // (These are just stub functions if ALSA is unavailable...)
  483. StringArray MidiOutput::getDevices() { return StringArray(); }
  484. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  485. MidiOutput* MidiOutput::openDevice (int) { return nullptr; }
  486. MidiOutput* MidiOutput::createNewDevice (const String&) { return nullptr; }
  487. MidiOutput::~MidiOutput() {}
  488. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  489. MidiInput::MidiInput (const String& nm) : name (nm), internal (nullptr) {}
  490. MidiInput::~MidiInput() {}
  491. void MidiInput::start() {}
  492. void MidiInput::stop() {}
  493. int MidiInput::getDefaultDeviceIndex() { return 0; }
  494. StringArray MidiInput::getDevices() { return StringArray(); }
  495. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return nullptr; }
  496. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return nullptr; }
  497. #endif