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.

991 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. // assert juce buffers
  351. CARLA_SAFE_ASSERT_RETURN(numInputChannels >= 0, runPendingRtEvents());
  352. CARLA_SAFE_ASSERT_RETURN(numOutputChannels > 0, runPendingRtEvents());
  353. CARLA_SAFE_ASSERT_RETURN(outputChannelData != nullptr, runPendingRtEvents());
  354. CARLA_SAFE_ASSERT_RETURN(numSamples == static_cast<int>(pData->bufferSize), runPendingRtEvents());
  355. const uint32_t nframes(static_cast<uint32_t>(numSamples));
  356. // initialize juce output
  357. for (int i=0; i < numOutputChannels; ++i)
  358. FloatVectorOperations::clear(outputChannelData[i], numSamples);
  359. // initialize events
  360. carla_zeroStruct<EngineEvent>(pData->events.in, kMaxEngineEventInternalCount);
  361. carla_zeroStruct<EngineEvent>(pData->events.out, kMaxEngineEventInternalCount);
  362. if (fMidiInEvents.mutex.tryLock())
  363. {
  364. uint32_t engineEventIndex = 0;
  365. fMidiInEvents.splice();
  366. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin(); it.valid(); it.next())
  367. {
  368. const RtMidiEvent& midiEvent(it.getValue());
  369. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  370. if (midiEvent.time < pData->timeInfo.frame)
  371. {
  372. engineEvent.time = 0;
  373. }
  374. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  375. {
  376. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  377. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  378. }
  379. else
  380. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  381. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data);
  382. if (engineEventIndex >= kMaxEngineEventInternalCount)
  383. break;
  384. }
  385. fMidiInEvents.data.clear();
  386. fMidiInEvents.mutex.unlock();
  387. }
  388. pData->graph.process(pData, inputChannelData, outputChannelData, static_cast<uint32_t>(numSamples));
  389. fMidiOutMutex.lock();
  390. if (fMidiOuts.count() > 0)
  391. {
  392. uint8_t size = 0;
  393. uint8_t data[3] = { 0, 0, 0 };
  394. const uint8_t* dataPtr = data;
  395. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  396. {
  397. const EngineEvent& engineEvent(pData->events.out[i]);
  398. if (engineEvent.type == kEngineEventTypeNull)
  399. break;
  400. else if (engineEvent.type == kEngineEventTypeControl)
  401. {
  402. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  403. ctrlEvent.convertToMidiData(engineEvent.channel, size, data);
  404. dataPtr = data;
  405. }
  406. else if (engineEvent.type == kEngineEventTypeMidi)
  407. {
  408. const EngineMidiEvent& midiEvent(engineEvent.midi);
  409. size = midiEvent.size;
  410. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  411. dataPtr = midiEvent.dataExt;
  412. else
  413. dataPtr = midiEvent.data;
  414. }
  415. else
  416. {
  417. continue;
  418. }
  419. if (size > 0)
  420. {
  421. MidiMessage message(static_cast<const void*>(dataPtr), static_cast<int>(size), static_cast<double>(engineEvent.time)/nframes);
  422. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  423. {
  424. MidiOutPort& outPort(it.getValue());
  425. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  426. outPort.port->sendMessageNow(message);
  427. }
  428. }
  429. }
  430. }
  431. fMidiOutMutex.unlock();
  432. runPendingRtEvents();
  433. return;
  434. }
  435. void audioDeviceAboutToStart(AudioIODevice* /*device*/) override
  436. {
  437. }
  438. void audioDeviceStopped() override
  439. {
  440. }
  441. void audioDeviceError(const String& errorMessage) override
  442. {
  443. callback(ENGINE_CALLBACK_ERROR, 0, 0, 0, 0.0f, errorMessage.toRawUTF8());
  444. }
  445. // -------------------------------------------------------------------
  446. void handleIncomingMidiMessage(MidiInput* /*source*/, const MidiMessage& message) override
  447. {
  448. const int messageSize(message.getRawDataSize());
  449. if (messageSize <= 0 || messageSize > EngineMidiEvent::kDataSize)
  450. return;
  451. const uint8_t* const messageData(message.getRawData());
  452. RtMidiEvent midiEvent;
  453. midiEvent.time = 0; // TODO
  454. midiEvent.size = static_cast<uint8_t>(messageSize);
  455. int i=0;
  456. for (; i < messageSize; ++i)
  457. midiEvent.data[i] = messageData[i];
  458. for (; i < EngineMidiEvent::kDataSize; ++i)
  459. midiEvent.data[i] = 0;
  460. fMidiInEvents.append(midiEvent);
  461. }
  462. // -------------------------------------------------------------------
  463. bool connectRackMidiInPort(const char* const portName) override
  464. {
  465. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  466. carla_debug("CarlaEngineJuce::connectRackMidiInPort(\"%s\")", portName);
  467. RackGraph* const graph(pData->graph.getRackGraph());
  468. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  469. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  470. StringArray midiIns(MidiInput::getDevices());
  471. if (! midiIns.contains(portName))
  472. return false;
  473. MidiInput* const juceMidiIn(MidiInput::openDevice(midiIns.indexOf(portName), this));
  474. juceMidiIn->start();
  475. MidiInPort midiPort;
  476. midiPort.port = juceMidiIn;
  477. std::strncpy(midiPort.name, portName, STR_MAX);
  478. midiPort.name[STR_MAX] = '\0';
  479. fMidiIns.append(midiPort);
  480. return true;
  481. }
  482. bool connectRackMidiOutPort(const char* const portName) override
  483. {
  484. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  485. carla_debug("CarlaEngineJuce::connectRackMidiOutPort(\"%s\")", portName);
  486. RackGraph* const graph(pData->graph.getRackGraph());
  487. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  488. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  489. StringArray midiOuts(MidiOutput::getDevices());
  490. if (! midiOuts.contains(portName))
  491. return false;
  492. MidiOutput* const juceMidiOut(MidiOutput::openDevice(midiOuts.indexOf(portName)));
  493. juceMidiOut->startBackgroundThread();
  494. MidiOutPort midiPort;
  495. midiPort.port = juceMidiOut;
  496. std::strncpy(midiPort.name, portName, STR_MAX);
  497. midiPort.name[STR_MAX] = '\0';
  498. const CarlaMutexLocker cml(fMidiOutMutex);
  499. fMidiOuts.append(midiPort);
  500. return true;
  501. }
  502. bool disconnectRackMidiInPort(const char* const portName) override
  503. {
  504. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  505. carla_debug("CarlaEngineRtAudio::disconnectRackMidiInPort(\"%s\")", portName);
  506. RackGraph* const graph(pData->graph.getRackGraph());
  507. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  508. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  509. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin(); it.valid(); it.next())
  510. {
  511. MidiInPort& inPort(it.getValue());
  512. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  513. if (std::strcmp(inPort.name, portName) != 0)
  514. continue;
  515. inPort.port->stop();
  516. delete inPort.port;
  517. fMidiIns.remove(it);
  518. return true;
  519. }
  520. return false;
  521. }
  522. bool disconnectRackMidiOutPort(const char* const portName) override
  523. {
  524. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  525. carla_debug("CarlaEngineRtAudio::disconnectRackMidiOutPort(\"%s\")", portName);
  526. RackGraph* const graph(pData->graph.getRackGraph());
  527. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  528. CARLA_SAFE_ASSERT_RETURN(graph->midi.outs.count() > 0, false);
  529. const CarlaMutexLocker cml(fMidiOutMutex);
  530. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  531. {
  532. MidiOutPort& outPort(it.getValue());
  533. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  534. if (std::strcmp(outPort.name, portName) != 0)
  535. continue;
  536. outPort.port->stopBackgroundThread();
  537. delete outPort.port;
  538. fMidiOuts.remove(it);
  539. return true;
  540. }
  541. return false;
  542. }
  543. // -------------------------------------
  544. private:
  545. ScopedPointer<AudioIODevice> fDevice;
  546. AudioIODeviceType* const fDeviceType;
  547. struct MidiInPort {
  548. MidiInput* port;
  549. char name[STR_MAX+1];
  550. };
  551. struct MidiOutPort {
  552. MidiOutput* port;
  553. char name[STR_MAX+1];
  554. };
  555. struct RtMidiEvent {
  556. uint64_t time; // needs to compare to internal time
  557. uint8_t size;
  558. uint8_t data[EngineMidiEvent::kDataSize];
  559. };
  560. struct RtMidiEvents {
  561. CarlaMutex mutex;
  562. RtLinkedList<RtMidiEvent>::Pool dataPool;
  563. RtLinkedList<RtMidiEvent> data;
  564. RtLinkedList<RtMidiEvent> dataPending;
  565. RtMidiEvents()
  566. : mutex(),
  567. dataPool(512, 512),
  568. data(dataPool),
  569. dataPending(dataPool) {}
  570. ~RtMidiEvents()
  571. {
  572. clear();
  573. }
  574. void append(const RtMidiEvent& event)
  575. {
  576. mutex.lock();
  577. dataPending.append(event);
  578. mutex.unlock();
  579. }
  580. void clear()
  581. {
  582. mutex.lock();
  583. data.clear();
  584. dataPending.clear();
  585. mutex.unlock();
  586. }
  587. void splice()
  588. {
  589. dataPending.spliceAppendTo(data);
  590. }
  591. };
  592. LinkedList<MidiInPort> fMidiIns;
  593. RtMidiEvents fMidiInEvents;
  594. LinkedList<MidiOutPort> fMidiOuts;
  595. CarlaMutex fMidiOutMutex;
  596. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJuce)
  597. };
  598. // -----------------------------------------
  599. CarlaEngine* CarlaEngine::newJuce(const AudioApi api)
  600. {
  601. initJuceDevicesIfNeeded();
  602. String juceApi;
  603. switch (api)
  604. {
  605. case AUDIO_API_NULL:
  606. case AUDIO_API_OSS:
  607. case AUDIO_API_PULSE:
  608. break;
  609. case AUDIO_API_JACK:
  610. juceApi = "JACK";
  611. break;
  612. case AUDIO_API_ALSA:
  613. juceApi = "ALSA";
  614. break;
  615. case AUDIO_API_CORE:
  616. juceApi = "CoreAudio";
  617. break;
  618. case AUDIO_API_ASIO:
  619. juceApi = "ASIO";
  620. break;
  621. case AUDIO_API_DS:
  622. juceApi = "DirectSound";
  623. break;
  624. }
  625. if (juceApi.isEmpty())
  626. return nullptr;
  627. AudioIODeviceType* deviceType = nullptr;
  628. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  629. {
  630. deviceType = gDeviceTypes[i];
  631. if (deviceType == nullptr || deviceType->getTypeName() == juceApi)
  632. break;
  633. }
  634. if (deviceType == nullptr)
  635. return nullptr;
  636. deviceType->scanForDevices();
  637. return new CarlaEngineJuce(deviceType);
  638. }
  639. uint CarlaEngine::getJuceApiCount()
  640. {
  641. initJuceDevicesIfNeeded();
  642. return static_cast<uint>(gDeviceTypes.size());
  643. }
  644. const char* CarlaEngine::getJuceApiName(const uint uindex)
  645. {
  646. initJuceDevicesIfNeeded();
  647. const int index(static_cast<int>(uindex));
  648. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  649. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  650. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  651. return deviceType->getTypeName().toRawUTF8();
  652. }
  653. const char* const* CarlaEngine::getJuceApiDeviceNames(const uint uindex)
  654. {
  655. initJuceDevicesIfNeeded();
  656. const int index(static_cast<int>(uindex));
  657. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  658. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  659. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  660. deviceType->scanForDevices();
  661. StringArray juceDeviceNames(deviceType->getDeviceNames());
  662. const int juceDeviceNameCount(juceDeviceNames.size());
  663. if (juceDeviceNameCount <= 0)
  664. return nullptr;
  665. CarlaStringList devNames;
  666. for (int i=0; i < juceDeviceNameCount; ++i)
  667. devNames.append(juceDeviceNames[i].toRawUTF8());
  668. gDeviceNames = devNames.toCharStringListPtr();
  669. return gDeviceNames;
  670. }
  671. const EngineDriverDeviceInfo* CarlaEngine::getJuceDeviceInfo(const uint uindex, const char* const deviceName)
  672. {
  673. initJuceDevicesIfNeeded();
  674. const int index(static_cast<int>(uindex));
  675. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  676. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  677. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  678. deviceType->scanForDevices();
  679. ScopedPointer<AudioIODevice> device(deviceType->createDevice(deviceName, deviceName));
  680. if (device == nullptr)
  681. return nullptr;
  682. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  683. static uint32_t dummyBufferSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  684. static double dummySampleRates[14] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  685. // reset
  686. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE | ENGINE_DRIVER_DEVICE_VARIABLE_SAMPLE_RATE;
  687. // cleanup
  688. if (devInfo.bufferSizes != nullptr && devInfo.bufferSizes != dummyBufferSizes)
  689. {
  690. delete[] devInfo.bufferSizes;
  691. devInfo.bufferSizes = nullptr;
  692. }
  693. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  694. {
  695. delete[] devInfo.sampleRates;
  696. devInfo.sampleRates = nullptr;
  697. }
  698. if (device->hasControlPanel())
  699. devInfo.hints |= ENGINE_DRIVER_DEVICE_HAS_CONTROL_PANEL;
  700. Array<int> juceBufferSizes = device->getAvailableBufferSizes();
  701. if (int bufferSizesCount = juceBufferSizes.size())
  702. {
  703. uint32_t* const bufferSizes(new uint32_t[bufferSizesCount+1]);
  704. for (int i=0; i < bufferSizesCount; ++i)
  705. bufferSizes[i] = static_cast<uint32_t>(juceBufferSizes[i]);
  706. bufferSizes[bufferSizesCount] = 0;
  707. devInfo.bufferSizes = bufferSizes;
  708. }
  709. else
  710. {
  711. devInfo.bufferSizes = dummyBufferSizes;
  712. }
  713. Array<double> juceSampleRates = device->getAvailableSampleRates();
  714. if (int sampleRatesCount = juceSampleRates.size())
  715. {
  716. double* const sampleRates(new double[sampleRatesCount+1]);
  717. for (int i=0; i < sampleRatesCount; ++i)
  718. sampleRates[i] = juceSampleRates[i];
  719. sampleRates[sampleRatesCount] = 0.0;
  720. devInfo.sampleRates = sampleRates;
  721. }
  722. else
  723. {
  724. devInfo.sampleRates = dummySampleRates;
  725. }
  726. return &devInfo;
  727. }
  728. // -----------------------------------------
  729. CARLA_BACKEND_END_NAMESPACE