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.

993 lines
32KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2014 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the GPL.txt file
  16. */
  17. #include "CarlaEngineGraph.hpp"
  18. #include "CarlaEngineInternal.hpp"
  19. #include "CarlaBackendUtils.hpp"
  20. #include "CarlaStringList.hpp"
  21. #include "RtLinkedList.hpp"
  22. #include "juce_audio_devices.h"
  23. using namespace juce;
  24. CARLA_BACKEND_START_NAMESPACE
  25. // -------------------------------------------------------------------------------------------------------------------
  26. // Global static data
  27. static CharStringListPtr gDeviceNames;
  28. static OwnedArray<AudioIODeviceType> gDeviceTypes;
  29. struct JuceCleanup : public DeletedAtShutdown {
  30. JuceCleanup() noexcept {}
  31. ~JuceCleanup()
  32. {
  33. gDeviceTypes.clear(true);
  34. }
  35. };
  36. // -------------------------------------------------------------------------------------------------------------------
  37. // Cleanup
  38. static void initJuceDevicesIfNeeded()
  39. {
  40. static AudioDeviceManager sDeviceManager;
  41. if (gDeviceTypes.size() != 0)
  42. return;
  43. sDeviceManager.createAudioDeviceTypes(gDeviceTypes);
  44. CARLA_SAFE_ASSERT_RETURN(gDeviceTypes.size() != 0,);
  45. new JuceCleanup();
  46. // remove JACK from device list
  47. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  48. {
  49. if (gDeviceTypes[i]->getTypeName() == "JACK")
  50. {
  51. gDeviceTypes.remove(i, true);
  52. break;
  53. }
  54. }
  55. }
  56. // -------------------------------------------------------------------------------------------------------------------
  57. // Juce Engine
  58. class CarlaEngineJuce : public CarlaEngine,
  59. public CarlaEngineGraphImpl,
  60. public AudioIODeviceCallback,
  61. public MidiInputCallback
  62. {
  63. public:
  64. CarlaEngineJuce(AudioIODeviceType* const devType)
  65. : CarlaEngine(),
  66. AudioIODeviceCallback(),
  67. fDevice(),
  68. fDeviceType(devType),
  69. fMidiIns(),
  70. fMidiInEvents(),
  71. fMidiOuts(),
  72. fMidiOutMutex(),
  73. leakDetector_CarlaEngineJuce()
  74. {
  75. carla_debug("CarlaEngineJuce::CarlaEngineJuce(%p)", devType);
  76. // just to make sure
  77. pData->options.transportMode = ENGINE_TRANSPORT_MODE_INTERNAL;
  78. }
  79. ~CarlaEngineJuce() override
  80. {
  81. carla_debug("CarlaEngineJuce::~CarlaEngineJuce()");
  82. }
  83. // -------------------------------------
  84. bool init(const char* const clientName) override
  85. {
  86. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr && clientName[0] != '\0', false);
  87. carla_debug("CarlaEngineJuce::init(\"%s\")", clientName);
  88. if (pData->options.processMode != ENGINE_PROCESS_MODE_CONTINUOUS_RACK && pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  89. {
  90. setLastError("Invalid process mode");
  91. return false;
  92. }
  93. String deviceName;
  94. if (pData->options.audioDevice != nullptr && pData->options.audioDevice[0] != '\0')
  95. {
  96. deviceName = pData->options.audioDevice;
  97. }
  98. else
  99. {
  100. const int defaultIndex(fDeviceType->getDefaultDeviceIndex(false));
  101. StringArray deviceNames(fDeviceType->getDeviceNames());
  102. if (defaultIndex >= 0 && defaultIndex < deviceNames.size())
  103. deviceName = deviceNames[defaultIndex];
  104. }
  105. if (deviceName.isEmpty())
  106. {
  107. setLastError("Audio device has not been selected yet and a default one is not available");
  108. return false;
  109. }
  110. fDevice = fDeviceType->createDevice(deviceName, deviceName);
  111. if (fDevice == nullptr)
  112. {
  113. setLastError("Failed to create device");
  114. return false;
  115. }
  116. StringArray inputNames(fDevice->getInputChannelNames());
  117. StringArray outputNames(fDevice->getOutputChannelNames());
  118. if (inputNames.size() < 0 || outputNames.size() <= 0)
  119. {
  120. setLastError("Selected device does not have any outputs");
  121. return false;
  122. }
  123. BigInteger inputChannels;
  124. inputChannels.setRange(0, inputNames.size(), true);
  125. BigInteger outputChannels;
  126. outputChannels.setRange(0, outputNames.size(), true);
  127. String error = fDevice->open(inputChannels, outputChannels, pData->options.audioSampleRate, static_cast<int>(pData->options.audioBufferSize));
  128. if (error.isNotEmpty())
  129. {
  130. setLastError(error.toUTF8());
  131. fDevice = nullptr;
  132. return false;
  133. }
  134. if (! pData->init(clientName))
  135. {
  136. close();
  137. setLastError("Failed to init internal data");
  138. return false;
  139. }
  140. pData->bufferSize = static_cast<uint32_t>(fDevice->getCurrentBufferSizeSamples());
  141. pData->sampleRate = fDevice->getCurrentSampleRate();
  142. pData->graph.create(static_cast<uint32_t>(inputNames.size()), static_cast<uint32_t>(outputNames.size()));
  143. fDevice->start(this);
  144. patchbayRefresh(false);
  145. callback(ENGINE_CALLBACK_ENGINE_STARTED, 0, pData->options.processMode, pData->options.transportMode, 0.0f, getCurrentDriverName());
  146. return true;
  147. }
  148. bool close() override
  149. {
  150. carla_debug("CarlaEngineJuce::close()");
  151. bool hasError = false;
  152. // stop stream first
  153. if (fDevice != nullptr && fDevice->isPlaying())
  154. fDevice->stop();
  155. // clear engine data
  156. CarlaEngine::close();
  157. pData->graph.destroy();
  158. for (LinkedList<MidiInPort>::Itenerator it = fMidiIns.begin(); it.valid(); it.next())
  159. {
  160. MidiInPort& inPort(it.getValue());
  161. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  162. inPort.port->stop();
  163. delete inPort.port;
  164. }
  165. fMidiIns.clear();
  166. fMidiInEvents.clear();
  167. fMidiOutMutex.lock();
  168. for (LinkedList<MidiOutPort>::Itenerator it = fMidiOuts.begin(); it.valid(); it.next())
  169. {
  170. MidiOutPort& outPort(it.getValue());
  171. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  172. outPort.port->stopBackgroundThread();
  173. delete outPort.port;
  174. }
  175. fMidiOuts.clear();
  176. fMidiOutMutex.unlock();
  177. // close stream
  178. if (fDevice != nullptr)
  179. {
  180. if (fDevice->isOpen())
  181. fDevice->close();
  182. fDevice = nullptr;
  183. }
  184. return !hasError;
  185. }
  186. bool isRunning() const noexcept override
  187. {
  188. return fDevice != nullptr && fDevice->isOpen();
  189. }
  190. bool isOffline() const noexcept override
  191. {
  192. return false;
  193. }
  194. EngineType getType() const noexcept override
  195. {
  196. return kEngineTypeJuce;
  197. }
  198. const char* getCurrentDriverName() const noexcept override
  199. {
  200. return fDeviceType->getTypeName().toRawUTF8();
  201. }
  202. // -------------------------------------------------------------------
  203. // Patchbay
  204. bool patchbayRefresh(const bool /*external*/) override
  205. {
  206. CARLA_SAFE_ASSERT_RETURN(pData->graph.isReady(), false);
  207. //fUsedMidiPorts.clear();
  208. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  209. patchbayRefreshRack();
  210. else
  211. patchbayRefreshPatchbay();
  212. return true;
  213. }
  214. void patchbayRefreshRack()
  215. {
  216. RackGraph* const graph(pData->graph.getRackGraph());
  217. CARLA_SAFE_ASSERT_RETURN(graph != nullptr,);
  218. String deviceName(fDevice->getName());
  219. if (deviceName.isNotEmpty())
  220. deviceName = deviceName.dropLastCharacters(deviceName.fromFirstOccurrenceOf(", ", true, false).length());
  221. graph->refreshConnections(this, deviceName.toRawUTF8());
  222. char strBuf[STR_MAX+1];
  223. strBuf[STR_MAX] = '\0';
  224. // Audio In
  225. {
  226. StringArray inputNames(fDevice->getInputChannelNames());
  227. if (deviceName.isNotEmpty())
  228. std::snprintf(strBuf, STR_MAX, "Capture (%s)", deviceName.toRawUTF8());
  229. else
  230. std::strncpy(strBuf, "Capture", STR_MAX);
  231. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, RACK_GRAPH_GROUP_AUDIO_IN, PATCHBAY_ICON_HARDWARE, -1, 0.0f, strBuf);
  232. for (int i=0, count=inputNames.size(); i<count; ++i)
  233. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, RACK_GRAPH_GROUP_AUDIO_IN, static_cast<int>(i)+1, PATCHBAY_PORT_TYPE_AUDIO, 0.0f, inputNames[i].toRawUTF8());
  234. }
  235. // Audio Out
  236. {
  237. StringArray outputNames(fDevice->getOutputChannelNames());
  238. if (deviceName.isNotEmpty())
  239. std::snprintf(strBuf, STR_MAX, "Playback (%s)", deviceName.toRawUTF8());
  240. else
  241. std::strncpy(strBuf, "Playback", STR_MAX);
  242. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, RACK_GRAPH_GROUP_AUDIO_OUT, PATCHBAY_ICON_HARDWARE, -1, 0.0f, strBuf);
  243. for (int i=0, count=outputNames.size(); i<count; ++i)
  244. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, RACK_GRAPH_GROUP_AUDIO_OUT, static_cast<int>(i)+1, PATCHBAY_PORT_TYPE_AUDIO|PATCHBAY_PORT_IS_INPUT, 0.0f, outputNames[i].toRawUTF8());
  245. }
  246. // MIDI In
  247. {
  248. StringArray midiIns(MidiInput::getDevices());
  249. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, RACK_GRAPH_GROUP_MIDI_IN, PATCHBAY_ICON_HARDWARE, -1, 0.0f, "Readable MIDI ports");
  250. for (int i=0, count=midiIns.size(); i<count; ++i)
  251. {
  252. String portName(midiIns[i]);
  253. std::snprintf(strBuf, STR_MAX, "Readable MIDI ports:%s", portName.toRawUTF8());
  254. PortNameToId portNameToId;
  255. portNameToId.setData(RACK_GRAPH_GROUP_MIDI_IN, static_cast<uint>(i)+1, portName.toRawUTF8(), strBuf);
  256. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, portNameToId.group, static_cast<int>(portNameToId.port), PATCHBAY_PORT_TYPE_MIDI, 0.0f, portNameToId.name);
  257. graph->midi.ins.append(portNameToId);
  258. }
  259. }
  260. // MIDI Out
  261. {
  262. StringArray midiOuts(MidiOutput::getDevices());
  263. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, RACK_GRAPH_GROUP_MIDI_OUT, PATCHBAY_ICON_HARDWARE, -1, 0.0f, "Writable MIDI ports");
  264. for (int i=0, count=midiOuts.size(); i<count; ++i)
  265. {
  266. String portName(midiOuts[i]);
  267. std::snprintf(strBuf, STR_MAX, "Writable MIDI ports:%s", portName.toRawUTF8());
  268. PortNameToId portNameToId;
  269. portNameToId.setData(RACK_GRAPH_GROUP_MIDI_OUT, static_cast<uint>(i)+1, portName.toRawUTF8(), strBuf);
  270. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, portNameToId.group, static_cast<int>(portNameToId.port), PATCHBAY_PORT_TYPE_MIDI|PATCHBAY_PORT_IS_INPUT, 0.0f, portNameToId.name);
  271. graph->midi.outs.append(portNameToId);
  272. }
  273. }
  274. // Connections
  275. graph->audio.mutex.lock();
  276. for (LinkedList<uint>::Itenerator it = graph->audio.connectedIn1.begin(); it.valid(); it.next())
  277. {
  278. const uint& portId(it.getValue());
  279. //CARLA_SAFE_ASSERT_CONTINUE(portId < fAudioInCount);
  280. ConnectionToId connectionToId;
  281. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_AUDIO_IN, portId, RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_AUDIO_IN1);
  282. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  283. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  284. graph->connections.list.append(connectionToId);
  285. }
  286. for (LinkedList<uint>::Itenerator it = graph->audio.connectedIn2.begin(); it.valid(); it.next())
  287. {
  288. const uint& portId(it.getValue());
  289. //CARLA_SAFE_ASSERT_CONTINUE(portId < fAudioInCount);
  290. ConnectionToId connectionToId;
  291. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_AUDIO_IN, portId, RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_AUDIO_IN2);
  292. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  293. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  294. graph->connections.list.append(connectionToId);
  295. }
  296. for (LinkedList<uint>::Itenerator it = graph->audio.connectedOut1.begin(); it.valid(); it.next())
  297. {
  298. const uint& portId(it.getValue());
  299. //CARLA_SAFE_ASSERT_CONTINUE(portId < fAudioOutCount);
  300. ConnectionToId connectionToId;
  301. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_AUDIO_OUT1, RACK_GRAPH_GROUP_AUDIO_OUT, portId);
  302. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  303. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  304. graph->connections.list.append(connectionToId);
  305. }
  306. for (LinkedList<uint>::Itenerator it = graph->audio.connectedOut2.begin(); it.valid(); it.next())
  307. {
  308. const uint& portId(it.getValue());
  309. //CARLA_SAFE_ASSERT_CONTINUE(portId < fAudioOutCount);
  310. ConnectionToId connectionToId;
  311. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_AUDIO_OUT2, RACK_GRAPH_GROUP_AUDIO_OUT, portId);
  312. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  313. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  314. graph->connections.list.append(connectionToId);
  315. }
  316. graph->audio.mutex.unlock();
  317. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin(); it.valid(); it.next())
  318. {
  319. const MidiInPort& inPort(it.getValue());
  320. const uint portId(graph->midi.getPortId(true, inPort.name));
  321. CARLA_SAFE_ASSERT_CONTINUE(portId < graph->midi.ins.count());
  322. ConnectionToId connectionToId;
  323. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_MIDI_IN, portId, RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_MIDI_IN);
  324. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  325. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  326. graph->connections.list.append(connectionToId);
  327. }
  328. fMidiOutMutex.lock();
  329. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  330. {
  331. const MidiOutPort& outPort(it.getValue());
  332. const uint portId(graph->midi.getPortId(false, outPort.name));
  333. CARLA_SAFE_ASSERT_CONTINUE(portId < graph->midi.outs.count());
  334. ConnectionToId connectionToId;
  335. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_MIDI_OUT, RACK_GRAPH_GROUP_MIDI_OUT, portId);
  336. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  337. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  338. graph->connections.list.append(connectionToId);
  339. }
  340. fMidiOutMutex.unlock();
  341. }
  342. void patchbayRefreshPatchbay() noexcept
  343. {
  344. PatchbayGraph* const graph(pData->graph.getPatchbayGraph());
  345. CARLA_SAFE_ASSERT_RETURN(graph != nullptr,);
  346. graph->refreshConnections(this);
  347. }
  348. // -------------------------------------------------------------------
  349. protected:
  350. void audioDeviceIOCallback(const float** inputChannelData, int numInputChannels, float** outputChannelData, int numOutputChannels, int numSamples) override
  351. {
  352. const PendingRtEventsRunner prt(this);
  353. // assert juce buffers
  354. CARLA_SAFE_ASSERT_RETURN(numInputChannels >= 0,);
  355. CARLA_SAFE_ASSERT_RETURN(numOutputChannels > 0,);
  356. CARLA_SAFE_ASSERT_RETURN(outputChannelData != nullptr,);
  357. CARLA_SAFE_ASSERT_RETURN(numSamples == static_cast<int>(pData->bufferSize),);
  358. const uint32_t nframes(static_cast<uint32_t>(numSamples));
  359. // initialize juce output
  360. for (int i=0; i < numOutputChannels; ++i)
  361. FloatVectorOperations::clear(outputChannelData[i], numSamples);
  362. // initialize events
  363. carla_zeroStruct<EngineEvent>(pData->events.in, kMaxEngineEventInternalCount);
  364. carla_zeroStruct<EngineEvent>(pData->events.out, kMaxEngineEventInternalCount);
  365. if (fMidiInEvents.mutex.tryLock())
  366. {
  367. uint32_t engineEventIndex = 0;
  368. fMidiInEvents.splice();
  369. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin(); it.valid(); it.next())
  370. {
  371. const RtMidiEvent& midiEvent(it.getValue());
  372. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  373. if (midiEvent.time < pData->timeInfo.frame)
  374. {
  375. engineEvent.time = 0;
  376. }
  377. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  378. {
  379. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  380. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  381. }
  382. else
  383. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  384. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data);
  385. if (engineEventIndex >= kMaxEngineEventInternalCount)
  386. break;
  387. }
  388. fMidiInEvents.data.clear();
  389. fMidiInEvents.mutex.unlock();
  390. }
  391. pData->graph.process(pData, inputChannelData, outputChannelData, static_cast<uint32_t>(numSamples));
  392. fMidiOutMutex.lock();
  393. if (fMidiOuts.count() > 0)
  394. {
  395. uint8_t size = 0;
  396. uint8_t data[3] = { 0, 0, 0 };
  397. const uint8_t* dataPtr = data;
  398. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  399. {
  400. const EngineEvent& engineEvent(pData->events.out[i]);
  401. if (engineEvent.type == kEngineEventTypeNull)
  402. break;
  403. else if (engineEvent.type == kEngineEventTypeControl)
  404. {
  405. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  406. ctrlEvent.convertToMidiData(engineEvent.channel, size, data);
  407. dataPtr = data;
  408. }
  409. else if (engineEvent.type == kEngineEventTypeMidi)
  410. {
  411. const EngineMidiEvent& midiEvent(engineEvent.midi);
  412. size = midiEvent.size;
  413. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  414. dataPtr = midiEvent.dataExt;
  415. else
  416. dataPtr = midiEvent.data;
  417. }
  418. else
  419. {
  420. continue;
  421. }
  422. if (size > 0)
  423. {
  424. MidiMessage message(static_cast<const void*>(dataPtr), static_cast<int>(size), static_cast<double>(engineEvent.time)/nframes);
  425. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  426. {
  427. MidiOutPort& outPort(it.getValue());
  428. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  429. outPort.port->sendMessageNow(message);
  430. }
  431. }
  432. }
  433. }
  434. fMidiOutMutex.unlock();
  435. }
  436. void audioDeviceAboutToStart(AudioIODevice* /*device*/) override
  437. {
  438. }
  439. void audioDeviceStopped() override
  440. {
  441. }
  442. void audioDeviceError(const String& errorMessage) override
  443. {
  444. callback(ENGINE_CALLBACK_ERROR, 0, 0, 0, 0.0f, errorMessage.toRawUTF8());
  445. }
  446. // -------------------------------------------------------------------
  447. void handleIncomingMidiMessage(MidiInput* /*source*/, const MidiMessage& message) override
  448. {
  449. const int messageSize(message.getRawDataSize());
  450. if (messageSize <= 0 || messageSize > EngineMidiEvent::kDataSize)
  451. return;
  452. const uint8_t* const messageData(message.getRawData());
  453. RtMidiEvent midiEvent;
  454. midiEvent.time = 0; // TODO
  455. midiEvent.size = static_cast<uint8_t>(messageSize);
  456. int i=0;
  457. for (; i < messageSize; ++i)
  458. midiEvent.data[i] = messageData[i];
  459. for (; i < EngineMidiEvent::kDataSize; ++i)
  460. midiEvent.data[i] = 0;
  461. fMidiInEvents.append(midiEvent);
  462. }
  463. // -------------------------------------------------------------------
  464. bool connectRackMidiInPort(const char* const portName) override
  465. {
  466. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  467. carla_debug("CarlaEngineJuce::connectRackMidiInPort(\"%s\")", portName);
  468. RackGraph* const graph(pData->graph.getRackGraph());
  469. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  470. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  471. StringArray midiIns(MidiInput::getDevices());
  472. if (! midiIns.contains(portName))
  473. return false;
  474. MidiInput* const juceMidiIn(MidiInput::openDevice(midiIns.indexOf(portName), this));
  475. juceMidiIn->start();
  476. MidiInPort midiPort;
  477. midiPort.port = juceMidiIn;
  478. std::strncpy(midiPort.name, portName, STR_MAX);
  479. midiPort.name[STR_MAX] = '\0';
  480. fMidiIns.append(midiPort);
  481. return true;
  482. }
  483. bool connectRackMidiOutPort(const char* const portName) override
  484. {
  485. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  486. carla_debug("CarlaEngineJuce::connectRackMidiOutPort(\"%s\")", portName);
  487. RackGraph* const graph(pData->graph.getRackGraph());
  488. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  489. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  490. StringArray midiOuts(MidiOutput::getDevices());
  491. if (! midiOuts.contains(portName))
  492. return false;
  493. MidiOutput* const juceMidiOut(MidiOutput::openDevice(midiOuts.indexOf(portName)));
  494. juceMidiOut->startBackgroundThread();
  495. MidiOutPort midiPort;
  496. midiPort.port = juceMidiOut;
  497. std::strncpy(midiPort.name, portName, STR_MAX);
  498. midiPort.name[STR_MAX] = '\0';
  499. const CarlaMutexLocker cml(fMidiOutMutex);
  500. fMidiOuts.append(midiPort);
  501. return true;
  502. }
  503. bool disconnectRackMidiInPort(const char* const portName) override
  504. {
  505. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  506. carla_debug("CarlaEngineRtAudio::disconnectRackMidiInPort(\"%s\")", portName);
  507. RackGraph* const graph(pData->graph.getRackGraph());
  508. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  509. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  510. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin(); it.valid(); it.next())
  511. {
  512. MidiInPort& inPort(it.getValue());
  513. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  514. if (std::strcmp(inPort.name, portName) != 0)
  515. continue;
  516. inPort.port->stop();
  517. delete inPort.port;
  518. fMidiIns.remove(it);
  519. return true;
  520. }
  521. return false;
  522. }
  523. bool disconnectRackMidiOutPort(const char* const portName) override
  524. {
  525. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  526. carla_debug("CarlaEngineRtAudio::disconnectRackMidiOutPort(\"%s\")", portName);
  527. RackGraph* const graph(pData->graph.getRackGraph());
  528. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  529. CARLA_SAFE_ASSERT_RETURN(graph->midi.outs.count() > 0, false);
  530. const CarlaMutexLocker cml(fMidiOutMutex);
  531. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  532. {
  533. MidiOutPort& outPort(it.getValue());
  534. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  535. if (std::strcmp(outPort.name, portName) != 0)
  536. continue;
  537. outPort.port->stopBackgroundThread();
  538. delete outPort.port;
  539. fMidiOuts.remove(it);
  540. return true;
  541. }
  542. return false;
  543. }
  544. // -------------------------------------
  545. private:
  546. ScopedPointer<AudioIODevice> fDevice;
  547. AudioIODeviceType* const fDeviceType;
  548. struct MidiInPort {
  549. MidiInput* port;
  550. char name[STR_MAX+1];
  551. };
  552. struct MidiOutPort {
  553. MidiOutput* port;
  554. char name[STR_MAX+1];
  555. };
  556. struct RtMidiEvent {
  557. uint64_t time; // needs to compare to internal time
  558. uint8_t size;
  559. uint8_t data[EngineMidiEvent::kDataSize];
  560. };
  561. struct RtMidiEvents {
  562. CarlaMutex mutex;
  563. RtLinkedList<RtMidiEvent>::Pool dataPool;
  564. RtLinkedList<RtMidiEvent> data;
  565. RtLinkedList<RtMidiEvent> dataPending;
  566. RtMidiEvents()
  567. : mutex(),
  568. dataPool(512, 512),
  569. data(dataPool),
  570. dataPending(dataPool) {}
  571. ~RtMidiEvents()
  572. {
  573. clear();
  574. }
  575. void append(const RtMidiEvent& event)
  576. {
  577. mutex.lock();
  578. dataPending.append(event);
  579. mutex.unlock();
  580. }
  581. void clear()
  582. {
  583. mutex.lock();
  584. data.clear();
  585. dataPending.clear();
  586. mutex.unlock();
  587. }
  588. void splice()
  589. {
  590. if (dataPending.count() > 0)
  591. dataPending.moveTo(data, true /* append */);
  592. }
  593. };
  594. LinkedList<MidiInPort> fMidiIns;
  595. RtMidiEvents fMidiInEvents;
  596. LinkedList<MidiOutPort> fMidiOuts;
  597. CarlaMutex fMidiOutMutex;
  598. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJuce)
  599. };
  600. // -----------------------------------------
  601. CarlaEngine* CarlaEngine::newJuce(const AudioApi api)
  602. {
  603. initJuceDevicesIfNeeded();
  604. String juceApi;
  605. switch (api)
  606. {
  607. case AUDIO_API_NULL:
  608. case AUDIO_API_OSS:
  609. case AUDIO_API_PULSE:
  610. break;
  611. case AUDIO_API_JACK:
  612. juceApi = "JACK";
  613. break;
  614. case AUDIO_API_ALSA:
  615. juceApi = "ALSA";
  616. break;
  617. case AUDIO_API_CORE:
  618. juceApi = "CoreAudio";
  619. break;
  620. case AUDIO_API_ASIO:
  621. juceApi = "ASIO";
  622. break;
  623. case AUDIO_API_DS:
  624. juceApi = "DirectSound";
  625. break;
  626. }
  627. if (juceApi.isEmpty())
  628. return nullptr;
  629. AudioIODeviceType* deviceType = nullptr;
  630. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  631. {
  632. deviceType = gDeviceTypes[i];
  633. if (deviceType == nullptr || deviceType->getTypeName() == juceApi)
  634. break;
  635. }
  636. if (deviceType == nullptr)
  637. return nullptr;
  638. deviceType->scanForDevices();
  639. return new CarlaEngineJuce(deviceType);
  640. }
  641. uint CarlaEngine::getJuceApiCount()
  642. {
  643. initJuceDevicesIfNeeded();
  644. return static_cast<uint>(gDeviceTypes.size());
  645. }
  646. const char* CarlaEngine::getJuceApiName(const uint uindex)
  647. {
  648. initJuceDevicesIfNeeded();
  649. const int index(static_cast<int>(uindex));
  650. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  651. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  652. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  653. return deviceType->getTypeName().toRawUTF8();
  654. }
  655. const char* const* CarlaEngine::getJuceApiDeviceNames(const uint uindex)
  656. {
  657. initJuceDevicesIfNeeded();
  658. const int index(static_cast<int>(uindex));
  659. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  660. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  661. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  662. deviceType->scanForDevices();
  663. StringArray juceDeviceNames(deviceType->getDeviceNames());
  664. const int juceDeviceNameCount(juceDeviceNames.size());
  665. if (juceDeviceNameCount <= 0)
  666. return nullptr;
  667. CarlaStringList devNames;
  668. for (int i=0; i < juceDeviceNameCount; ++i)
  669. devNames.append(juceDeviceNames[i].toRawUTF8());
  670. gDeviceNames = devNames.toCharStringListPtr();
  671. return gDeviceNames;
  672. }
  673. const EngineDriverDeviceInfo* CarlaEngine::getJuceDeviceInfo(const uint uindex, const char* const deviceName)
  674. {
  675. initJuceDevicesIfNeeded();
  676. const int index(static_cast<int>(uindex));
  677. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  678. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  679. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  680. deviceType->scanForDevices();
  681. ScopedPointer<AudioIODevice> device(deviceType->createDevice(deviceName, deviceName));
  682. if (device == nullptr)
  683. return nullptr;
  684. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  685. static uint32_t dummyBufferSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  686. static double dummySampleRates[14] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  687. // reset
  688. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE | ENGINE_DRIVER_DEVICE_VARIABLE_SAMPLE_RATE;
  689. // cleanup
  690. if (devInfo.bufferSizes != nullptr && devInfo.bufferSizes != dummyBufferSizes)
  691. {
  692. delete[] devInfo.bufferSizes;
  693. devInfo.bufferSizes = nullptr;
  694. }
  695. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  696. {
  697. delete[] devInfo.sampleRates;
  698. devInfo.sampleRates = nullptr;
  699. }
  700. if (device->hasControlPanel())
  701. devInfo.hints |= ENGINE_DRIVER_DEVICE_HAS_CONTROL_PANEL;
  702. Array<int> juceBufferSizes = device->getAvailableBufferSizes();
  703. if (int bufferSizesCount = juceBufferSizes.size())
  704. {
  705. uint32_t* const bufferSizes(new uint32_t[bufferSizesCount+1]);
  706. for (int i=0; i < bufferSizesCount; ++i)
  707. bufferSizes[i] = static_cast<uint32_t>(juceBufferSizes[i]);
  708. bufferSizes[bufferSizesCount] = 0;
  709. devInfo.bufferSizes = bufferSizes;
  710. }
  711. else
  712. {
  713. devInfo.bufferSizes = dummyBufferSizes;
  714. }
  715. Array<double> juceSampleRates = device->getAvailableSampleRates();
  716. if (int sampleRatesCount = juceSampleRates.size())
  717. {
  718. double* const sampleRates(new double[sampleRatesCount+1]);
  719. for (int i=0; i < sampleRatesCount; ++i)
  720. sampleRates[i] = juceSampleRates[i];
  721. sampleRates[sampleRatesCount] = 0.0;
  722. devInfo.sampleRates = sampleRates;
  723. }
  724. else
  725. {
  726. devInfo.sampleRates = dummySampleRates;
  727. }
  728. return &devInfo;
  729. }
  730. // -----------------------------------------
  731. CARLA_BACKEND_END_NAMESPACE