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.

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