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.

612 lines
19KB

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