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.

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