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.

juce_linux_Bela.cpp 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. //==============================================================================
  20. class MidiInput::Pimpl
  21. {
  22. public:
  23. static Array<Pimpl*> midiInputs;
  24. Pimpl (const String& port, MidiInput* input, MidiInputCallback* callback)
  25. : midiInput (input), midiPort (port), midiCallback (callback)
  26. {
  27. jassert (midiCallback != nullptr);
  28. midiInputs.add (this);
  29. buffer.resize (32);
  30. }
  31. ~Pimpl()
  32. {
  33. stop();
  34. midiInputs.removeAllInstancesOf (this);
  35. }
  36. void start()
  37. {
  38. midi.readFrom (midiPort.toRawUTF8());
  39. }
  40. void stop()
  41. {
  42. midi.enableParser (false);
  43. }
  44. void poll()
  45. {
  46. size_t receivedBytes = 0;
  47. for (;;)
  48. {
  49. auto data = midi.getInput();
  50. if (data < 0)
  51. break;
  52. buffer[receivedBytes] = (uint8) data;
  53. receivedBytes++;
  54. if (receivedBytes == buffer.size())
  55. {
  56. pushMidiData (static_cast<int> (receivedBytes));
  57. receivedBytes = 0;
  58. }
  59. }
  60. if (receivedBytes > 0)
  61. pushMidiData ((int) receivedBytes);
  62. }
  63. static Array<MidiDeviceInfo> getDevices (bool input)
  64. {
  65. Array<MidiDeviceInfo> devices;
  66. for (auto& card : findAllALSACardIDs())
  67. findMidiDevices (devices, input, card);
  68. return devices;
  69. }
  70. void pushMidiMessage (juce::MidiMessage& message)
  71. {
  72. concatenator.pushMidiData (message.getRawData(), message.getRawDataSize(), Time::getMillisecondCounter() * 0.001, midiInput, *midiCallback);
  73. }
  74. private:
  75. void pushMidiData (int length)
  76. {
  77. concatenator.pushMidiData (buffer.data(), length, Time::getMillisecondCounter() * 0.001, midiInput, *midiCallback);
  78. }
  79. std::vector<uint8> buffer;
  80. static Array<int> findAllALSACardIDs()
  81. {
  82. Array<int> cards;
  83. int card = -1;
  84. for (;;)
  85. {
  86. auto status = snd_card_next (&card);
  87. if (status != 0 || card < 0)
  88. break;
  89. cards.add (card);
  90. }
  91. return cards;
  92. }
  93. // Adds all midi devices to the devices array of the given input/output type on the given card
  94. static void findMidiDevices (Array<MidiDeviceInfo>& devices, bool input, int cardNum)
  95. {
  96. snd_ctl_t* ctl = nullptr;
  97. auto status = snd_ctl_open (&ctl, ("hw:" + String (cardNum)).toRawUTF8(), 0);
  98. if (status < 0)
  99. return;
  100. int device = -1;
  101. for (;;)
  102. {
  103. status = snd_ctl_rawmidi_next_device (ctl, &device);
  104. if (status < 0 || device < 0)
  105. break;
  106. snd_rawmidi_info_t* info;
  107. snd_rawmidi_info_alloca (&info);
  108. snd_rawmidi_info_set_device (info, (unsigned int) device);
  109. snd_rawmidi_info_set_stream (info, input ? SND_RAWMIDI_STREAM_INPUT
  110. : SND_RAWMIDI_STREAM_OUTPUT);
  111. snd_ctl_rawmidi_info (ctl, info);
  112. auto subCount = snd_rawmidi_info_get_subdevices_count (info);
  113. for (size_t sub = 0; sub < subCount; ++sub)
  114. {
  115. snd_rawmidi_info_set_subdevice (info, sub);
  116. status = snd_ctl_rawmidi_info (ctl, info);
  117. if (status == 0)
  118. {
  119. String deviceName ("hw:" + String (cardNum) + "," + String (device) + "," + String (sub));
  120. devices.add (MidiDeviceInfo (deviceName, deviceName));
  121. }
  122. }
  123. }
  124. snd_ctl_close (ctl);
  125. }
  126. MidiInput* const midiInput;
  127. String midiPort;
  128. MidiInputCallback* const midiCallback;
  129. Midi midi;
  130. MidiDataConcatenator concatenator { 512 };
  131. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  132. };
  133. Array<MidiInput::Pimpl*> MidiInput::Pimpl::midiInputs;
  134. //==============================================================================
  135. class BelaAudioIODevice : public AudioIODevice
  136. {
  137. public:
  138. BelaAudioIODevice() : AudioIODevice (BelaAudioIODevice::belaTypeName,
  139. BelaAudioIODevice::belaTypeName)
  140. {
  141. Bela_defaultSettings (&defaultSettings);
  142. }
  143. ~BelaAudioIODevice()
  144. {
  145. close();
  146. }
  147. //==============================================================================
  148. StringArray getOutputChannelNames() override
  149. {
  150. StringArray result;
  151. for (int i = 1; i <= actualNumberOfOutputs; i++)
  152. result.add ("Out #" + std::to_string (i));
  153. return result;
  154. }
  155. StringArray getInputChannelNames() override
  156. {
  157. StringArray result;
  158. for (int i = 1; i <= actualNumberOfInputs; i++)
  159. result.add ("In #" + std::to_string (i));
  160. return result;
  161. }
  162. Array<double> getAvailableSampleRates() override { return { 44100.0 }; }
  163. Array<int> getAvailableBufferSizes() override { /* TODO: */ return { getDefaultBufferSize() }; }
  164. int getDefaultBufferSize() override { return defaultSettings.periodSize; }
  165. //==============================================================================
  166. String open (const BigInteger& inputChannels,
  167. const BigInteger& outputChannels,
  168. double sampleRate,
  169. int bufferSizeSamples) override
  170. {
  171. if (sampleRate != 44100.0 && sampleRate != 0.0)
  172. {
  173. lastError = "Bela audio outputs only support 44.1 kHz sample rate";
  174. return lastError;
  175. }
  176. settings = defaultSettings;
  177. auto numIns = getNumContiguousSetBits (inputChannels);
  178. auto numOuts = getNumContiguousSetBits (outputChannels);
  179. // Input and Output channels are numbered as follows
  180. //
  181. // 0 .. 1 - audio
  182. // 2 .. 9 - analog
  183. if (numIns > 2 || numOuts > 2)
  184. {
  185. settings.useAnalog = true;
  186. settings.numAnalogInChannels = std::max (numIns - 2, 8);
  187. settings.numAnalogOutChannels = std::max (numOuts - 2, 8);
  188. settings.uniformSampleRate = true;
  189. }
  190. settings.numAudioInChannels = std::max (numIns, 2);
  191. settings.numAudioOutChannels = std::max (numOuts, 2);
  192. settings.detectUnderruns = 1;
  193. settings.setup = setupCallback;
  194. settings.render = renderCallback;
  195. settings.cleanup = cleanupCallback;
  196. settings.interleave = 0;
  197. if (bufferSizeSamples > 0)
  198. settings.periodSize = bufferSizeSamples;
  199. isBelaOpen = false;
  200. isRunning = false;
  201. callback = nullptr;
  202. underruns = 0;
  203. if (Bela_initAudio (&settings, this) != 0 || ! isBelaOpen)
  204. {
  205. lastError = "Bela_initAutio failed";
  206. return lastError;
  207. }
  208. actualNumberOfInputs = jmin (numIns, actualNumberOfInputs);
  209. actualNumberOfOutputs = jmin (numOuts, actualNumberOfOutputs);
  210. channelInBuffer.calloc (actualNumberOfInputs);
  211. channelOutBuffer.calloc (actualNumberOfOutputs);
  212. return {};
  213. }
  214. void close() override
  215. {
  216. stop();
  217. if (isBelaOpen)
  218. {
  219. Bela_cleanupAudio();
  220. isBelaOpen = false;
  221. callback = nullptr;
  222. underruns = 0;
  223. actualBufferSize = 0;
  224. actualNumberOfInputs = 0;
  225. actualNumberOfOutputs = 0;
  226. channelInBuffer.free();
  227. channelOutBuffer.free();
  228. }
  229. }
  230. bool isOpen() override { return isBelaOpen; }
  231. void start (AudioIODeviceCallback* newCallback) override
  232. {
  233. if (! isBelaOpen)
  234. return;
  235. if (isRunning)
  236. {
  237. if (newCallback != callback)
  238. {
  239. if (newCallback != nullptr)
  240. newCallback->audioDeviceAboutToStart (this);
  241. {
  242. ScopedLock lock (callbackLock);
  243. std::swap (callback, newCallback);
  244. }
  245. if (newCallback != nullptr)
  246. newCallback->audioDeviceStopped();
  247. }
  248. }
  249. else
  250. {
  251. callback = newCallback;
  252. isRunning = (Bela_startAudio() == 0);
  253. if (callback != nullptr)
  254. {
  255. if (isRunning)
  256. {
  257. callback->audioDeviceAboutToStart (this);
  258. }
  259. else
  260. {
  261. lastError = "Bela_StartAudio failed";
  262. callback->audioDeviceError (lastError);
  263. }
  264. }
  265. }
  266. }
  267. void stop() override
  268. {
  269. AudioIODeviceCallback* oldCallback = nullptr;
  270. if (callback != nullptr)
  271. {
  272. ScopedLock lock (callbackLock);
  273. std::swap (callback, oldCallback);
  274. }
  275. isRunning = false;
  276. Bela_stopAudio();
  277. if (oldCallback != nullptr)
  278. oldCallback->audioDeviceStopped();
  279. }
  280. bool isPlaying() override { return isRunning; }
  281. String getLastError() override { return lastError; }
  282. //==============================================================================
  283. int getCurrentBufferSizeSamples() override { return (int) actualBufferSize; }
  284. double getCurrentSampleRate() override { return 44100.0; }
  285. int getCurrentBitDepth() override { return 16; }
  286. BigInteger getActiveOutputChannels() const override { BigInteger b; b.setRange (0, actualNumberOfOutputs, true); return b; }
  287. BigInteger getActiveInputChannels() const override { BigInteger b; b.setRange (0, actualNumberOfInputs, true); return b; }
  288. int getOutputLatencyInSamples() override { /* TODO */ return 0; }
  289. int getInputLatencyInSamples() override { /* TODO */ return 0; }
  290. int getXRunCount() const noexcept override { return underruns; }
  291. //==============================================================================
  292. static const char* const belaTypeName;
  293. private:
  294. //==============================================================================
  295. bool setup (BelaContext& context)
  296. {
  297. actualBufferSize = context.audioFrames;
  298. actualNumberOfInputs = (int) (context.audioInChannels + context.analogInChannels);
  299. actualNumberOfOutputs = (int) (context.audioOutChannels + context.analogOutChannels);
  300. isBelaOpen = true;
  301. firstCallback = true;
  302. ScopedLock lock (callbackLock);
  303. if (callback != nullptr)
  304. callback->audioDeviceAboutToStart (this);
  305. return true;
  306. }
  307. void render (BelaContext& context)
  308. {
  309. // check for xruns
  310. calculateXruns (context.audioFramesElapsed, context.audioFrames);
  311. ScopedLock lock (callbackLock);
  312. // Check for and process and midi
  313. for (auto midiInput : MidiInput::Pimpl::midiInputs)
  314. midiInput->poll();
  315. if (callback != nullptr)
  316. {
  317. jassert (context.audioFrames <= actualBufferSize);
  318. jassert ((context.flags & BELA_FLAG_INTERLEAVED) == 0);
  319. using Frames = decltype (context.audioFrames);
  320. // Setup channelInBuffers
  321. for (int ch = 0; ch < actualNumberOfInputs; ++ch)
  322. {
  323. if (ch < analogChannelStart)
  324. channelInBuffer[ch] = &context.audioIn[(Frames) ch * context.audioFrames];
  325. else
  326. channelInBuffer[ch] = &context.analogIn[(Frames) (ch - analogChannelStart) * context.analogFrames];
  327. }
  328. // Setup channelOutBuffers
  329. for (int ch = 0; ch < actualNumberOfOutputs; ++ch)
  330. {
  331. if (ch < analogChannelStart)
  332. channelOutBuffer[ch] = &context.audioOut[(Frames) ch * context.audioFrames];
  333. else
  334. channelOutBuffer[ch] = &context.analogOut[(Frames) (ch - analogChannelStart) * context.audioFrames];
  335. }
  336. callback->audioDeviceIOCallback (channelInBuffer.getData(), actualNumberOfInputs,
  337. channelOutBuffer.getData(), actualNumberOfOutputs,
  338. (int) context.audioFrames);
  339. }
  340. }
  341. void cleanup (BelaContext&)
  342. {
  343. ScopedLock lock (callbackLock);
  344. if (callback != nullptr)
  345. callback->audioDeviceStopped();
  346. }
  347. const int analogChannelStart = 2;
  348. //==============================================================================
  349. uint64_t expectedElapsedAudioSamples = 0;
  350. int underruns = 0;
  351. bool firstCallback = false;
  352. void calculateXruns (uint64_t audioFramesElapsed, uint32_t numSamples)
  353. {
  354. if (audioFramesElapsed > expectedElapsedAudioSamples && ! firstCallback)
  355. ++underruns;
  356. firstCallback = false;
  357. expectedElapsedAudioSamples = audioFramesElapsed + numSamples;
  358. }
  359. //==============================================================================
  360. static int getNumContiguousSetBits (const BigInteger& value) noexcept
  361. {
  362. int bit = 0;
  363. while (value[bit])
  364. ++bit;
  365. return bit;
  366. }
  367. //==============================================================================
  368. static bool setupCallback (BelaContext* context, void* userData) noexcept { return static_cast<BelaAudioIODevice*> (userData)->setup (*context); }
  369. static void renderCallback (BelaContext* context, void* userData) noexcept { static_cast<BelaAudioIODevice*> (userData)->render (*context); }
  370. static void cleanupCallback (BelaContext* context, void* userData) noexcept { static_cast<BelaAudioIODevice*> (userData)->cleanup (*context); }
  371. //==============================================================================
  372. BelaInitSettings defaultSettings, settings;
  373. bool isBelaOpen = false, isRunning = false;
  374. CriticalSection callbackLock;
  375. AudioIODeviceCallback* callback = nullptr;
  376. String lastError;
  377. uint32_t actualBufferSize = 0;
  378. int actualNumberOfInputs = 0, actualNumberOfOutputs = 0;
  379. HeapBlock<const float*> channelInBuffer;
  380. HeapBlock<float*> channelOutBuffer;
  381. bool includeAnalogSupport;
  382. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BelaAudioIODevice)
  383. };
  384. const char* const BelaAudioIODevice::belaTypeName = "Bela Analog";
  385. //==============================================================================
  386. struct BelaAudioIODeviceType : public AudioIODeviceType
  387. {
  388. BelaAudioIODeviceType() : AudioIODeviceType ("Bela") {}
  389. StringArray getDeviceNames (bool) const override { return StringArray (BelaAudioIODevice::belaTypeName); }
  390. void scanForDevices() override {}
  391. int getDefaultDeviceIndex (bool) const override { return 0; }
  392. int getIndexOfDevice (AudioIODevice* device, bool) const override { return device != nullptr ? 0 : -1; }
  393. bool hasSeparateInputsAndOutputs() const override { return false; }
  394. AudioIODevice* createDevice (const String& outputName, const String& inputName) override
  395. {
  396. // TODO: switching whether to support analog/digital with possible multiple Bela device types?
  397. if (outputName == BelaAudioIODevice::belaTypeName || inputName == BelaAudioIODevice::belaTypeName)
  398. return new BelaAudioIODevice();
  399. return nullptr;
  400. }
  401. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BelaAudioIODeviceType)
  402. };
  403. //==============================================================================
  404. MidiInput::MidiInput (const String& deviceName, const String& deviceID)
  405. : deviceInfo (deviceName, deviceID)
  406. {
  407. }
  408. MidiInput::~MidiInput() = default;
  409. void MidiInput::start() { internal->start(); }
  410. void MidiInput::stop() { internal->stop(); }
  411. Array<MidiDeviceInfo> MidiInput::getAvailableDevices()
  412. {
  413. return Pimpl::getDevices (true);
  414. }
  415. MidiDeviceInfo MidiInput::getDefaultDevice()
  416. {
  417. return getAvailableDevices().getFirst();
  418. }
  419. std::unique_ptr<MidiInput> MidiInput::openDevice (const String& deviceIdentifier, MidiInputCallback* callback)
  420. {
  421. if (deviceIdentifier.isEmpty())
  422. return {};
  423. std::unique_ptr<MidiInput> midiInput (new MidiInput (deviceIdentifier, deviceIdentifier));
  424. midiInput->internal = std::make_unique<Pimpl> (deviceIdentifier, midiInput.get(), callback);
  425. return midiInput;
  426. }
  427. std::unique_ptr<MidiInput> MidiInput::createNewDevice (const String&, MidiInputCallback*)
  428. {
  429. // N/A on Bela
  430. jassertfalse;
  431. return {};
  432. }
  433. StringArray MidiInput::getDevices()
  434. {
  435. StringArray deviceNames;
  436. for (auto& d : getAvailableDevices())
  437. deviceNames.add (d.name);
  438. return deviceNames;
  439. }
  440. int MidiInput::getDefaultDeviceIndex()
  441. {
  442. return 0;
  443. }
  444. std::unique_ptr<MidiInput> MidiInput::openDevice (int index, MidiInputCallback* callback)
  445. {
  446. return openDevice (getAvailableDevices()[index].identifier, callback);
  447. }
  448. //==============================================================================
  449. // TODO: Add Bela MidiOutput support
  450. class MidiOutput::Pimpl {};
  451. MidiOutput::~MidiOutput() = default;
  452. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  453. Array<MidiDeviceInfo> MidiOutput::getAvailableDevices() { return {}; }
  454. MidiDeviceInfo MidiOutput::getDefaultDevice() { return {}; }
  455. std::unique_ptr<MidiOutput> MidiOutput::openDevice (const String&) { return {}; }
  456. std::unique_ptr<MidiOutput> MidiOutput::createNewDevice (const String&) { return {}; }
  457. StringArray MidiOutput::getDevices() { return {}; }
  458. int MidiOutput::getDefaultDeviceIndex() { return 0;}
  459. std::unique_ptr<MidiOutput> MidiOutput::openDevice (int) { return {}; }
  460. } // namespace juce