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.

1003 lines
33KB

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