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.

1376 lines
47KB

  1. /*
  2. * Carla LinuxSampler Plugin
  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 doc/GPL.txt file.
  16. */
  17. /* TODO
  18. * - implement buffer size changes
  19. * - implement sample rate changes
  20. * - call outDev->ReconnectAll() after changing buffer size or sample rate
  21. * - use CARLA_SAFE_ASSERT_RETURN with err
  22. */
  23. #include "CarlaPluginInternal.hpp"
  24. #include "CarlaEngine.hpp"
  25. #ifdef WANT_LINUXSAMPLER
  26. #include "CarlaBackendUtils.hpp"
  27. #include "CarlaMathUtils.hpp"
  28. #include "juce_core.h"
  29. #include "linuxsampler/EngineFactory.h"
  30. #include <linuxsampler/Sampler.h>
  31. // -----------------------------------------------------------------------
  32. namespace LinuxSampler {
  33. using CarlaBackend::CarlaEngine;
  34. using CarlaBackend::CarlaPlugin;
  35. // -----------------------------------------------------------------------
  36. // LinuxSampler static values
  37. static const float kVolumeMax = 3.16227766f; // +10 dB
  38. // -----------------------------------------------------------------------
  39. // LinuxSampler AudioOutputDevice Plugin
  40. class AudioOutputDevicePlugin : public AudioOutputDevice
  41. {
  42. public:
  43. AudioOutputDevicePlugin(const CarlaEngine* const engine, const CarlaPlugin* const plugin, const bool uses16Outs)
  44. : AudioOutputDevice(std::map<String, DeviceCreationParameter*>()),
  45. fEngine(engine),
  46. fPlugin(plugin)
  47. {
  48. CARLA_ASSERT(engine != nullptr);
  49. CARLA_ASSERT(plugin != nullptr);
  50. AcquireChannels(uses16Outs ? 32 : 2);
  51. }
  52. ~AudioOutputDevicePlugin() override {}
  53. // -------------------------------------------------------------------
  54. // LinuxSampler virtual methods
  55. void Play() override {}
  56. void Stop() override {}
  57. bool IsPlaying() override
  58. {
  59. return (fEngine->isRunning() && fPlugin->isEnabled());
  60. }
  61. uint MaxSamplesPerCycle() override
  62. {
  63. return fEngine->getBufferSize();
  64. }
  65. uint SampleRate() override
  66. {
  67. return uint(fEngine->getSampleRate());
  68. }
  69. String Driver() override
  70. {
  71. return "AudioOutputDevicePlugin";
  72. }
  73. AudioChannel* CreateChannel(uint channelNr) override
  74. {
  75. return new AudioChannel(channelNr, nullptr, 0);
  76. }
  77. // -------------------------------------------------------------------
  78. // Give public access to the RenderAudio call
  79. int Render(const uint samples)
  80. {
  81. return RenderAudio(samples);
  82. }
  83. // -------------------------------------------------------------------
  84. private:
  85. const CarlaEngine* const fEngine;
  86. const CarlaPlugin* const fPlugin;
  87. };
  88. // -----------------------------------------------------------------------
  89. // LinuxSampler MidiInputPort Plugin
  90. class MidiInputPortPlugin : public MidiInputPort
  91. {
  92. public:
  93. MidiInputPortPlugin(MidiInputDevice* const device, const int portNum)
  94. : MidiInputPort(device, portNum) {}
  95. ~MidiInputPortPlugin() override {}
  96. };
  97. // -----------------------------------------------------------------------
  98. // LinuxSampler MidiInputDevice Plugin
  99. class MidiInputDevicePlugin : public MidiInputDevice
  100. {
  101. public:
  102. MidiInputDevicePlugin(Sampler* const sampler)
  103. : MidiInputDevice(std::map<String, DeviceCreationParameter*>(), sampler) {}
  104. // -------------------------------------------------------------------
  105. // LinuxSampler virtual methods
  106. void Listen() override {}
  107. void StopListen() override {}
  108. String Driver() override
  109. {
  110. return "MidiInputDevicePlugin";
  111. }
  112. MidiInputPort* CreateMidiPort() override
  113. {
  114. return new MidiInputPortPlugin(this, int(Ports.size()));
  115. }
  116. MidiInputPortPlugin* CreateMidiPortPlugin()
  117. {
  118. return new MidiInputPortPlugin(this, int(Ports.size()));
  119. }
  120. };
  121. } // namespace LinuxSampler
  122. // -----------------------------------------------------------------------
  123. using juce::File;
  124. using juce::StringArray;
  125. CARLA_BACKEND_START_NAMESPACE
  126. // -----------------------------------------------------------------------
  127. class LinuxSamplerPlugin : public CarlaPlugin
  128. {
  129. public:
  130. LinuxSamplerPlugin(CarlaEngine* const engine, const uint id, const char* const format, const bool use16Outs)
  131. : CarlaPlugin(engine, id),
  132. fUses16Outs(use16Outs),
  133. fFormat(carla_strdup(format)),
  134. fLabel(nullptr),
  135. fMaker(nullptr),
  136. fRealName(nullptr),
  137. fEngine(nullptr),
  138. fAudioOutputDevice(nullptr),
  139. fMidiInputDevice(nullptr),
  140. fMidiInputPort(nullptr),
  141. fInstrument(nullptr)
  142. {
  143. carla_debug("LinuxSamplerPlugin::LinuxSamplerPlugin(%p, %i, %s, %s)", engine, id, format, bool2str(use16Outs));
  144. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  145. {
  146. fCurMidiProgs[0] = 0;
  147. fSamplerChannels[i] = nullptr;
  148. fEngineChannels[i] = nullptr;
  149. }
  150. }
  151. ~LinuxSamplerPlugin() override
  152. {
  153. carla_debug("LinuxSamplerPlugin::~LinuxSamplerPlugin()");
  154. pData->singleMutex.lock();
  155. pData->masterMutex.lock();
  156. if (pData->client != nullptr && pData->client->isActive())
  157. pData->client->deactivate();
  158. if (pData->active)
  159. {
  160. deactivate();
  161. pData->active = false;
  162. }
  163. if (fEngine != nullptr)
  164. {
  165. if (fMidiInputDevice != nullptr)
  166. {
  167. if (fMidiInputPort != nullptr)
  168. {
  169. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  170. {
  171. if (fSamplerChannels[i] != nullptr)
  172. {
  173. if (fEngineChannels[i] != nullptr)
  174. {
  175. fMidiInputPort->Disconnect(fEngineChannels[i]);
  176. fEngineChannels[i]->DisconnectAudioOutputDevice();
  177. fEngineChannels[i] = nullptr;
  178. }
  179. fSampler.RemoveSamplerChannel(fSamplerChannels[i]);
  180. fSamplerChannels[i] = nullptr;
  181. }
  182. }
  183. delete fMidiInputPort;
  184. fMidiInputPort = nullptr;
  185. }
  186. delete fMidiInputDevice;
  187. fMidiInputDevice = nullptr;
  188. }
  189. if (fAudioOutputDevice != nullptr)
  190. {
  191. delete fAudioOutputDevice;
  192. fAudioOutputDevice = nullptr;
  193. }
  194. fInstrument = nullptr;
  195. LinuxSampler::EngineFactory::Destroy(fEngine);
  196. fEngine = nullptr;
  197. }
  198. fInstrumentIds.clear();
  199. if (fFormat != nullptr)
  200. {
  201. delete[] fFormat;
  202. fFormat = nullptr;
  203. }
  204. if (fLabel != nullptr)
  205. {
  206. delete[] fLabel;
  207. fLabel = nullptr;
  208. }
  209. if (fMaker != nullptr)
  210. {
  211. delete[] fMaker;
  212. fMaker = nullptr;
  213. }
  214. if (fRealName != nullptr)
  215. {
  216. delete[] fRealName;
  217. fRealName = nullptr;
  218. }
  219. clearBuffers();
  220. }
  221. // -------------------------------------------------------------------
  222. // Information (base)
  223. PluginType getType() const noexcept override
  224. {
  225. return getPluginTypeFromString(fFormat);
  226. }
  227. PluginCategory getCategory() const noexcept override
  228. {
  229. return PLUGIN_CATEGORY_SYNTH;
  230. }
  231. // -------------------------------------------------------------------
  232. // Information (count)
  233. // nothing
  234. // -------------------------------------------------------------------
  235. // Information (current data)
  236. // nothing
  237. // -------------------------------------------------------------------
  238. // Information (per-plugin data)
  239. uint getOptionsAvailable() const noexcept override
  240. {
  241. uint options = 0x0;
  242. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  243. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  244. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  245. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  246. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  247. return options;
  248. }
  249. void getLabel(char* const strBuf) const noexcept override
  250. {
  251. if (fLabel != nullptr)
  252. {
  253. std::strncpy(strBuf, fLabel, STR_MAX);
  254. return;
  255. }
  256. CarlaPlugin::getLabel(strBuf);
  257. }
  258. void getMaker(char* const strBuf) const noexcept override
  259. {
  260. if (fMaker != nullptr)
  261. {
  262. std::strncpy(strBuf, fMaker, STR_MAX);
  263. return;
  264. }
  265. CarlaPlugin::getMaker(strBuf);
  266. }
  267. void getCopyright(char* const strBuf) const noexcept override
  268. {
  269. getMaker(strBuf);
  270. }
  271. void getRealName(char* const strBuf) const noexcept override
  272. {
  273. if (fRealName != nullptr)
  274. {
  275. std::strncpy(strBuf, fRealName, STR_MAX);
  276. return;
  277. }
  278. CarlaPlugin::getRealName(strBuf);
  279. }
  280. // -------------------------------------------------------------------
  281. // Set data (state)
  282. void prepareForSave() override
  283. {
  284. char strBuf[STR_MAX+1];
  285. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i", fCurMidiProgs[0], fCurMidiProgs[1], fCurMidiProgs[2], fCurMidiProgs[3],
  286. fCurMidiProgs[4], fCurMidiProgs[5], fCurMidiProgs[6], fCurMidiProgs[7],
  287. fCurMidiProgs[8], fCurMidiProgs[9], fCurMidiProgs[10], fCurMidiProgs[11],
  288. fCurMidiProgs[12], fCurMidiProgs[13], fCurMidiProgs[14], fCurMidiProgs[15]);
  289. CarlaPlugin::setCustomData(CUSTOM_DATA_TYPE_STRING, "midiPrograms", strBuf, false);
  290. }
  291. // -------------------------------------------------------------------
  292. // Set data (internal stuff)
  293. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  294. {
  295. if (channel >= 0 && channel < MAX_MIDI_CHANNELS)
  296. pData->midiprog.current = fCurMidiProgs[channel];
  297. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  298. }
  299. // -------------------------------------------------------------------
  300. // Set data (plugin-specific stuff)
  301. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  302. {
  303. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  304. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  305. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  306. carla_debug("LinuxSamplerPlugin::setCustomData(%s, \"%s\", \"%s\", %s)", type, key, value, bool2str(sendGui));
  307. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) != 0)
  308. return carla_stderr2("LinuxSamplerPlugin::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  309. if (std::strcmp(key, "midiPrograms") != 0)
  310. return carla_stderr2("LinuxSamplerPlugin::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  311. if (fUses16Outs)
  312. {
  313. StringArray midiProgramList(StringArray::fromTokens(value, ":", ""));
  314. if (midiProgramList.size() == MAX_MIDI_CHANNELS)
  315. {
  316. uint8_t channel = 0;
  317. for (juce::String *it=midiProgramList.begin(), *end=midiProgramList.end(); it != end; ++it)
  318. {
  319. const int index(it->getIntValue());
  320. if (index >= 0 && index < static_cast<int>(pData->midiprog.count))
  321. {
  322. const uint32_t bank = pData->midiprog.data[index].bank;
  323. const uint32_t program = pData->midiprog.data[index].program;
  324. const uint32_t rIndex = bank*128 + program;
  325. /*if (pData->engine->isOffline())
  326. {
  327. fEngineChannels[channel]->PrepareLoadInstrument(pData->filename, rIndex);
  328. fEngineChannels[channel]->LoadInstrument();
  329. }
  330. else*/
  331. {
  332. fInstrument->LoadInstrumentInBackground(fInstrumentIds[rIndex], fEngineChannels[channel]);
  333. }
  334. fCurMidiProgs[channel] = index;
  335. if (pData->ctrlChannel == static_cast<int32_t>(channel))
  336. {
  337. pData->midiprog.current = index;
  338. pData->engine->callback(ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED, pData->id, index, 0, 0.0f, nullptr);
  339. }
  340. }
  341. ++channel;
  342. }
  343. CARLA_SAFE_ASSERT(channel == MAX_MIDI_CHANNELS);
  344. }
  345. }
  346. CarlaPlugin::setCustomData(type, key, value, sendGui);
  347. }
  348. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  349. {
  350. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  351. if (index >= 0 && pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  352. {
  353. const uint32_t bank = pData->midiprog.data[index].bank;
  354. const uint32_t program = pData->midiprog.data[index].program;
  355. const uint32_t rIndex = bank*128 + program;
  356. LinuxSampler::EngineChannel* const engineChannel(fEngineChannels[pData->ctrlChannel]);
  357. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  358. /*if (pData->engine->isOffline())
  359. {
  360. engineChannel->PrepareLoadInstrument(pData->filename, rIndex);
  361. engineChannel->LoadInstrument();
  362. }
  363. else*/
  364. {
  365. try {
  366. fInstrument->LoadInstrumentInBackground(fInstrumentIds[rIndex], engineChannel);
  367. } catch(...) {}
  368. }
  369. fCurMidiProgs[pData->ctrlChannel] = index;
  370. }
  371. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  372. }
  373. // -------------------------------------------------------------------
  374. // Set ui stuff
  375. // nothing
  376. // -------------------------------------------------------------------
  377. // Plugin state
  378. void reload() override
  379. {
  380. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  381. CARLA_SAFE_ASSERT_RETURN(fInstrument != nullptr,);
  382. carla_debug("LinuxSamplerPlugin::reload() - start");
  383. const EngineProcessMode processMode(pData->engine->getProccessMode());
  384. // Safely disable plugin for reload
  385. const ScopedDisabler sd(this);
  386. if (pData->active)
  387. deactivate();
  388. clearBuffers();
  389. uint32_t aOuts;
  390. aOuts = fUses16Outs ? 32 : 2;
  391. pData->audioOut.createNew(aOuts);
  392. const uint portNameSize(pData->engine->getMaxPortNameSize());
  393. CarlaString portName;
  394. // ---------------------------------------
  395. // Audio Outputs
  396. if (fUses16Outs)
  397. {
  398. for (uint32_t i=0; i < 32; ++i)
  399. {
  400. portName.clear();
  401. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  402. {
  403. portName = pData->name;
  404. portName += ":";
  405. }
  406. portName += "out-";
  407. if ((i+2)/2 < 9)
  408. portName += "0";
  409. portName += CarlaString((i+2)/2);
  410. if (i % 2 == 0)
  411. portName += "L";
  412. else
  413. portName += "R";
  414. portName.truncate(portNameSize);
  415. pData->audioOut.ports[i].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  416. pData->audioOut.ports[i].rindex = i;
  417. }
  418. }
  419. else
  420. {
  421. // out-left
  422. portName.clear();
  423. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  424. {
  425. portName = pData->name;
  426. portName += ":";
  427. }
  428. portName += "out-left";
  429. portName.truncate(portNameSize);
  430. pData->audioOut.ports[0].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  431. pData->audioOut.ports[0].rindex = 0;
  432. // out-right
  433. portName.clear();
  434. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  435. {
  436. portName = pData->name;
  437. portName += ":";
  438. }
  439. portName += "out-right";
  440. portName.truncate(portNameSize);
  441. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  442. pData->audioOut.ports[1].rindex = 1;
  443. }
  444. // ---------------------------------------
  445. // Event Input
  446. {
  447. portName.clear();
  448. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  449. {
  450. portName = pData->name;
  451. portName += ":";
  452. }
  453. portName += "events-in";
  454. portName.truncate(portNameSize);
  455. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  456. }
  457. // ---------------------------------------
  458. // plugin hints
  459. pData->hints = 0x0;
  460. pData->hints |= PLUGIN_IS_SYNTH;
  461. pData->hints |= PLUGIN_CAN_VOLUME;
  462. if (! fUses16Outs)
  463. pData->hints |= PLUGIN_CAN_BALANCE;
  464. // extra plugin hints
  465. pData->extraHints = 0x0;
  466. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  467. if (fUses16Outs)
  468. pData->extraHints |= PLUGIN_EXTRA_HINT_USES_MULTI_PROGS;
  469. else
  470. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  471. bufferSizeChanged(pData->engine->getBufferSize());
  472. reloadPrograms(true);
  473. if (pData->active)
  474. activate();
  475. carla_debug("LinuxSamplerPlugin::reload() - end");
  476. }
  477. void reloadPrograms(bool doInit) override
  478. {
  479. carla_debug("LinuxSamplerPlugin::reloadPrograms(%s)", bool2str(doInit));
  480. // Delete old programs
  481. pData->midiprog.clear();
  482. // Query new programs
  483. uint32_t count = uint32_t(fInstrumentIds.size());
  484. // sound kits must always have at least 1 midi-program
  485. CARLA_SAFE_ASSERT_RETURN(count > 0,);
  486. pData->midiprog.createNew(count);
  487. // Update data
  488. LinuxSampler::InstrumentManager::instrument_info_t info;
  489. for (uint32_t i=0; i < pData->midiprog.count; ++i)
  490. {
  491. pData->midiprog.data[i].bank = i / 128;
  492. pData->midiprog.data[i].program = i % 128;
  493. try {
  494. info = fInstrument->GetInstrumentInfo(fInstrumentIds[i]);
  495. }
  496. catch (const LinuxSampler::InstrumentManagerException&)
  497. {
  498. continue;
  499. }
  500. pData->midiprog.data[i].name = carla_strdup(info.InstrumentName.c_str());
  501. }
  502. #ifndef BUILD_BRIDGE
  503. // Update OSC Names
  504. if (pData->engine->isOscControlRegistered())
  505. {
  506. pData->engine->oscSend_control_set_midi_program_count(pData->id, count);
  507. for (uint32_t i=0; i < count; ++i)
  508. pData->engine->oscSend_control_set_midi_program_data(pData->id, i, pData->midiprog.data[i].bank, pData->midiprog.data[i].program, pData->midiprog.data[i].name);
  509. }
  510. #endif
  511. if (doInit)
  512. {
  513. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  514. {
  515. CARLA_SAFE_ASSERT_CONTINUE(fEngineChannels[i] != nullptr);
  516. /*fEngineChannels[i]->PrepareLoadInstrument(pData->filename, 0);
  517. fEngineChannels[i]->LoadInstrument();*/
  518. fInstrument->LoadInstrumentInBackground(fInstrumentIds[0], fEngineChannels[i]);
  519. fCurMidiProgs[i] = 0;
  520. }
  521. pData->midiprog.current = 0;
  522. }
  523. else
  524. {
  525. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  526. }
  527. }
  528. // -------------------------------------------------------------------
  529. // Plugin processing
  530. #if 0
  531. void activate() override
  532. {
  533. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  534. {
  535. if (fAudioOutputDevices[i] != nullptr)
  536. fAudioOutputDevices[i]->Play();
  537. }
  538. }
  539. void deactivate() override
  540. {
  541. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  542. {
  543. if (fAudioOutputDevices[i] != nullptr)
  544. fAudioOutputDevices[i]->Stop();
  545. }
  546. }
  547. #endif
  548. void process(float** const, float** const outBuffer, const uint32_t frames) override
  549. {
  550. // --------------------------------------------------------------------------------------------------------
  551. // Check if active
  552. if (! pData->active)
  553. {
  554. // disable any output sound
  555. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  556. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  557. return;
  558. }
  559. // --------------------------------------------------------------------------------------------------------
  560. // Check if needs reset
  561. if (pData->needsReset)
  562. {
  563. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  564. {
  565. for (uint i=0; i < MAX_MIDI_CHANNELS; ++i)
  566. {
  567. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, i);
  568. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, i);
  569. }
  570. }
  571. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  572. {
  573. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  574. fMidiInputPort->DispatchNoteOff(i, 0, uint(pData->ctrlChannel));
  575. }
  576. pData->needsReset = false;
  577. }
  578. // --------------------------------------------------------------------------------------------------------
  579. // Event Input and Processing
  580. {
  581. // ----------------------------------------------------------------------------------------------------
  582. // MIDI Input (External)
  583. if (pData->extNotes.mutex.tryLock())
  584. {
  585. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin(); it.valid(); it.next())
  586. {
  587. const ExternalMidiNote& note(it.getValue());
  588. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  589. if (note.velo > 0)
  590. fMidiInputPort->DispatchNoteOn(note.note, note.velo, static_cast<uint>(note.channel));
  591. else
  592. fMidiInputPort->DispatchNoteOff(note.note, note.velo, static_cast<uint>(note.channel));
  593. }
  594. pData->extNotes.data.clear();
  595. pData->extNotes.mutex.unlock();
  596. } // End of MIDI Input (External)
  597. // ----------------------------------------------------------------------------------------------------
  598. // Event Input (System)
  599. bool allNotesOffSent = false;
  600. bool sampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  601. uint32_t nEvents = pData->event.portIn->getEventCount();
  602. uint32_t startTime = 0;
  603. uint32_t timeOffset = 0;
  604. uint32_t nextBankIds[MAX_MIDI_CHANNELS] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0 };
  605. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0 && pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  606. nextBankIds[pData->ctrlChannel] = pData->midiprog.data[pData->midiprog.current].bank;
  607. for (uint32_t i=0; i < nEvents; ++i)
  608. {
  609. const EngineEvent& event(pData->event.portIn->getEvent(i));
  610. CARLA_SAFE_ASSERT_CONTINUE(event.time < frames);
  611. CARLA_SAFE_ASSERT_BREAK(event.time >= timeOffset);
  612. if (event.time > timeOffset && sampleAccurate)
  613. {
  614. if (processSingle(outBuffer, event.time - timeOffset, timeOffset))
  615. {
  616. startTime = 0;
  617. timeOffset = event.time;
  618. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0 && pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  619. nextBankIds[pData->ctrlChannel] = pData->midiprog.data[pData->midiprog.current].bank;
  620. }
  621. else
  622. startTime += timeOffset;
  623. }
  624. // Control change
  625. switch (event.type)
  626. {
  627. case kEngineEventTypeNull:
  628. break;
  629. case kEngineEventTypeControl:
  630. {
  631. const EngineControlEvent& ctrlEvent = event.ctrl;
  632. switch (ctrlEvent.type)
  633. {
  634. case kEngineControlEventTypeNull:
  635. break;
  636. case kEngineControlEventTypeParameter:
  637. {
  638. #ifndef BUILD_BRIDGE
  639. // Control backend stuff
  640. if (event.channel == pData->ctrlChannel)
  641. {
  642. float value;
  643. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  644. {
  645. value = ctrlEvent.value;
  646. setDryWet(value, false, false);
  647. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  648. }
  649. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  650. {
  651. value = ctrlEvent.value*127.0f/100.0f;
  652. setVolume(value, false, false);
  653. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  654. }
  655. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  656. {
  657. float left, right;
  658. value = ctrlEvent.value/0.5f - 1.0f;
  659. if (value < 0.0f)
  660. {
  661. left = -1.0f;
  662. right = (value*2.0f)+1.0f;
  663. }
  664. else if (value > 0.0f)
  665. {
  666. left = (value*2.0f)-1.0f;
  667. right = 1.0f;
  668. }
  669. else
  670. {
  671. left = -1.0f;
  672. right = 1.0f;
  673. }
  674. setBalanceLeft(left, false, false);
  675. setBalanceRight(right, false, false);
  676. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  677. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  678. }
  679. }
  680. #endif
  681. // Control plugin parameters
  682. for (uint32_t k=0; k < pData->param.count; ++k)
  683. {
  684. if (pData->param.data[k].midiChannel != event.channel)
  685. continue;
  686. if (pData->param.data[k].midiCC != ctrlEvent.param)
  687. continue;
  688. if (pData->param.data[k].hints != PARAMETER_INPUT)
  689. continue;
  690. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  691. continue;
  692. float value;
  693. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  694. {
  695. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  696. }
  697. else
  698. {
  699. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  700. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  701. value = std::rint(value);
  702. }
  703. setParameterValue(k, value, false, false, false);
  704. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  705. }
  706. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  707. {
  708. fMidiInputPort->DispatchControlChange(uint8_t(ctrlEvent.param), uint8_t(ctrlEvent.value*127.0f), event.channel, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  709. }
  710. break;
  711. }
  712. case kEngineControlEventTypeMidiBank:
  713. if (event.channel < MAX_MIDI_CHANNELS && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  714. nextBankIds[event.channel] = ctrlEvent.param;
  715. break;
  716. case kEngineControlEventTypeMidiProgram:
  717. if (event.channel < MAX_MIDI_CHANNELS && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  718. {
  719. const uint32_t bankId(nextBankIds[event.channel]);
  720. const uint32_t progId(ctrlEvent.param);
  721. const uint32_t rIndex = bankId*128 + progId;
  722. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  723. {
  724. if (pData->midiprog.data[k].bank == bankId && pData->midiprog.data[k].program == progId)
  725. {
  726. LinuxSampler::EngineChannel* const engineChannel(fEngineChannels[pData->ctrlChannel]);
  727. /*if (pData->engine->isOffline())
  728. {
  729. engineChannel->PrepareLoadInstrument(pData->filename, rIndex);
  730. engineChannel->LoadInstrument();
  731. }
  732. else*/
  733. {
  734. fInstrument->LoadInstrumentInBackground(fInstrumentIds[rIndex], engineChannel);
  735. }
  736. fCurMidiProgs[event.channel] = static_cast<int32_t>(k);
  737. if (event.channel == pData->ctrlChannel)
  738. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, static_cast<int32_t>(k), 0, 0.0f);
  739. break;
  740. }
  741. }
  742. }
  743. break;
  744. case kEngineControlEventTypeAllSoundOff:
  745. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  746. {
  747. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, event.channel, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  748. }
  749. break;
  750. case kEngineControlEventTypeAllNotesOff:
  751. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  752. {
  753. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  754. {
  755. allNotesOffSent = true;
  756. sendMidiAllNotesOffToCallback();
  757. }
  758. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, event.channel, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  759. }
  760. break;
  761. }
  762. break;
  763. }
  764. case kEngineEventTypeMidi:
  765. {
  766. const EngineMidiEvent& midiEvent(event.midi);
  767. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  768. uint8_t channel = event.channel;
  769. // Fix bad note-off
  770. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  771. status = MIDI_STATUS_NOTE_OFF;
  772. if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  773. continue;
  774. if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  775. continue;
  776. if (MIDI_IS_STATUS_CHANNEL_PRESSURE(status) && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  777. continue;
  778. if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  779. continue;
  780. // put back channel in data
  781. uint8_t data[EngineMidiEvent::kDataSize];
  782. std::memcpy(data, event.midi.data, EngineMidiEvent::kDataSize);
  783. if (status < 0xF0 && channel < MAX_MIDI_CHANNELS)
  784. data[0] = uint8_t(data[0] + channel);
  785. fMidiInputPort->DispatchRaw(data, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  786. if (status == MIDI_STATUS_NOTE_ON)
  787. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, data[1], data[2]);
  788. else if (status == MIDI_STATUS_NOTE_OFF)
  789. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel,data[1], 0.0f);
  790. break;
  791. }
  792. }
  793. }
  794. pData->postRtEvents.trySplice();
  795. if (frames > timeOffset)
  796. processSingle(outBuffer, frames - timeOffset, timeOffset);
  797. } // End of Event Input and Processing
  798. }
  799. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  800. {
  801. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  802. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  803. // --------------------------------------------------------------------------------------------------------
  804. // Try lock, silence otherwise
  805. if (pData->engine->isOffline())
  806. {
  807. pData->singleMutex.lock();
  808. }
  809. else if (! pData->singleMutex.tryLock())
  810. {
  811. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  812. {
  813. for (uint32_t k=0; k < frames; ++k)
  814. outBuffer[i][k+timeOffset] = 0.0f;
  815. }
  816. return false;
  817. }
  818. // --------------------------------------------------------------------------------------------------------
  819. // Run plugin
  820. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  821. {
  822. if (LinuxSampler::AudioChannel* const outDev = fAudioOutputDevice->Channel(i))
  823. outDev->SetBuffer(outBuffer[i] + timeOffset);
  824. }
  825. fAudioOutputDevice->Render(frames);
  826. #ifndef BUILD_BRIDGE
  827. // --------------------------------------------------------------------------------------------------------
  828. // Post-processing (dry/wet, volume and balance)
  829. {
  830. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) > 0 && pData->postProc.volume != 1.0f;
  831. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) > 0 && (pData->postProc.balanceLeft != -1.0f || pData->postProc.balanceRight != 1.0f);
  832. float oldBufLeft[doBalance ? frames : 1];
  833. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  834. {
  835. // Balance
  836. if (doBalance)
  837. {
  838. if (i % 2 == 0)
  839. FloatVectorOperations::copy(oldBufLeft, outBuffer[i], static_cast<int>(frames));
  840. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  841. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  842. for (uint32_t k=0; k < frames; ++k)
  843. {
  844. if (i % 2 == 0)
  845. {
  846. // left
  847. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  848. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  849. }
  850. else
  851. {
  852. // right
  853. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  854. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  855. }
  856. }
  857. }
  858. // Volume
  859. if (doVolume)
  860. {
  861. for (uint32_t k=0; k < frames; ++k)
  862. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  863. }
  864. }
  865. } // End of Post-processing
  866. #endif
  867. // --------------------------------------------------------------------------------------------------------
  868. pData->singleMutex.unlock();
  869. return true;
  870. }
  871. #ifndef CARLA_OS_WIN // FIXME, need to update linuxsampler win32 build
  872. void bufferSizeChanged(const uint32_t) override
  873. {
  874. CARLA_SAFE_ASSERT_RETURN(fAudioOutputDevice != nullptr,);
  875. fAudioOutputDevice->ReconnectAll();
  876. }
  877. void sampleRateChanged(const double) override
  878. {
  879. CARLA_SAFE_ASSERT_RETURN(fAudioOutputDevice != nullptr,);
  880. fAudioOutputDevice->ReconnectAll();
  881. }
  882. #endif
  883. // -------------------------------------------------------------------
  884. // Plugin buffers
  885. // nothing
  886. // -------------------------------------------------------------------
  887. const void* getExtraStuff() const noexcept override
  888. {
  889. static const char xtrue[] = "true";
  890. static const char xfalse[] = "false";
  891. return fUses16Outs ? xtrue : xfalse;
  892. }
  893. bool init(const char* const filename, const char* const name, const char* const label)
  894. {
  895. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  896. // ---------------------------------------------------------------
  897. // first checks
  898. if (pData->client != nullptr)
  899. {
  900. pData->engine->setLastError("Plugin client is already registered");
  901. return false;
  902. }
  903. if (filename == nullptr || filename[0] == '\0')
  904. {
  905. pData->engine->setLastError("null filename");
  906. return false;
  907. }
  908. if (label == nullptr || label[0] == '\0')
  909. {
  910. pData->engine->setLastError("null label");
  911. return false;
  912. }
  913. // ---------------------------------------------------------------
  914. // Store format
  915. CarlaString cstype(fFormat);
  916. cstype.toLower();
  917. const char* const ctype(cstype.buffer());
  918. // ---------------------------------------------------------------
  919. // Create the LinuxSampler Engine
  920. try {
  921. fEngine = LinuxSampler::EngineFactory::Create(ctype);
  922. }
  923. catch (LinuxSampler::Exception& e)
  924. {
  925. pData->engine->setLastError(e.what());
  926. return false;
  927. }
  928. // ---------------------------------------------------------------
  929. // Init LinuxSampler stuff
  930. fAudioOutputDevice = new LinuxSampler::AudioOutputDevicePlugin(pData->engine, this, fUses16Outs);
  931. fMidiInputDevice = new LinuxSampler::MidiInputDevicePlugin(&fSampler);
  932. fMidiInputPort = fMidiInputDevice->CreateMidiPortPlugin();
  933. for (uint i=0; i < MAX_MIDI_CHANNELS; ++i)
  934. {
  935. fSamplerChannels[i] = fSampler.AddSamplerChannel();
  936. CARLA_SAFE_ASSERT_CONTINUE(fSamplerChannels[i] != nullptr);
  937. fSamplerChannels[i]->SetEngineType(ctype);
  938. fSamplerChannels[i]->SetAudioOutputDevice(fAudioOutputDevice);
  939. fEngineChannels[i] = fSamplerChannels[i]->GetEngineChannel();
  940. CARLA_SAFE_ASSERT_CONTINUE(fEngineChannels[i] != nullptr);
  941. fEngineChannels[i]->Connect(fAudioOutputDevice);
  942. fEngineChannels[i]->Volume(LinuxSampler::kVolumeMax);
  943. if (fUses16Outs)
  944. {
  945. fEngineChannels[i]->SetOutputChannel(0, i*2);
  946. fEngineChannels[i]->SetOutputChannel(1, i*2 +1);
  947. }
  948. else
  949. {
  950. fEngineChannels[i]->SetOutputChannel(0, 0);
  951. fEngineChannels[i]->SetOutputChannel(1, 1);
  952. }
  953. fMidiInputPort->Connect(fEngineChannels[i], static_cast<LinuxSampler::midi_chan_t>(i));
  954. }
  955. // ---------------------------------------------------------------
  956. // Get the Engine's Instrument Manager
  957. fInstrument = fEngine->GetInstrumentManager();
  958. if (fInstrument == nullptr)
  959. {
  960. pData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  961. return false;
  962. }
  963. // ---------------------------------------------------------------
  964. // Load the Instrument via filename
  965. try {
  966. fInstrumentIds = fInstrument->GetInstrumentFileContent(filename);
  967. }
  968. catch (const LinuxSampler::InstrumentManagerException& e)
  969. {
  970. pData->engine->setLastError(e.what());
  971. return false;
  972. }
  973. // ---------------------------------------------------------------
  974. // Get info
  975. if (fInstrumentIds.size() == 0)
  976. {
  977. pData->engine->setLastError("Failed to find any instruments");
  978. return false;
  979. }
  980. LinuxSampler::InstrumentManager::instrument_info_t info;
  981. try {
  982. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  983. }
  984. catch (const LinuxSampler::InstrumentManagerException& e)
  985. {
  986. pData->engine->setLastError(e.what());
  987. return false;
  988. }
  989. CarlaString label2(label);
  990. if (fUses16Outs && ! label2.endsWith(" (16 outs)"))
  991. label2 += " (16 outs)";
  992. fLabel = label2.dup();
  993. fMaker = carla_strdup(info.Artists.c_str());
  994. fRealName = carla_strdup(info.InstrumentName.c_str());
  995. pData->filename = carla_strdup(filename);
  996. if (name != nullptr && name[0] != '\0')
  997. pData->name = pData->engine->getUniquePluginName(name);
  998. else if (fRealName[0] != '\0')
  999. pData->name = pData->engine->getUniquePluginName(fRealName);
  1000. else
  1001. pData->name = pData->engine->getUniquePluginName(label);
  1002. // ---------------------------------------------------------------
  1003. // register client
  1004. pData->client = pData->engine->addClient(this);
  1005. if (pData->client == nullptr || ! pData->client->isOk())
  1006. {
  1007. pData->engine->setLastError("Failed to register plugin client");
  1008. return false;
  1009. }
  1010. // ---------------------------------------------------------------
  1011. // set default options
  1012. pData->options = 0x0;
  1013. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1014. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1015. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1016. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1017. return true;
  1018. }
  1019. // -------------------------------------------------------------------
  1020. private:
  1021. const bool fUses16Outs;
  1022. const char* fFormat;
  1023. const char* fLabel;
  1024. const char* fMaker;
  1025. const char* fRealName;
  1026. int32_t fCurMidiProgs[MAX_MIDI_CHANNELS];
  1027. LinuxSampler::Sampler fSampler;
  1028. LinuxSampler::Engine* fEngine;
  1029. LinuxSampler::SamplerChannel* fSamplerChannels[MAX_MIDI_CHANNELS];
  1030. LinuxSampler::EngineChannel* fEngineChannels[MAX_MIDI_CHANNELS];
  1031. LinuxSampler::AudioOutputDevicePlugin* fAudioOutputDevice;
  1032. LinuxSampler::MidiInputDevicePlugin* fMidiInputDevice;
  1033. LinuxSampler::MidiInputPortPlugin* fMidiInputPort;
  1034. LinuxSampler::InstrumentManager* fInstrument;
  1035. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  1036. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LinuxSamplerPlugin)
  1037. };
  1038. CARLA_BACKEND_END_NAMESPACE
  1039. #endif // WANT_LINUXSAMPLER
  1040. CARLA_BACKEND_START_NAMESPACE
  1041. CarlaPlugin* CarlaPlugin::newLinuxSampler(const Initializer& init, const char* const format, const bool use16Outs)
  1042. {
  1043. carla_debug("LinuxSamplerPlugin::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s, %s)", init.engine, init.filename, init.name, init.label, init.uniqueId, format, bool2str(use16Outs));
  1044. #ifdef WANT_LINUXSAMPLER
  1045. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  1046. {
  1047. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  1048. return nullptr;
  1049. }
  1050. // -------------------------------------------------------------------
  1051. // Check if file exists
  1052. if (! File(init.filename).existsAsFile())
  1053. {
  1054. init.engine->setLastError("Requested file is not valid or does not exist");
  1055. return nullptr;
  1056. }
  1057. LinuxSamplerPlugin* const plugin(new LinuxSamplerPlugin(init.engine, init.id, format, use16Outs));
  1058. if (! plugin->init(init.filename, init.name, init.label))
  1059. {
  1060. delete plugin;
  1061. return nullptr;
  1062. }
  1063. plugin->reload();
  1064. return plugin;
  1065. #else
  1066. init.engine->setLastError("linuxsampler support not available");
  1067. return nullptr;
  1068. // unused
  1069. (void)format;
  1070. (void)use16Outs;
  1071. #endif
  1072. }
  1073. CARLA_BACKEND_END_NAMESPACE