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