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

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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 (const MidiMessage& message, int port);
  81. snd_seq_t* get() const noexcept { return handle; }
  82. private:
  83. bool input;
  84. snd_seq_t* handle;
  85. Array<AlsaPortAndCallback*> activeCallbacks;
  86. CriticalSection callbackLock;
  87. //==============================================================================
  88. class MidiInputThread : public Thread
  89. {
  90. public:
  91. MidiInputThread (AlsaClient& c)
  92. : Thread ("Juce MIDI Input"), client (c)
  93. {
  94. jassert (client.input && client.get() != nullptr);
  95. }
  96. void run() override
  97. {
  98. const int maxEventSize = 16 * 1024;
  99. snd_midi_event_t* midiParser;
  100. snd_seq_t* seqHandle = client.get();
  101. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  102. {
  103. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  104. HeapBlock<pollfd> pfd ((size_t) numPfds);
  105. snd_seq_poll_descriptors (seqHandle, pfd, (unsigned int) numPfds, POLLIN);
  106. HeapBlock<uint8> buffer (maxEventSize);
  107. while (! threadShouldExit())
  108. {
  109. 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
  110. {
  111. if (threadShouldExit())
  112. break;
  113. snd_seq_nonblock (seqHandle, 1);
  114. do
  115. {
  116. snd_seq_event_t* inputEvent = nullptr;
  117. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  118. {
  119. // xxx what about SYSEXes that are too big for the buffer?
  120. const long numBytes = snd_midi_event_decode (midiParser, buffer,
  121. maxEventSize, inputEvent);
  122. snd_midi_event_reset_decode (midiParser);
  123. if (numBytes > 0)
  124. {
  125. const MidiMessage message ((const uint8*) buffer, (int) numBytes,
  126. Time::getMillisecondCounter() * 0.001);
  127. client.handleIncomingMidiMessage (message, inputEvent->dest.port);
  128. }
  129. snd_seq_free_event (inputEvent);
  130. }
  131. }
  132. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  133. }
  134. }
  135. snd_midi_event_free (midiParser);
  136. }
  137. };
  138. private:
  139. AlsaClient& client;
  140. };
  141. ScopedPointer<MidiInputThread> inputThread;
  142. };
  143. static AlsaClient::Ptr globalAlsaSequencerIn()
  144. {
  145. static AlsaClient::Ptr global (new AlsaClient (true));
  146. return global;
  147. }
  148. static AlsaClient::Ptr globalAlsaSequencerOut()
  149. {
  150. static AlsaClient::Ptr global (new AlsaClient (false));
  151. return global;
  152. }
  153. static AlsaClient::Ptr globalAlsaSequencer (bool input)
  154. {
  155. return input ? globalAlsaSequencerIn()
  156. : globalAlsaSequencerOut();
  157. }
  158. //==============================================================================
  159. // represents an input or output port of the supplied AlsaClient
  160. class AlsaPort
  161. {
  162. public:
  163. AlsaPort() noexcept : portId (-1) {}
  164. AlsaPort (const AlsaClient::Ptr& c, int port) noexcept : client (c), portId (port) {}
  165. void createPort (const AlsaClient::Ptr& c, const String& name, bool forInput)
  166. {
  167. client = c;
  168. if (snd_seq_t* handle = client->get())
  169. portId = snd_seq_create_simple_port (handle, name.toUTF8(),
  170. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  171. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  172. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  173. }
  174. void deletePort()
  175. {
  176. if (isValid())
  177. {
  178. snd_seq_delete_simple_port (client->get(), portId);
  179. portId = -1;
  180. }
  181. }
  182. void connectWith (int sourceClient, int sourcePort)
  183. {
  184. if (client->isInput())
  185. snd_seq_connect_from (client->get(), portId, sourceClient, sourcePort);
  186. else
  187. snd_seq_connect_to (client->get(), portId, sourceClient, sourcePort);
  188. }
  189. bool isValid() const noexcept
  190. {
  191. return client != nullptr && client->get() != nullptr && portId >= 0;
  192. }
  193. AlsaClient::Ptr client;
  194. int portId;
  195. };
  196. //==============================================================================
  197. class AlsaPortAndCallback
  198. {
  199. public:
  200. AlsaPortAndCallback (AlsaPort p, MidiInput* in, MidiInputCallback* cb)
  201. : port (p), midiInput (in), callback (cb), callbackEnabled (false)
  202. {
  203. }
  204. ~AlsaPortAndCallback()
  205. {
  206. enableCallback (false);
  207. port.deletePort();
  208. }
  209. void enableCallback (bool enable)
  210. {
  211. if (callbackEnabled != enable)
  212. {
  213. callbackEnabled = enable;
  214. if (enable)
  215. port.client->registerCallback (this);
  216. else
  217. port.client->unregisterCallback (this);
  218. }
  219. }
  220. void handleIncomingMidiMessage (const MidiMessage& message) const
  221. {
  222. callback->handleIncomingMidiMessage (midiInput, message);
  223. }
  224. private:
  225. AlsaPort port;
  226. MidiInput* midiInput;
  227. MidiInputCallback* callback;
  228. bool callbackEnabled;
  229. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlsaPortAndCallback)
  230. };
  231. void AlsaClient::handleIncomingMidiMessage (const MidiMessage& message, int port)
  232. {
  233. const ScopedLock sl (callbackLock);
  234. if (AlsaPortAndCallback* const cb = activeCallbacks[port])
  235. cb->handleIncomingMidiMessage (message);
  236. }
  237. //==============================================================================
  238. static AlsaPort iterateMidiClient (const AlsaClient::Ptr& seq,
  239. snd_seq_client_info_t* clientInfo,
  240. const bool forInput,
  241. StringArray& deviceNamesFound,
  242. const int deviceIndexToOpen)
  243. {
  244. AlsaPort port;
  245. snd_seq_t* seqHandle = seq->get();
  246. snd_seq_port_info_t* portInfo = nullptr;
  247. if (snd_seq_port_info_malloc (&portInfo) == 0)
  248. {
  249. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  250. const int client = snd_seq_client_info_get_client (clientInfo);
  251. snd_seq_port_info_set_client (portInfo, client);
  252. snd_seq_port_info_set_port (portInfo, -1);
  253. while (--numPorts >= 0)
  254. {
  255. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  256. && (snd_seq_port_info_get_capability (portInfo) & (forInput ? SND_SEQ_PORT_CAP_READ
  257. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  258. {
  259. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  260. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  261. {
  262. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  263. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  264. if (sourcePort != -1)
  265. {
  266. const String name (forInput ? JUCE_ALSA_MIDI_INPUT_NAME
  267. : JUCE_ALSA_MIDI_OUTPUT_NAME);
  268. seq->setName (name);
  269. port.createPort (seq, name, forInput);
  270. port.connectWith (sourceClient, sourcePort);
  271. }
  272. }
  273. }
  274. }
  275. snd_seq_port_info_free (portInfo);
  276. }
  277. return port;
  278. }
  279. static AlsaPort iterateMidiDevices (const bool forInput,
  280. StringArray& deviceNamesFound,
  281. const int deviceIndexToOpen)
  282. {
  283. AlsaPort port;
  284. const AlsaClient::Ptr client (globalAlsaSequencer (forInput));
  285. if (snd_seq_t* const seqHandle = client->get())
  286. {
  287. snd_seq_system_info_t* systemInfo = nullptr;
  288. snd_seq_client_info_t* clientInfo = nullptr;
  289. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  290. {
  291. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  292. && snd_seq_client_info_malloc (&clientInfo) == 0)
  293. {
  294. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  295. while (--numClients >= 0 && ! port.isValid())
  296. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  297. port = iterateMidiClient (client, clientInfo, forInput,
  298. deviceNamesFound, deviceIndexToOpen);
  299. snd_seq_client_info_free (clientInfo);
  300. }
  301. snd_seq_system_info_free (systemInfo);
  302. }
  303. }
  304. deviceNamesFound.appendNumbersToDuplicates (true, true);
  305. return port;
  306. }
  307. AlsaPort createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  308. {
  309. AlsaPort port;
  310. AlsaClient::Ptr client (new AlsaClient (forInput));
  311. if (client->get())
  312. {
  313. client->setName (deviceNameToOpen + (forInput ? " Input" : " Output"));
  314. port.createPort (client, forInput ? "in" : "out", forInput);
  315. }
  316. return port;
  317. }
  318. //==============================================================================
  319. class MidiOutputDevice
  320. {
  321. public:
  322. MidiOutputDevice (MidiOutput* const output, const AlsaPort& p)
  323. : midiOutput (output), port (p),
  324. maxEventSize (16 * 1024)
  325. {
  326. jassert (port.isValid() && midiOutput != nullptr);
  327. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  328. }
  329. ~MidiOutputDevice()
  330. {
  331. snd_midi_event_free (midiParser);
  332. port.deletePort();
  333. }
  334. bool sendMessageNow (const MidiMessage& message)
  335. {
  336. if (message.getRawDataSize() > maxEventSize)
  337. {
  338. maxEventSize = message.getRawDataSize();
  339. snd_midi_event_free (midiParser);
  340. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  341. }
  342. snd_seq_event_t event;
  343. snd_seq_ev_clear (&event);
  344. long numBytes = (long) message.getRawDataSize();
  345. const uint8* data = message.getRawData();
  346. snd_seq_t* seqHandle = port.client->get();
  347. bool success = true;
  348. while (numBytes > 0)
  349. {
  350. const long numSent = snd_midi_event_encode (midiParser, data, numBytes, &event);
  351. if (numSent <= 0)
  352. {
  353. success = numSent == 0;
  354. break;
  355. }
  356. numBytes -= numSent;
  357. data += numSent;
  358. snd_seq_ev_set_source (&event, 0);
  359. snd_seq_ev_set_subs (&event);
  360. snd_seq_ev_set_direct (&event);
  361. if (snd_seq_event_output_direct (seqHandle, &event) < 0)
  362. {
  363. success = false;
  364. break;
  365. }
  366. }
  367. snd_midi_event_reset_encode (midiParser);
  368. return success;
  369. }
  370. private:
  371. MidiOutput* const midiOutput;
  372. AlsaPort port;
  373. snd_midi_event_t* midiParser;
  374. int maxEventSize;
  375. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice)
  376. };
  377. } // namespace
  378. StringArray MidiOutput::getDevices()
  379. {
  380. StringArray devices;
  381. iterateMidiDevices (false, devices, -1);
  382. return devices;
  383. }
  384. int MidiOutput::getDefaultDeviceIndex()
  385. {
  386. return 0;
  387. }
  388. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  389. {
  390. MidiOutput* newDevice = nullptr;
  391. StringArray devices;
  392. AlsaPort port (iterateMidiDevices (false, devices, deviceIndex));
  393. if (port.isValid())
  394. {
  395. newDevice = new MidiOutput (devices [deviceIndex]);
  396. newDevice->internal = new MidiOutputDevice (newDevice, port);
  397. }
  398. return newDevice;
  399. }
  400. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  401. {
  402. MidiOutput* newDevice = nullptr;
  403. AlsaPort port (createMidiDevice (false, deviceName));
  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 (createMidiDevice (true, deviceName));
  464. if (port.isValid())
  465. {
  466. newDevice = new MidiInput (deviceName);
  467. newDevice->internal = new AlsaPortAndCallback (port, newDevice, callback);
  468. }
  469. return newDevice;
  470. }
  471. //==============================================================================
  472. #else
  473. // (These are just stub functions if ALSA is unavailable...)
  474. StringArray MidiOutput::getDevices() { return StringArray(); }
  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 StringArray(); }
  486. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return nullptr; }
  487. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return nullptr; }
  488. #endif