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.

611 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. }
  334. void 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 (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. while (numBytes > 0)
  348. {
  349. const long numSent = snd_midi_event_encode (midiParser, data, numBytes, &event);
  350. if (numSent <= 0)
  351. break;
  352. numBytes -= numSent;
  353. data += numSent;
  354. snd_seq_ev_set_source (&event, 0);
  355. snd_seq_ev_set_subs (&event);
  356. snd_seq_ev_set_direct (&event);
  357. snd_seq_event_output (seqHandle, &event);
  358. }
  359. snd_seq_drain_output (seqHandle);
  360. snd_midi_event_reset_encode (midiParser);
  361. }
  362. private:
  363. MidiOutput* const midiOutput;
  364. AlsaPort port;
  365. snd_midi_event_t* midiParser;
  366. int maxEventSize;
  367. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  368. };
  369. } // namespace
  370. StringArray MidiOutput::getDevices()
  371. {
  372. StringArray devices;
  373. iterateMidiDevices (false, devices, -1);
  374. return devices;
  375. }
  376. int MidiOutput::getDefaultDeviceIndex()
  377. {
  378. return 0;
  379. }
  380. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  381. {
  382. MidiOutput* newDevice = nullptr;
  383. StringArray devices;
  384. AlsaPort port (iterateMidiDevices (false, devices, deviceIndex));
  385. if (port.isValid())
  386. {
  387. newDevice = new MidiOutput();
  388. newDevice->internal = new MidiOutputDevice (newDevice, port);
  389. }
  390. return newDevice;
  391. }
  392. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  393. {
  394. MidiOutput* newDevice = nullptr;
  395. AlsaPort port (createMidiDevice (false, deviceName));
  396. if (port.isValid())
  397. {
  398. newDevice = new MidiOutput();
  399. newDevice->internal = new MidiOutputDevice (newDevice, port);
  400. }
  401. return newDevice;
  402. }
  403. MidiOutput::~MidiOutput()
  404. {
  405. delete static_cast <MidiOutputDevice*> (internal);
  406. }
  407. void MidiOutput::sendMessageNow (const MidiMessage& message)
  408. {
  409. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  410. }
  411. //==============================================================================
  412. MidiInput::MidiInput (const String& nm)
  413. : name (nm), internal (nullptr)
  414. {
  415. }
  416. MidiInput::~MidiInput()
  417. {
  418. stop();
  419. delete static_cast <AlsaPortAndCallback*> (internal);
  420. }
  421. void MidiInput::start()
  422. {
  423. static_cast<AlsaPortAndCallback*> (internal)->enableCallback (true);
  424. }
  425. void MidiInput::stop()
  426. {
  427. static_cast<AlsaPortAndCallback*> (internal)->enableCallback (false);
  428. }
  429. int MidiInput::getDefaultDeviceIndex()
  430. {
  431. return 0;
  432. }
  433. StringArray MidiInput::getDevices()
  434. {
  435. StringArray devices;
  436. iterateMidiDevices (true, devices, -1);
  437. return devices;
  438. }
  439. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  440. {
  441. MidiInput* newDevice = nullptr;
  442. StringArray devices;
  443. AlsaPort port (iterateMidiDevices (true, devices, deviceIndex));
  444. if (port.isValid())
  445. {
  446. newDevice = new MidiInput (devices [deviceIndex]);
  447. newDevice->internal = new AlsaPortAndCallback (port, newDevice, callback);
  448. }
  449. return newDevice;
  450. }
  451. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  452. {
  453. MidiInput* newDevice = nullptr;
  454. AlsaPort port (createMidiDevice (true, deviceName));
  455. if (port.isValid())
  456. {
  457. newDevice = new MidiInput (deviceName);
  458. newDevice->internal = new AlsaPortAndCallback (port, newDevice, callback);
  459. }
  460. return newDevice;
  461. }
  462. //==============================================================================
  463. #else
  464. // (These are just stub functions if ALSA is unavailable...)
  465. StringArray MidiOutput::getDevices() { return StringArray(); }
  466. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  467. MidiOutput* MidiOutput::openDevice (int) { return nullptr; }
  468. MidiOutput* MidiOutput::createNewDevice (const String&) { return nullptr; }
  469. MidiOutput::~MidiOutput() {}
  470. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  471. MidiInput::MidiInput (const String& nm) : name (nm), internal (nullptr) {}
  472. MidiInput::~MidiInput() {}
  473. void MidiInput::start() {}
  474. void MidiInput::stop() {}
  475. int MidiInput::getDefaultDeviceIndex() { return 0; }
  476. StringArray MidiInput::getDevices() { return StringArray(); }
  477. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return nullptr; }
  478. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return nullptr; }
  479. #endif