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.

613 lines
18KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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 (numPfds);
  105. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  106. HeapBlock <uint8> buffer (maxEventSize);
  107. while (! threadShouldExit())
  108. {
  109. 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
  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 int 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, 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 (maxEventSize, &midiParser);
  328. }
  329. ~MidiOutputDevice()
  330. {
  331. snd_midi_event_free (midiParser);
  332. port.deletePort();
  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. stopBackgroundThread();
  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