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.

667 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. #if JUCE_ALSA
  20. //==============================================================================
  21. namespace
  22. {
  23. //==============================================================================
  24. class AlsaClient : public ReferenceCountedObject
  25. {
  26. public:
  27. AlsaClient()
  28. {
  29. jassert (instance == nullptr);
  30. snd_seq_open (&handle, "default", SND_SEQ_OPEN_DUPLEX, 0);
  31. if (handle != nullptr)
  32. {
  33. snd_seq_nonblock (handle, SND_SEQ_NONBLOCK);
  34. snd_seq_set_client_name (handle, getAlsaMidiName().toRawUTF8());
  35. clientId = snd_seq_client_id (handle);
  36. // It's good idea to pre-allocate a good number of elements
  37. ports.ensureStorageAllocated (32);
  38. }
  39. }
  40. ~AlsaClient()
  41. {
  42. jassert (instance != nullptr);
  43. instance = nullptr;
  44. if (handle != nullptr)
  45. snd_seq_close (handle);
  46. jassert (activeCallbacks.get() == 0);
  47. if (inputThread)
  48. inputThread->stopThread (3000);
  49. }
  50. static String getAlsaMidiName()
  51. {
  52. #ifdef JUCE_ALSA_MIDI_NAME
  53. return JUCE_ALSA_MIDI_NAME;
  54. #else
  55. if (auto* app = JUCEApplicationBase::getInstance())
  56. return app->getApplicationName();
  57. return "JUCE";
  58. #endif
  59. }
  60. using Ptr = ReferenceCountedObjectPtr<AlsaClient>;
  61. //==============================================================================
  62. // represents an input or output port of the supplied AlsaClient
  63. struct Port
  64. {
  65. Port (AlsaClient& c, bool forInput) noexcept
  66. : client (c), isInput (forInput)
  67. {}
  68. ~Port()
  69. {
  70. if (isValid())
  71. {
  72. if (isInput)
  73. enableCallback (false);
  74. else
  75. snd_midi_event_free (midiParser);
  76. snd_seq_delete_simple_port (client.get(), portId);
  77. }
  78. }
  79. void connectWith (int sourceClient, int sourcePort) const noexcept
  80. {
  81. if (isInput)
  82. snd_seq_connect_from (client.get(), portId, sourceClient, sourcePort);
  83. else
  84. snd_seq_connect_to (client.get(), portId, sourceClient, sourcePort);
  85. }
  86. bool isValid() const noexcept
  87. {
  88. return client.get() != nullptr && portId >= 0;
  89. }
  90. void setupInput (MidiInput* input, MidiInputCallback* cb)
  91. {
  92. jassert (cb != nullptr && input != nullptr);
  93. callback = cb;
  94. midiInput = input;
  95. }
  96. void setupOutput()
  97. {
  98. jassert (! isInput);
  99. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  100. }
  101. void enableCallback (bool enable)
  102. {
  103. if (callbackEnabled != enable)
  104. {
  105. callbackEnabled = enable;
  106. if (enable)
  107. client.registerCallback();
  108. else
  109. client.unregisterCallback();
  110. }
  111. }
  112. bool sendMessageNow (const MidiMessage& message)
  113. {
  114. if (message.getRawDataSize() > maxEventSize)
  115. {
  116. maxEventSize = message.getRawDataSize();
  117. snd_midi_event_free (midiParser);
  118. snd_midi_event_new ((size_t) maxEventSize, &midiParser);
  119. }
  120. snd_seq_event_t event;
  121. snd_seq_ev_clear (&event);
  122. auto numBytes = (long) message.getRawDataSize();
  123. auto* data = message.getRawData();
  124. auto seqHandle = client.get();
  125. bool success = true;
  126. while (numBytes > 0)
  127. {
  128. auto numSent = snd_midi_event_encode (midiParser, data, numBytes, &event);
  129. if (numSent <= 0)
  130. {
  131. success = numSent == 0;
  132. break;
  133. }
  134. numBytes -= numSent;
  135. data += numSent;
  136. snd_seq_ev_set_source (&event, (unsigned char) portId);
  137. snd_seq_ev_set_subs (&event);
  138. snd_seq_ev_set_direct (&event);
  139. if (snd_seq_event_output_direct (seqHandle, &event) < 0)
  140. {
  141. success = false;
  142. break;
  143. }
  144. }
  145. snd_midi_event_reset_encode (midiParser);
  146. return success;
  147. }
  148. bool operator== (const Port& lhs) const noexcept
  149. {
  150. return portId != -1 && portId == lhs.portId;
  151. }
  152. void createPort (const String& name, bool enableSubscription)
  153. {
  154. if (auto seqHandle = client.get())
  155. {
  156. const unsigned int caps =
  157. isInput ? (SND_SEQ_PORT_CAP_WRITE | (enableSubscription ? SND_SEQ_PORT_CAP_SUBS_WRITE : 0))
  158. : (SND_SEQ_PORT_CAP_READ | (enableSubscription ? SND_SEQ_PORT_CAP_SUBS_READ : 0));
  159. portName = name;
  160. portId = snd_seq_create_simple_port (seqHandle, portName.toUTF8(), caps,
  161. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  162. SND_SEQ_PORT_TYPE_APPLICATION);
  163. }
  164. }
  165. void handleIncomingMidiMessage (const MidiMessage& message) const
  166. {
  167. callback->handleIncomingMidiMessage (midiInput, message);
  168. }
  169. void handlePartialSysexMessage (const uint8* messageData, int numBytesSoFar, double timeStamp)
  170. {
  171. callback->handlePartialSysexMessage (midiInput, messageData, numBytesSoFar, timeStamp);
  172. }
  173. AlsaClient& client;
  174. MidiInputCallback* callback = nullptr;
  175. snd_midi_event_t* midiParser = nullptr;
  176. MidiInput* midiInput = nullptr;
  177. String portName;
  178. int maxEventSize = 4096, portId = -1;
  179. bool callbackEnabled = false, isInput = false;
  180. };
  181. static Ptr getInstance()
  182. {
  183. if (instance == nullptr)
  184. instance = new AlsaClient();
  185. return instance;
  186. }
  187. void registerCallback()
  188. {
  189. if (inputThread == nullptr)
  190. inputThread.reset (new MidiInputThread (*this));
  191. if (++activeCallbacks == 1)
  192. inputThread->startThread();
  193. }
  194. void unregisterCallback()
  195. {
  196. jassert (activeCallbacks.get() > 0);
  197. if (--activeCallbacks == 0 && inputThread->isThreadRunning())
  198. inputThread->signalThreadShouldExit();
  199. }
  200. void handleIncomingMidiMessage (snd_seq_event* event, const MidiMessage& message)
  201. {
  202. if (event->dest.port < ports.size() && ports[event->dest.port]->callbackEnabled)
  203. ports[event->dest.port]->handleIncomingMidiMessage (message);
  204. }
  205. void handlePartialSysexMessage (snd_seq_event* event, const uint8* messageData, int numBytesSoFar, double timeStamp)
  206. {
  207. if (event->dest.port < ports.size()
  208. && ports[event->dest.port]->callbackEnabled)
  209. ports[event->dest.port]->handlePartialSysexMessage (messageData, numBytesSoFar, timeStamp);
  210. }
  211. snd_seq_t* get() const noexcept { return handle; }
  212. int getId() const noexcept { return clientId; }
  213. Port* createPort (const String& name, bool forInput, bool enableSubscription)
  214. {
  215. auto port = new Port (*this, forInput);
  216. port->createPort (name, enableSubscription);
  217. ports.set (port->portId, port);
  218. incReferenceCount();
  219. return port;
  220. }
  221. void deletePort (Port* port)
  222. {
  223. ports.set (port->portId, nullptr);
  224. decReferenceCount();
  225. }
  226. private:
  227. snd_seq_t* handle = nullptr;
  228. int clientId = 0;
  229. OwnedArray<Port> ports;
  230. Atomic<int> activeCallbacks;
  231. CriticalSection callbackLock;
  232. static AlsaClient* instance;
  233. //==============================================================================
  234. class MidiInputThread : public Thread
  235. {
  236. public:
  237. MidiInputThread (AlsaClient& c)
  238. : Thread ("JUCE MIDI Input"), client (c)
  239. {
  240. jassert (client.get() != nullptr);
  241. }
  242. void run() override
  243. {
  244. auto seqHandle = client.get();
  245. const int maxEventSize = 16 * 1024;
  246. snd_midi_event_t* midiParser;
  247. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  248. {
  249. auto numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  250. HeapBlock<pollfd> pfd (numPfds);
  251. snd_seq_poll_descriptors (seqHandle, pfd, (unsigned int) numPfds, POLLIN);
  252. HeapBlock<uint8> buffer (maxEventSize);
  253. while (! threadShouldExit())
  254. {
  255. 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
  256. {
  257. if (threadShouldExit())
  258. break;
  259. do
  260. {
  261. snd_seq_event_t* inputEvent = nullptr;
  262. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  263. {
  264. // xxx what about SYSEXes that are too big for the buffer?
  265. auto numBytes = snd_midi_event_decode (midiParser, buffer,
  266. maxEventSize, inputEvent);
  267. snd_midi_event_reset_decode (midiParser);
  268. concatenator.pushMidiData (buffer, (int) numBytes,
  269. Time::getMillisecondCounter() * 0.001,
  270. inputEvent, client);
  271. snd_seq_free_event (inputEvent);
  272. }
  273. }
  274. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  275. }
  276. }
  277. snd_midi_event_free (midiParser);
  278. }
  279. }
  280. private:
  281. AlsaClient& client;
  282. MidiDataConcatenator concatenator { 2048 };
  283. };
  284. std::unique_ptr<MidiInputThread> inputThread;
  285. };
  286. AlsaClient* AlsaClient::instance = nullptr;
  287. //==============================================================================
  288. static String getFormattedPortIdentifier (int clientId, int portId)
  289. {
  290. return String (clientId) + "-" + String (portId);
  291. }
  292. static AlsaClient::Port* iterateMidiClient (const AlsaClient::Ptr& client,
  293. snd_seq_client_info_t* clientInfo,
  294. bool forInput,
  295. Array<MidiDeviceInfo>& devices,
  296. const String& deviceIdentifierToOpen)
  297. {
  298. AlsaClient::Port* port = nullptr;
  299. auto seqHandle = client->get();
  300. snd_seq_port_info_t* portInfo = nullptr;
  301. snd_seq_port_info_alloca (&portInfo);
  302. jassert (portInfo != nullptr);
  303. auto numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  304. auto sourceClient = snd_seq_client_info_get_client (clientInfo);
  305. snd_seq_port_info_set_client (portInfo, sourceClient);
  306. snd_seq_port_info_set_port (portInfo, -1);
  307. while (--numPorts >= 0)
  308. {
  309. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  310. && (snd_seq_port_info_get_capability (portInfo)
  311. & (forInput ? SND_SEQ_PORT_CAP_SUBS_READ : SND_SEQ_PORT_CAP_SUBS_WRITE)) != 0)
  312. {
  313. String portName (snd_seq_port_info_get_name (portInfo));
  314. auto portID = snd_seq_port_info_get_port (portInfo);
  315. MidiDeviceInfo device (portName, getFormattedPortIdentifier (sourceClient, portID));
  316. devices.add (device);
  317. if (deviceIdentifierToOpen.isNotEmpty() && deviceIdentifierToOpen == device.identifier)
  318. {
  319. if (portID != -1)
  320. {
  321. port = client->createPort (portName, forInput, false);
  322. jassert (port->isValid());
  323. port->connectWith (sourceClient, portID);
  324. break;
  325. }
  326. }
  327. }
  328. }
  329. return port;
  330. }
  331. static AlsaClient::Port* iterateMidiDevices (bool forInput,
  332. Array<MidiDeviceInfo>& devices,
  333. const String& deviceIdentifierToOpen)
  334. {
  335. AlsaClient::Port* port = nullptr;
  336. auto client = AlsaClient::getInstance();
  337. if (auto seqHandle = client->get())
  338. {
  339. snd_seq_system_info_t* systemInfo = nullptr;
  340. snd_seq_client_info_t* clientInfo = nullptr;
  341. snd_seq_system_info_alloca (&systemInfo);
  342. jassert (systemInfo != nullptr);
  343. if (snd_seq_system_info (seqHandle, systemInfo) == 0)
  344. {
  345. snd_seq_client_info_alloca (&clientInfo);
  346. jassert (clientInfo != nullptr);
  347. auto numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  348. while (--numClients >= 0)
  349. {
  350. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  351. {
  352. port = iterateMidiClient (client, clientInfo, forInput,
  353. devices, deviceIdentifierToOpen);
  354. if (port != nullptr)
  355. break;
  356. }
  357. }
  358. }
  359. }
  360. return port;
  361. }
  362. } // namespace
  363. //==============================================================================
  364. Array<MidiDeviceInfo> MidiInput::getAvailableDevices()
  365. {
  366. Array<MidiDeviceInfo> devices;
  367. iterateMidiDevices (true, devices, {});
  368. return devices;
  369. }
  370. MidiDeviceInfo MidiInput::getDefaultDevice()
  371. {
  372. return getAvailableDevices().getFirst();
  373. }
  374. std::unique_ptr<MidiInput> MidiInput::openDevice (const String& deviceIdentifier, MidiInputCallback* callback)
  375. {
  376. if (deviceIdentifier.isEmpty())
  377. return {};
  378. Array<MidiDeviceInfo> devices;
  379. auto* port = iterateMidiDevices (true, devices, deviceIdentifier);
  380. if (port == nullptr || ! port->isValid())
  381. return {};
  382. jassert (port->isValid());
  383. std::unique_ptr<MidiInput> midiInput (new MidiInput (port->portName, deviceIdentifier));
  384. port->setupInput (midiInput.get(), callback);
  385. midiInput->internal = port;
  386. return midiInput;
  387. }
  388. std::unique_ptr<MidiInput> MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  389. {
  390. auto client = AlsaClient::getInstance();
  391. auto* port = client->createPort (deviceName, true, true);
  392. if (port == nullptr || ! port->isValid())
  393. return {};
  394. std::unique_ptr<MidiInput> midiInput (new MidiInput (deviceName, getFormattedPortIdentifier (client->getId(), port->portId)));
  395. port->setupInput (midiInput.get(), callback);
  396. midiInput->internal = port;
  397. return midiInput;
  398. }
  399. StringArray MidiInput::getDevices()
  400. {
  401. StringArray deviceNames;
  402. for (auto& d : getAvailableDevices())
  403. deviceNames.add (d.name);
  404. deviceNames.appendNumbersToDuplicates (true, true);
  405. return deviceNames;
  406. }
  407. int MidiInput::getDefaultDeviceIndex()
  408. {
  409. return 0;
  410. }
  411. std::unique_ptr<MidiInput> MidiInput::openDevice (int index, MidiInputCallback* callback)
  412. {
  413. return openDevice (getAvailableDevices()[index].identifier, callback);
  414. }
  415. MidiInput::MidiInput (const String& deviceName, const String& deviceIdentifier)
  416. : deviceInfo (deviceName, deviceIdentifier)
  417. {
  418. }
  419. MidiInput::~MidiInput()
  420. {
  421. stop();
  422. AlsaClient::getInstance()->deletePort (static_cast<AlsaClient::Port*> (internal));
  423. }
  424. void MidiInput::start()
  425. {
  426. static_cast<AlsaClient::Port*> (internal)->enableCallback (true);
  427. }
  428. void MidiInput::stop()
  429. {
  430. static_cast<AlsaClient::Port*> (internal)->enableCallback (false);
  431. }
  432. //==============================================================================
  433. Array<MidiDeviceInfo> MidiOutput::getAvailableDevices()
  434. {
  435. Array<MidiDeviceInfo> devices;
  436. iterateMidiDevices (false, devices, {});
  437. return devices;
  438. }
  439. MidiDeviceInfo MidiOutput::getDefaultDevice()
  440. {
  441. return getAvailableDevices().getFirst();
  442. }
  443. std::unique_ptr<MidiOutput> MidiOutput::openDevice (const String& deviceIdentifier)
  444. {
  445. if (deviceIdentifier.isEmpty())
  446. return {};
  447. Array<MidiDeviceInfo> devices;
  448. auto* port = iterateMidiDevices (false, devices, deviceIdentifier);
  449. if (port == nullptr || ! port->isValid())
  450. return {};
  451. std::unique_ptr<MidiOutput> midiOutput (new MidiOutput (port->portName, deviceIdentifier));
  452. port->setupOutput();
  453. midiOutput->internal = port;
  454. return midiOutput;
  455. }
  456. std::unique_ptr<MidiOutput> MidiOutput::createNewDevice (const String& deviceName)
  457. {
  458. auto client = AlsaClient::getInstance();
  459. auto* port = client->createPort (deviceName, false, true);
  460. if (port == nullptr || ! port->isValid())
  461. return {};
  462. std::unique_ptr<MidiOutput> midiOutput (new MidiOutput (deviceName, getFormattedPortIdentifier (client->getId(), port->portId)));
  463. port->setupOutput();
  464. midiOutput->internal = port;
  465. return midiOutput;
  466. }
  467. StringArray MidiOutput::getDevices()
  468. {
  469. StringArray deviceNames;
  470. for (auto& d : getAvailableDevices())
  471. deviceNames.add (d.name);
  472. deviceNames.appendNumbersToDuplicates (true, true);
  473. return deviceNames;
  474. }
  475. int MidiOutput::getDefaultDeviceIndex()
  476. {
  477. return 0;
  478. }
  479. std::unique_ptr<MidiOutput> MidiOutput::openDevice (int index)
  480. {
  481. return openDevice (getAvailableDevices()[index].identifier);
  482. }
  483. MidiOutput::~MidiOutput()
  484. {
  485. stopBackgroundThread();
  486. AlsaClient::getInstance()->deletePort (static_cast<AlsaClient::Port*> (internal));
  487. }
  488. void MidiOutput::sendMessageNow (const MidiMessage& message)
  489. {
  490. static_cast<AlsaClient::Port*> (internal)->sendMessageNow (message);
  491. }
  492. //==============================================================================
  493. #else
  494. // (These are just stub functions if ALSA is unavailable...)
  495. MidiInput::MidiInput (const String& deviceName, const String& deviceID)
  496. : deviceInfo (deviceName, deviceID)
  497. {
  498. }
  499. MidiInput::~MidiInput() {}
  500. void MidiInput::start() {}
  501. void MidiInput::stop() {}
  502. Array<MidiDeviceInfo> MidiInput::getAvailableDevices() { return {}; }
  503. MidiDeviceInfo MidiInput::getDefaultDevice() { return {}; }
  504. std::unique_ptr<MidiInput> MidiInput::openDevice (const String&, MidiInputCallback*) { return {}; }
  505. std::unique_ptr<MidiInput> MidiInput::createNewDevice (const String&, MidiInputCallback*) { return {}; }
  506. StringArray MidiInput::getDevices() { return {}; }
  507. int MidiInput::getDefaultDeviceIndex() { return 0;}
  508. std::unique_ptr<MidiInput> MidiInput::openDevice (int, MidiInputCallback*) { return {}; }
  509. MidiOutput::~MidiOutput() {}
  510. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  511. Array<MidiDeviceInfo> MidiOutput::getAvailableDevices() { return {}; }
  512. MidiDeviceInfo MidiOutput::getDefaultDevice() { return {}; }
  513. std::unique_ptr<MidiOutput> MidiOutput::openDevice (const String&) { return {}; }
  514. std::unique_ptr<MidiOutput> MidiOutput::createNewDevice (const String&) { return {}; }
  515. StringArray MidiOutput::getDevices() { return {}; }
  516. int MidiOutput::getDefaultDeviceIndex() { return 0;}
  517. std::unique_ptr<MidiOutput> MidiOutput::openDevice (int) { return {}; }
  518. #endif
  519. } // namespace juce