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.

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