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.

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