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.

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