The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

2607 lines
90KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: SamplerPlugin
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Sampler audio plugin.
  24. dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
  25. juce_audio_plugin_client, juce_audio_processors,
  26. juce_audio_utils, juce_core, juce_data_structures,
  27. juce_events, juce_graphics, juce_gui_basics, juce_gui_extra
  28. exporters: xcode_mac, vs2019
  29. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  30. type: AudioProcessor
  31. mainClass: SamplerAudioProcessor
  32. useLocalCopy: 1
  33. END_JUCE_PIP_METADATA
  34. *******************************************************************************/
  35. #pragma once
  36. #include "../Assets/DemoUtilities.h"
  37. #include <array>
  38. #include <atomic>
  39. #include <memory>
  40. #include <vector>
  41. #include <tuple>
  42. #include <iomanip>
  43. #include <sstream>
  44. #include <functional>
  45. #include <mutex>
  46. namespace IDs
  47. {
  48. #define DECLARE_ID(name) const juce::Identifier name (#name);
  49. DECLARE_ID (DATA_MODEL)
  50. DECLARE_ID (sampleReader)
  51. DECLARE_ID (centreFrequencyHz)
  52. DECLARE_ID (loopMode)
  53. DECLARE_ID (loopPointsSeconds)
  54. DECLARE_ID (MPE_SETTINGS)
  55. DECLARE_ID (synthVoices)
  56. DECLARE_ID (voiceStealingEnabled)
  57. DECLARE_ID (legacyModeEnabled)
  58. DECLARE_ID (mpeZoneLayout)
  59. DECLARE_ID (legacyFirstChannel)
  60. DECLARE_ID (legacyLastChannel)
  61. DECLARE_ID (legacyPitchbendRange)
  62. DECLARE_ID (VISIBLE_RANGE)
  63. DECLARE_ID (totalRange)
  64. DECLARE_ID (visibleRange)
  65. #undef DECLARE_ID
  66. } // namespace IDs
  67. enum class LoopMode
  68. {
  69. none,
  70. forward,
  71. pingpong
  72. };
  73. // We want to send type-erased commands to the audio thread, but we also
  74. // want those commands to contain move-only resources, so that we can
  75. // construct resources on the gui thread, and then transfer ownership
  76. // cheaply to the audio thread. We can't do this with std::function
  77. // because it enforces that functions are copy-constructible.
  78. // Therefore, we use a very simple templated type-eraser here.
  79. template <typename Proc>
  80. struct Command
  81. {
  82. virtual ~Command() noexcept = default;
  83. virtual void run (Proc& proc) = 0;
  84. };
  85. template <typename Proc, typename Func>
  86. class TemplateCommand : public Command<Proc>,
  87. private Func
  88. {
  89. public:
  90. template <typename FuncPrime>
  91. explicit TemplateCommand (FuncPrime&& funcPrime)
  92. : Func (std::forward<FuncPrime> (funcPrime))
  93. {}
  94. void run (Proc& proc) override { (*this) (proc); }
  95. };
  96. template <typename Proc>
  97. class CommandFifo final
  98. {
  99. public:
  100. explicit CommandFifo (int size)
  101. : buffer ((size_t) size),
  102. abstractFifo (size)
  103. {}
  104. CommandFifo()
  105. : CommandFifo (1024)
  106. {}
  107. template <typename Item>
  108. void push (Item&& item) noexcept
  109. {
  110. auto command = makeCommand (std::forward<Item> (item));
  111. abstractFifo.write (1).forEach ([&] (int index)
  112. {
  113. buffer[size_t (index)] = std::move (command);
  114. });
  115. }
  116. void call (Proc& proc) noexcept
  117. {
  118. abstractFifo.read (abstractFifo.getNumReady()).forEach ([&] (int index)
  119. {
  120. buffer[size_t (index)]->run (proc);
  121. });
  122. }
  123. private:
  124. template <typename Func>
  125. static std::unique_ptr<Command<Proc>> makeCommand (Func&& func)
  126. {
  127. using Decayed = typename std::decay<Func>::type;
  128. return std::make_unique<TemplateCommand<Proc, Decayed>> (std::forward<Func> (func));
  129. }
  130. std::vector<std::unique_ptr<Command<Proc>>> buffer;
  131. AbstractFifo abstractFifo;
  132. };
  133. //==============================================================================
  134. // Represents the constant parts of an audio sample: its name, sample rate,
  135. // length, and the audio sample data itself.
  136. // Samples might be pretty big, so we'll keep shared_ptrs to them most of the
  137. // time, to reduce duplication and copying.
  138. class Sample final
  139. {
  140. public:
  141. Sample (AudioFormatReader& source, double maxSampleLengthSecs)
  142. : sourceSampleRate (source.sampleRate),
  143. length (jmin (int (source.lengthInSamples),
  144. int (maxSampleLengthSecs * sourceSampleRate))),
  145. data (jmin (2, int (source.numChannels)), length + 4)
  146. {
  147. if (length == 0)
  148. throw std::runtime_error ("Unable to load sample");
  149. source.read (&data, 0, length + 4, 0, true, true);
  150. }
  151. double getSampleRate() const { return sourceSampleRate; }
  152. int getLength() const { return length; }
  153. const AudioBuffer<float>& getBuffer() const { return data; }
  154. private:
  155. double sourceSampleRate;
  156. int length;
  157. AudioBuffer<float> data;
  158. };
  159. //==============================================================================
  160. // A class which contains all the information related to sample-playback, such
  161. // as sample data, loop points, and loop kind.
  162. // It is expected that multiple sampler voices will maintain pointers to a
  163. // single instance of this class, to avoid redundant duplication of sample
  164. // data in memory.
  165. class MPESamplerSound final
  166. {
  167. public:
  168. void setSample (std::unique_ptr<Sample> value)
  169. {
  170. sample = move (value);
  171. setLoopPointsInSeconds (loopPoints);
  172. }
  173. Sample* getSample() const
  174. {
  175. return sample.get();
  176. }
  177. void setLoopPointsInSeconds (Range<double> value)
  178. {
  179. loopPoints = sample == nullptr ? value
  180. : Range<double> (0, sample->getLength() / sample->getSampleRate())
  181. .constrainRange (value);
  182. }
  183. Range<double> getLoopPointsInSeconds() const
  184. {
  185. return loopPoints;
  186. }
  187. void setCentreFrequencyInHz (double centre)
  188. {
  189. centreFrequencyInHz = centre;
  190. }
  191. double getCentreFrequencyInHz() const
  192. {
  193. return centreFrequencyInHz;
  194. }
  195. void setLoopMode (LoopMode type)
  196. {
  197. loopMode = type;
  198. }
  199. LoopMode getLoopMode() const
  200. {
  201. return loopMode;
  202. }
  203. private:
  204. std::unique_ptr<Sample> sample;
  205. double centreFrequencyInHz { 440.0 };
  206. Range<double> loopPoints;
  207. LoopMode loopMode { LoopMode::none };
  208. };
  209. //==============================================================================
  210. class MPESamplerVoice : public MPESynthesiserVoice
  211. {
  212. public:
  213. explicit MPESamplerVoice (std::shared_ptr<const MPESamplerSound> sound)
  214. : samplerSound (std::move (sound))
  215. {
  216. jassert (samplerSound != nullptr);
  217. }
  218. void noteStarted() override
  219. {
  220. jassert (currentlyPlayingNote.isValid());
  221. jassert (currentlyPlayingNote.keyState == MPENote::keyDown
  222. || currentlyPlayingNote.keyState == MPENote::keyDownAndSustained);
  223. level .setTargetValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  224. frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
  225. auto loopPoints = samplerSound->getLoopPointsInSeconds();
  226. loopBegin.setTargetValue (loopPoints.getStart() * samplerSound->getSample()->getSampleRate());
  227. loopEnd .setTargetValue (loopPoints.getEnd() * samplerSound->getSample()->getSampleRate());
  228. for (auto smoothed : { &level, &frequency, &loopBegin, &loopEnd })
  229. smoothed->reset (currentSampleRate, smoothingLengthInSeconds);
  230. currentSamplePos = 0.0;
  231. tailOff = 0.0;
  232. }
  233. void noteStopped (bool allowTailOff) override
  234. {
  235. jassert (currentlyPlayingNote.keyState == MPENote::off);
  236. if (allowTailOff && tailOff == 0.0)
  237. tailOff = 1.0;
  238. else
  239. stopNote();
  240. }
  241. void notePressureChanged() override
  242. {
  243. level.setTargetValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  244. }
  245. void notePitchbendChanged() override
  246. {
  247. frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
  248. }
  249. void noteTimbreChanged() override {}
  250. void noteKeyStateChanged() override {}
  251. void renderNextBlock (AudioBuffer<float>& outputBuffer,
  252. int startSample,
  253. int numSamples) override
  254. {
  255. render (outputBuffer, startSample, numSamples);
  256. }
  257. void renderNextBlock (AudioBuffer<double>& outputBuffer,
  258. int startSample,
  259. int numSamples) override
  260. {
  261. render (outputBuffer, startSample, numSamples);
  262. }
  263. double getCurrentSamplePosition() const
  264. {
  265. return currentSamplePos;
  266. }
  267. private:
  268. template <typename Element>
  269. void render (AudioBuffer<Element>& outputBuffer, int startSample, int numSamples)
  270. {
  271. jassert (samplerSound->getSample() != nullptr);
  272. auto loopPoints = samplerSound->getLoopPointsInSeconds();
  273. loopBegin.setTargetValue (loopPoints.getStart() * samplerSound->getSample()->getSampleRate());
  274. loopEnd .setTargetValue (loopPoints.getEnd() * samplerSound->getSample()->getSampleRate());
  275. auto& data = samplerSound->getSample()->getBuffer();
  276. auto inL = data.getReadPointer (0);
  277. auto inR = data.getNumChannels() > 1 ? data.getReadPointer (1) : nullptr;
  278. auto outL = outputBuffer.getWritePointer (0, startSample);
  279. if (outL == nullptr)
  280. return;
  281. auto outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getWritePointer (1, startSample)
  282. : nullptr;
  283. size_t writePos = 0;
  284. while (--numSamples >= 0 && renderNextSample (inL, inR, outL, outR, writePos))
  285. writePos += 1;
  286. }
  287. template <typename Element>
  288. bool renderNextSample (const float* inL,
  289. const float* inR,
  290. Element* outL,
  291. Element* outR,
  292. size_t writePos)
  293. {
  294. auto currentLevel = level.getNextValue();
  295. auto currentFrequency = frequency.getNextValue();
  296. auto currentLoopBegin = loopBegin.getNextValue();
  297. auto currentLoopEnd = loopEnd.getNextValue();
  298. if (isTailingOff())
  299. {
  300. currentLevel *= tailOff;
  301. tailOff *= 0.9999;
  302. if (tailOff < 0.005)
  303. {
  304. stopNote();
  305. return false;
  306. }
  307. }
  308. auto pos = (int) currentSamplePos;
  309. auto nextPos = pos + 1;
  310. auto alpha = (Element) (currentSamplePos - pos);
  311. auto invAlpha = 1.0f - alpha;
  312. // just using a very simple linear interpolation here..
  313. auto l = static_cast<Element> (currentLevel * (inL[pos] * invAlpha + inL[nextPos] * alpha));
  314. auto r = static_cast<Element> ((inR != nullptr) ? currentLevel * (inR[pos] * invAlpha + inR[nextPos] * alpha)
  315. : l);
  316. if (outR != nullptr)
  317. {
  318. outL[writePos] += l;
  319. outR[writePos] += r;
  320. }
  321. else
  322. {
  323. outL[writePos] += (l + r) * 0.5f;
  324. }
  325. std::tie (currentSamplePos, currentDirection) = getNextState (currentFrequency,
  326. currentLoopBegin,
  327. currentLoopEnd);
  328. if (currentSamplePos > samplerSound->getSample()->getLength())
  329. {
  330. stopNote();
  331. return false;
  332. }
  333. return true;
  334. }
  335. double getSampleValue() const;
  336. bool isTailingOff() const
  337. {
  338. return tailOff != 0.0;
  339. }
  340. void stopNote()
  341. {
  342. clearCurrentNote();
  343. currentSamplePos = 0.0;
  344. }
  345. enum class Direction
  346. {
  347. forward,
  348. backward
  349. };
  350. std::tuple<double, Direction> getNextState (double freq,
  351. double begin,
  352. double end) const
  353. {
  354. auto nextPitchRatio = freq / samplerSound->getCentreFrequencyInHz();
  355. auto nextSamplePos = currentSamplePos;
  356. auto nextDirection = currentDirection;
  357. // Move the current sample pos in the correct direction
  358. switch (currentDirection)
  359. {
  360. case Direction::forward:
  361. nextSamplePos += nextPitchRatio;
  362. break;
  363. case Direction::backward:
  364. nextSamplePos -= nextPitchRatio;
  365. break;
  366. default:
  367. break;
  368. }
  369. // Update current sample position, taking loop mode into account
  370. // If the loop mode was changed while we were travelling backwards, deal
  371. // with it gracefully.
  372. if (nextDirection == Direction::backward && nextSamplePos < begin)
  373. {
  374. nextSamplePos = begin;
  375. nextDirection = Direction::forward;
  376. return std::tuple<double, Direction> (nextSamplePos, nextDirection);
  377. }
  378. if (samplerSound->getLoopMode() == LoopMode::none)
  379. return std::tuple<double, Direction> (nextSamplePos, nextDirection);
  380. if (nextDirection == Direction::forward && end < nextSamplePos && !isTailingOff())
  381. {
  382. if (samplerSound->getLoopMode() == LoopMode::forward)
  383. nextSamplePos = begin;
  384. else if (samplerSound->getLoopMode() == LoopMode::pingpong)
  385. {
  386. nextSamplePos = end;
  387. nextDirection = Direction::backward;
  388. }
  389. }
  390. return std::tuple<double, Direction> (nextSamplePos, nextDirection);
  391. }
  392. std::shared_ptr<const MPESamplerSound> samplerSound;
  393. SmoothedValue<double> level { 0 };
  394. SmoothedValue<double> frequency { 0 };
  395. SmoothedValue<double> loopBegin;
  396. SmoothedValue<double> loopEnd;
  397. double currentSamplePos { 0 };
  398. double tailOff { 0 };
  399. Direction currentDirection { Direction::forward };
  400. double smoothingLengthInSeconds { 0.01 };
  401. };
  402. template <typename Contents>
  403. class ReferenceCountingAdapter : public ReferenceCountedObject
  404. {
  405. public:
  406. template <typename... Args>
  407. explicit ReferenceCountingAdapter (Args&&... args)
  408. : contents (std::forward<Args> (args)...)
  409. {}
  410. const Contents& get() const
  411. {
  412. return contents;
  413. }
  414. Contents& get()
  415. {
  416. return contents;
  417. }
  418. private:
  419. Contents contents;
  420. };
  421. template <typename Contents, typename... Args>
  422. std::unique_ptr<ReferenceCountingAdapter<Contents>>
  423. make_reference_counted (Args&&... args)
  424. {
  425. auto adapter = new ReferenceCountingAdapter<Contents> (std::forward<Args> (args)...);
  426. return std::unique_ptr<ReferenceCountingAdapter<Contents>> (adapter);
  427. }
  428. //==============================================================================
  429. inline std::unique_ptr<AudioFormatReader> makeAudioFormatReader (AudioFormatManager& manager,
  430. const void* sampleData,
  431. size_t dataSize)
  432. {
  433. return std::unique_ptr<AudioFormatReader> (manager.createReaderFor (std::make_unique<MemoryInputStream> (sampleData,
  434. dataSize,
  435. false)));
  436. }
  437. inline std::unique_ptr<AudioFormatReader> makeAudioFormatReader (AudioFormatManager& manager,
  438. const File& file)
  439. {
  440. return std::unique_ptr<AudioFormatReader> (manager.createReaderFor (file));
  441. }
  442. //==============================================================================
  443. class AudioFormatReaderFactory
  444. {
  445. public:
  446. virtual ~AudioFormatReaderFactory() noexcept = default;
  447. virtual std::unique_ptr<AudioFormatReader> make (AudioFormatManager&) const = 0;
  448. virtual std::unique_ptr<AudioFormatReaderFactory> clone() const = 0;
  449. };
  450. //==============================================================================
  451. class MemoryAudioFormatReaderFactory : public AudioFormatReaderFactory
  452. {
  453. public:
  454. MemoryAudioFormatReaderFactory (const void* sampleDataIn, size_t dataSizeIn)
  455. : sampleData (sampleDataIn),
  456. dataSize (dataSizeIn)
  457. {}
  458. std::unique_ptr<AudioFormatReader> make (AudioFormatManager& manager) const override
  459. {
  460. return makeAudioFormatReader (manager, sampleData, dataSize);
  461. }
  462. std::unique_ptr<AudioFormatReaderFactory> clone() const override
  463. {
  464. return std::unique_ptr<AudioFormatReaderFactory> (new MemoryAudioFormatReaderFactory (*this));
  465. }
  466. private:
  467. const void* sampleData;
  468. size_t dataSize;
  469. };
  470. //==============================================================================
  471. class FileAudioFormatReaderFactory : public AudioFormatReaderFactory
  472. {
  473. public:
  474. explicit FileAudioFormatReaderFactory (File fileIn)
  475. : file (std::move (fileIn))
  476. {}
  477. std::unique_ptr<AudioFormatReader> make (AudioFormatManager& manager) const override
  478. {
  479. return makeAudioFormatReader (manager, file);
  480. }
  481. std::unique_ptr<AudioFormatReaderFactory> clone() const override
  482. {
  483. return std::unique_ptr<AudioFormatReaderFactory> (new FileAudioFormatReaderFactory (*this));
  484. }
  485. private:
  486. File file;
  487. };
  488. namespace juce
  489. {
  490. bool operator== (const MPEZoneLayout& a, const MPEZoneLayout& b)
  491. {
  492. if (a.getLowerZone() != b.getLowerZone())
  493. return false;
  494. if (a.getUpperZone() != b.getUpperZone())
  495. return false;
  496. return true;
  497. }
  498. bool operator!= (const MPEZoneLayout& a, const MPEZoneLayout& b)
  499. {
  500. return ! (a == b);
  501. }
  502. template<>
  503. struct VariantConverter<LoopMode>
  504. {
  505. static LoopMode fromVar (const var& v)
  506. {
  507. return static_cast<LoopMode> (int (v));
  508. }
  509. static var toVar (LoopMode loopMode)
  510. {
  511. return static_cast<int> (loopMode);
  512. }
  513. };
  514. template <typename Wrapped>
  515. struct GenericVariantConverter
  516. {
  517. static Wrapped fromVar (const var& v)
  518. {
  519. auto cast = dynamic_cast<ReferenceCountingAdapter<Wrapped>*> (v.getObject());
  520. jassert (cast != nullptr);
  521. return cast->get();
  522. }
  523. static var toVar (Wrapped range)
  524. {
  525. return { make_reference_counted<Wrapped> (std::move (range)).release() };
  526. }
  527. };
  528. template <typename Numeric>
  529. struct VariantConverter<Range<Numeric>> : GenericVariantConverter<Range<Numeric>> {};
  530. template<>
  531. struct VariantConverter<MPEZoneLayout> : GenericVariantConverter<MPEZoneLayout> {};
  532. template<>
  533. struct VariantConverter<std::shared_ptr<AudioFormatReaderFactory>>
  534. : GenericVariantConverter<std::shared_ptr<AudioFormatReaderFactory>>
  535. {};
  536. } // namespace juce
  537. //==============================================================================
  538. class VisibleRangeDataModel : private ValueTree::Listener
  539. {
  540. public:
  541. class Listener
  542. {
  543. public:
  544. virtual ~Listener() noexcept = default;
  545. virtual void totalRangeChanged (Range<double>) {}
  546. virtual void visibleRangeChanged (Range<double>) {}
  547. };
  548. VisibleRangeDataModel()
  549. : VisibleRangeDataModel (ValueTree (IDs::VISIBLE_RANGE))
  550. {}
  551. explicit VisibleRangeDataModel (const ValueTree& vt)
  552. : valueTree (vt),
  553. totalRange (valueTree, IDs::totalRange, nullptr),
  554. visibleRange (valueTree, IDs::visibleRange, nullptr)
  555. {
  556. jassert (valueTree.hasType (IDs::VISIBLE_RANGE));
  557. valueTree.addListener (this);
  558. }
  559. VisibleRangeDataModel (const VisibleRangeDataModel& other)
  560. : VisibleRangeDataModel (other.valueTree)
  561. {}
  562. VisibleRangeDataModel& operator= (const VisibleRangeDataModel& other)
  563. {
  564. auto copy (other);
  565. swap (copy);
  566. return *this;
  567. }
  568. Range<double> getTotalRange() const
  569. {
  570. return totalRange;
  571. }
  572. void setTotalRange (Range<double> value, UndoManager* undoManager)
  573. {
  574. totalRange.setValue (value, undoManager);
  575. setVisibleRange (visibleRange, undoManager);
  576. }
  577. Range<double> getVisibleRange() const
  578. {
  579. return visibleRange;
  580. }
  581. void setVisibleRange (Range<double> value, UndoManager* undoManager)
  582. {
  583. visibleRange.setValue (totalRange.get().constrainRange (value), undoManager);
  584. }
  585. void addListener (Listener& listener)
  586. {
  587. listenerList.add (&listener);
  588. }
  589. void removeListener (Listener& listener)
  590. {
  591. listenerList.remove (&listener);
  592. }
  593. void swap (VisibleRangeDataModel& other) noexcept
  594. {
  595. using std::swap;
  596. swap (other.valueTree, valueTree);
  597. }
  598. private:
  599. void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
  600. {
  601. if (property == IDs::totalRange)
  602. {
  603. totalRange.forceUpdateOfCachedValue();
  604. listenerList.call ([this] (Listener& l) { l.totalRangeChanged (totalRange); });
  605. }
  606. else if (property == IDs::visibleRange)
  607. {
  608. visibleRange.forceUpdateOfCachedValue();
  609. listenerList.call ([this] (Listener& l) { l.visibleRangeChanged (visibleRange); });
  610. }
  611. }
  612. void valueTreeChildAdded (ValueTree&, ValueTree&) override { jassertfalse; }
  613. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { jassertfalse; }
  614. void valueTreeChildOrderChanged (ValueTree&, int, int) override { jassertfalse; }
  615. void valueTreeParentChanged (ValueTree&) override { jassertfalse; }
  616. ValueTree valueTree;
  617. CachedValue<Range<double>> totalRange;
  618. CachedValue<Range<double>> visibleRange;
  619. ListenerList<Listener> listenerList;
  620. };
  621. //==============================================================================
  622. class MPESettingsDataModel : private ValueTree::Listener
  623. {
  624. public:
  625. class Listener
  626. {
  627. public:
  628. virtual ~Listener() noexcept = default;
  629. virtual void synthVoicesChanged (int) {}
  630. virtual void voiceStealingEnabledChanged (bool) {}
  631. virtual void legacyModeEnabledChanged (bool) {}
  632. virtual void mpeZoneLayoutChanged (const MPEZoneLayout&) {}
  633. virtual void legacyFirstChannelChanged (int) {}
  634. virtual void legacyLastChannelChanged (int) {}
  635. virtual void legacyPitchbendRangeChanged (int) {}
  636. };
  637. MPESettingsDataModel()
  638. : MPESettingsDataModel (ValueTree (IDs::MPE_SETTINGS))
  639. {}
  640. explicit MPESettingsDataModel (const ValueTree& vt)
  641. : valueTree (vt),
  642. synthVoices (valueTree, IDs::synthVoices, nullptr, 15),
  643. voiceStealingEnabled (valueTree, IDs::voiceStealingEnabled, nullptr, false),
  644. legacyModeEnabled (valueTree, IDs::legacyModeEnabled, nullptr, true),
  645. mpeZoneLayout (valueTree, IDs::mpeZoneLayout, nullptr, {}),
  646. legacyFirstChannel (valueTree, IDs::legacyFirstChannel, nullptr, 1),
  647. legacyLastChannel (valueTree, IDs::legacyLastChannel, nullptr, 15),
  648. legacyPitchbendRange (valueTree, IDs::legacyPitchbendRange, nullptr, 48)
  649. {
  650. jassert (valueTree.hasType (IDs::MPE_SETTINGS));
  651. valueTree.addListener (this);
  652. }
  653. MPESettingsDataModel (const MPESettingsDataModel& other)
  654. : MPESettingsDataModel (other.valueTree)
  655. {}
  656. MPESettingsDataModel& operator= (const MPESettingsDataModel& other)
  657. {
  658. auto copy (other);
  659. swap (copy);
  660. return *this;
  661. }
  662. int getSynthVoices() const
  663. {
  664. return synthVoices;
  665. }
  666. void setSynthVoices (int value, UndoManager* undoManager)
  667. {
  668. synthVoices.setValue (Range<int> (1, 20).clipValue (value), undoManager);
  669. }
  670. bool getVoiceStealingEnabled() const
  671. {
  672. return voiceStealingEnabled;
  673. }
  674. void setVoiceStealingEnabled (bool value, UndoManager* undoManager)
  675. {
  676. voiceStealingEnabled.setValue (value, undoManager);
  677. }
  678. bool getLegacyModeEnabled() const
  679. {
  680. return legacyModeEnabled;
  681. }
  682. void setLegacyModeEnabled (bool value, UndoManager* undoManager)
  683. {
  684. legacyModeEnabled.setValue (value, undoManager);
  685. }
  686. MPEZoneLayout getMPEZoneLayout() const
  687. {
  688. return mpeZoneLayout;
  689. }
  690. void setMPEZoneLayout (MPEZoneLayout value, UndoManager* undoManager)
  691. {
  692. mpeZoneLayout.setValue (value, undoManager);
  693. }
  694. int getLegacyFirstChannel() const
  695. {
  696. return legacyFirstChannel;
  697. }
  698. void setLegacyFirstChannel (int value, UndoManager* undoManager)
  699. {
  700. legacyFirstChannel.setValue (Range<int> (1, legacyLastChannel).clipValue (value), undoManager);
  701. }
  702. int getLegacyLastChannel() const
  703. {
  704. return legacyLastChannel;
  705. }
  706. void setLegacyLastChannel (int value, UndoManager* undoManager)
  707. {
  708. legacyLastChannel.setValue (Range<int> (legacyFirstChannel, 15).clipValue (value), undoManager);
  709. }
  710. int getLegacyPitchbendRange() const
  711. {
  712. return legacyPitchbendRange;
  713. }
  714. void setLegacyPitchbendRange (int value, UndoManager* undoManager)
  715. {
  716. legacyPitchbendRange.setValue (Range<int> (0, 95).clipValue (value), undoManager);
  717. }
  718. void addListener (Listener& listener)
  719. {
  720. listenerList.add (&listener);
  721. }
  722. void removeListener (Listener& listener)
  723. {
  724. listenerList.remove (&listener);
  725. }
  726. void swap (MPESettingsDataModel& other) noexcept
  727. {
  728. using std::swap;
  729. swap (other.valueTree, valueTree);
  730. }
  731. private:
  732. void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
  733. {
  734. if (property == IDs::synthVoices)
  735. {
  736. synthVoices.forceUpdateOfCachedValue();
  737. listenerList.call ([this] (Listener& l) { l.synthVoicesChanged (synthVoices); });
  738. }
  739. else if (property == IDs::voiceStealingEnabled)
  740. {
  741. voiceStealingEnabled.forceUpdateOfCachedValue();
  742. listenerList.call ([this] (Listener& l) { l.voiceStealingEnabledChanged (voiceStealingEnabled); });
  743. }
  744. else if (property == IDs::legacyModeEnabled)
  745. {
  746. legacyModeEnabled.forceUpdateOfCachedValue();
  747. listenerList.call ([this] (Listener& l) { l.legacyModeEnabledChanged (legacyModeEnabled); });
  748. }
  749. else if (property == IDs::mpeZoneLayout)
  750. {
  751. mpeZoneLayout.forceUpdateOfCachedValue();
  752. listenerList.call ([this] (Listener& l) { l.mpeZoneLayoutChanged (mpeZoneLayout); });
  753. }
  754. else if (property == IDs::legacyFirstChannel)
  755. {
  756. legacyFirstChannel.forceUpdateOfCachedValue();
  757. listenerList.call ([this] (Listener& l) { l.legacyFirstChannelChanged (legacyFirstChannel); });
  758. }
  759. else if (property == IDs::legacyLastChannel)
  760. {
  761. legacyLastChannel.forceUpdateOfCachedValue();
  762. listenerList.call ([this] (Listener& l) { l.legacyLastChannelChanged (legacyLastChannel); });
  763. }
  764. else if (property == IDs::legacyPitchbendRange)
  765. {
  766. legacyPitchbendRange.forceUpdateOfCachedValue();
  767. listenerList.call ([this] (Listener& l) { l.legacyPitchbendRangeChanged (legacyPitchbendRange); });
  768. }
  769. }
  770. void valueTreeChildAdded (ValueTree&, ValueTree&) override { jassertfalse; }
  771. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { jassertfalse; }
  772. void valueTreeChildOrderChanged (ValueTree&, int, int) override { jassertfalse; }
  773. void valueTreeParentChanged (ValueTree&) override { jassertfalse; }
  774. ValueTree valueTree;
  775. CachedValue<int> synthVoices;
  776. CachedValue<bool> voiceStealingEnabled;
  777. CachedValue<bool> legacyModeEnabled;
  778. CachedValue<MPEZoneLayout> mpeZoneLayout;
  779. CachedValue<int> legacyFirstChannel;
  780. CachedValue<int> legacyLastChannel;
  781. CachedValue<int> legacyPitchbendRange;
  782. ListenerList<Listener> listenerList;
  783. };
  784. //==============================================================================
  785. class DataModel : private ValueTree::Listener
  786. {
  787. public:
  788. class Listener
  789. {
  790. public:
  791. virtual ~Listener() noexcept = default;
  792. virtual void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory>) {}
  793. virtual void centreFrequencyHzChanged (double) {}
  794. virtual void loopModeChanged (LoopMode) {}
  795. virtual void loopPointsSecondsChanged (Range<double>) {}
  796. };
  797. explicit DataModel (AudioFormatManager& audioFormatManagerIn)
  798. : DataModel (audioFormatManagerIn, ValueTree (IDs::DATA_MODEL))
  799. {}
  800. DataModel (AudioFormatManager& audioFormatManagerIn, const ValueTree& vt)
  801. : audioFormatManager (&audioFormatManagerIn),
  802. valueTree (vt),
  803. sampleReader (valueTree, IDs::sampleReader, nullptr),
  804. centreFrequencyHz (valueTree, IDs::centreFrequencyHz, nullptr),
  805. loopMode (valueTree, IDs::loopMode, nullptr, LoopMode::none),
  806. loopPointsSeconds (valueTree, IDs::loopPointsSeconds, nullptr)
  807. {
  808. jassert (valueTree.hasType (IDs::DATA_MODEL));
  809. valueTree.addListener (this);
  810. }
  811. DataModel (const DataModel& other)
  812. : DataModel (*other.audioFormatManager, other.valueTree)
  813. {}
  814. DataModel& operator= (const DataModel& other)
  815. {
  816. auto copy (other);
  817. swap (copy);
  818. return *this;
  819. }
  820. std::unique_ptr<AudioFormatReader> getSampleReader() const
  821. {
  822. return sampleReader != nullptr ? sampleReader.get()->make (*audioFormatManager) : nullptr;
  823. }
  824. void setSampleReader (std::unique_ptr<AudioFormatReaderFactory> readerFactory,
  825. UndoManager* undoManager)
  826. {
  827. sampleReader.setValue (move (readerFactory), undoManager);
  828. setLoopPointsSeconds (Range<double> (0, getSampleLengthSeconds()).constrainRange (loopPointsSeconds),
  829. undoManager);
  830. }
  831. double getSampleLengthSeconds() const
  832. {
  833. if (auto r = getSampleReader())
  834. return (double) r->lengthInSamples / r->sampleRate;
  835. return 1.0;
  836. }
  837. double getCentreFrequencyHz() const
  838. {
  839. return centreFrequencyHz;
  840. }
  841. void setCentreFrequencyHz (double value, UndoManager* undoManager)
  842. {
  843. centreFrequencyHz.setValue (Range<double> (20, 20000).clipValue (value),
  844. undoManager);
  845. }
  846. LoopMode getLoopMode() const
  847. {
  848. return loopMode;
  849. }
  850. void setLoopMode (LoopMode value, UndoManager* undoManager)
  851. {
  852. loopMode.setValue (value, undoManager);
  853. }
  854. Range<double> getLoopPointsSeconds() const
  855. {
  856. return loopPointsSeconds;
  857. }
  858. void setLoopPointsSeconds (Range<double> value, UndoManager* undoManager)
  859. {
  860. loopPointsSeconds.setValue (Range<double> (0, getSampleLengthSeconds()).constrainRange (value),
  861. undoManager);
  862. }
  863. MPESettingsDataModel mpeSettings()
  864. {
  865. return MPESettingsDataModel (valueTree.getOrCreateChildWithName (IDs::MPE_SETTINGS, nullptr));
  866. }
  867. void addListener (Listener& listener)
  868. {
  869. listenerList.add (&listener);
  870. }
  871. void removeListener (Listener& listener)
  872. {
  873. listenerList.remove (&listener);
  874. }
  875. void swap (DataModel& other) noexcept
  876. {
  877. using std::swap;
  878. swap (other.valueTree, valueTree);
  879. }
  880. AudioFormatManager& getAudioFormatManager() const
  881. {
  882. return *audioFormatManager;
  883. }
  884. private:
  885. void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
  886. {
  887. if (property == IDs::sampleReader)
  888. {
  889. sampleReader.forceUpdateOfCachedValue();
  890. listenerList.call ([this] (Listener& l) { l.sampleReaderChanged (sampleReader); });
  891. }
  892. else if (property == IDs::centreFrequencyHz)
  893. {
  894. centreFrequencyHz.forceUpdateOfCachedValue();
  895. listenerList.call ([this] (Listener& l) { l.centreFrequencyHzChanged (centreFrequencyHz); });
  896. }
  897. else if (property == IDs::loopMode)
  898. {
  899. loopMode.forceUpdateOfCachedValue();
  900. listenerList.call ([this] (Listener& l) { l.loopModeChanged (loopMode); });
  901. }
  902. else if (property == IDs::loopPointsSeconds)
  903. {
  904. loopPointsSeconds.forceUpdateOfCachedValue();
  905. listenerList.call ([this] (Listener& l) { l.loopPointsSecondsChanged (loopPointsSeconds); });
  906. }
  907. }
  908. void valueTreeChildAdded (ValueTree&, ValueTree&) override {}
  909. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { jassertfalse; }
  910. void valueTreeChildOrderChanged (ValueTree&, int, int) override { jassertfalse; }
  911. void valueTreeParentChanged (ValueTree&) override { jassertfalse; }
  912. AudioFormatManager* audioFormatManager;
  913. ValueTree valueTree;
  914. CachedValue<std::shared_ptr<AudioFormatReaderFactory>> sampleReader;
  915. CachedValue<double> centreFrequencyHz;
  916. CachedValue<LoopMode> loopMode;
  917. CachedValue<Range<double>> loopPointsSeconds;
  918. ListenerList<Listener> listenerList;
  919. };
  920. namespace
  921. {
  922. void initialiseComboBoxWithConsecutiveIntegers (Component& owner,
  923. ComboBox& comboBox,
  924. Label& label,
  925. int firstValue,
  926. int numValues,
  927. int valueToSelect)
  928. {
  929. for (auto i = 0; i < numValues; ++i)
  930. comboBox.addItem (String (i + firstValue), i + 1);
  931. comboBox.setSelectedId (valueToSelect - firstValue + 1);
  932. label.attachToComponent (&comboBox, true);
  933. owner.addAndMakeVisible (comboBox);
  934. }
  935. constexpr int controlHeight = 24;
  936. constexpr int controlSeparation = 6;
  937. } // namespace
  938. //==============================================================================
  939. class MPELegacySettingsComponent final : public Component,
  940. private MPESettingsDataModel::Listener
  941. {
  942. public:
  943. explicit MPELegacySettingsComponent (const MPESettingsDataModel& model,
  944. UndoManager& um)
  945. : dataModel (model),
  946. undoManager (&um)
  947. {
  948. dataModel.addListener (*this);
  949. initialiseComboBoxWithConsecutiveIntegers (*this, legacyStartChannel, legacyStartChannelLabel, 1, 16, 1);
  950. initialiseComboBoxWithConsecutiveIntegers (*this, legacyEndChannel, legacyEndChannelLabel, 1, 16, 16);
  951. initialiseComboBoxWithConsecutiveIntegers (*this, legacyPitchbendRange, legacyPitchbendRangeLabel, 0, 96, 2);
  952. legacyStartChannel.onChange = [this]
  953. {
  954. if (isLegacyModeValid())
  955. {
  956. undoManager->beginNewTransaction();
  957. dataModel.setLegacyFirstChannel (getFirstChannel(), undoManager);
  958. }
  959. };
  960. legacyEndChannel.onChange = [this]
  961. {
  962. if (isLegacyModeValid())
  963. {
  964. undoManager->beginNewTransaction();
  965. dataModel.setLegacyLastChannel (getLastChannel(), undoManager);
  966. }
  967. };
  968. legacyPitchbendRange.onChange = [this]
  969. {
  970. if (isLegacyModeValid())
  971. {
  972. undoManager->beginNewTransaction();
  973. dataModel.setLegacyPitchbendRange (legacyPitchbendRange.getText().getIntValue(), undoManager);
  974. }
  975. };
  976. }
  977. int getMinHeight() const
  978. {
  979. return (controlHeight * 3) + (controlSeparation * 2);
  980. }
  981. private:
  982. void resized() override
  983. {
  984. Rectangle<int> r (proportionOfWidth (0.65f), 0, proportionOfWidth (0.25f), getHeight());
  985. for (auto& comboBox : { &legacyStartChannel, &legacyEndChannel, &legacyPitchbendRange })
  986. {
  987. comboBox->setBounds (r.removeFromTop (controlHeight));
  988. r.removeFromTop (controlSeparation);
  989. }
  990. }
  991. bool isLegacyModeValid() const
  992. {
  993. if (! areLegacyModeParametersValid())
  994. {
  995. handleInvalidLegacyModeParameters();
  996. return false;
  997. }
  998. return true;
  999. }
  1000. void legacyFirstChannelChanged (int value) override
  1001. {
  1002. legacyStartChannel.setSelectedId (value, dontSendNotification);
  1003. }
  1004. void legacyLastChannelChanged (int value) override
  1005. {
  1006. legacyEndChannel.setSelectedId (value, dontSendNotification);
  1007. }
  1008. void legacyPitchbendRangeChanged (int value) override
  1009. {
  1010. legacyPitchbendRange.setSelectedId (value + 1, dontSendNotification);
  1011. }
  1012. int getFirstChannel() const
  1013. {
  1014. return legacyStartChannel.getText().getIntValue();
  1015. }
  1016. int getLastChannel() const
  1017. {
  1018. return legacyEndChannel.getText().getIntValue();
  1019. }
  1020. bool areLegacyModeParametersValid() const
  1021. {
  1022. return getFirstChannel() <= getLastChannel();
  1023. }
  1024. void handleInvalidLegacyModeParameters() const
  1025. {
  1026. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  1027. "Invalid legacy mode channel layout",
  1028. "Cannot set legacy mode start/end channel:\n"
  1029. "The end channel must not be less than the start channel!",
  1030. "Got it");
  1031. }
  1032. MPESettingsDataModel dataModel;
  1033. ComboBox legacyStartChannel, legacyEndChannel, legacyPitchbendRange;
  1034. Label legacyStartChannelLabel { {}, "First channel" },
  1035. legacyEndChannelLabel { {}, "Last channel" },
  1036. legacyPitchbendRangeLabel { {}, "Pitchbend range (semitones)" };
  1037. UndoManager* undoManager;
  1038. };
  1039. //==============================================================================
  1040. class MPENewSettingsComponent final : public Component,
  1041. private MPESettingsDataModel::Listener
  1042. {
  1043. public:
  1044. MPENewSettingsComponent (const MPESettingsDataModel& model,
  1045. UndoManager& um)
  1046. : dataModel (model),
  1047. undoManager (&um)
  1048. {
  1049. dataModel.addListener (*this);
  1050. addAndMakeVisible (isLowerZoneButton);
  1051. isLowerZoneButton.setToggleState (true, NotificationType::dontSendNotification);
  1052. initialiseComboBoxWithConsecutiveIntegers (*this, memberChannels, memberChannelsLabel, 0, 16, 15);
  1053. initialiseComboBoxWithConsecutiveIntegers (*this, masterPitchbendRange, masterPitchbendRangeLabel, 0, 96, 2);
  1054. initialiseComboBoxWithConsecutiveIntegers (*this, notePitchbendRange, notePitchbendRangeLabel, 0, 96, 48);
  1055. for (auto& button : { &setZoneButton, &clearAllZonesButton })
  1056. addAndMakeVisible (button);
  1057. setZoneButton.onClick = [this]
  1058. {
  1059. auto isLowerZone = isLowerZoneButton.getToggleState();
  1060. auto numMemberChannels = memberChannels.getText().getIntValue();
  1061. auto perNotePb = notePitchbendRange.getText().getIntValue();
  1062. auto masterPb = masterPitchbendRange.getText().getIntValue();
  1063. if (isLowerZone)
  1064. zoneLayout.setLowerZone (numMemberChannels, perNotePb, masterPb);
  1065. else
  1066. zoneLayout.setUpperZone (numMemberChannels, perNotePb, masterPb);
  1067. undoManager->beginNewTransaction();
  1068. dataModel.setMPEZoneLayout (zoneLayout, undoManager);
  1069. };
  1070. clearAllZonesButton.onClick = [this]
  1071. {
  1072. zoneLayout.clearAllZones();
  1073. undoManager->beginNewTransaction();
  1074. dataModel.setMPEZoneLayout (zoneLayout, undoManager);
  1075. };
  1076. }
  1077. int getMinHeight() const
  1078. {
  1079. return (controlHeight * 6) + (controlSeparation * 6);
  1080. }
  1081. private:
  1082. void resized() override
  1083. {
  1084. Rectangle<int> r (proportionOfWidth (0.65f), 0, proportionOfWidth (0.25f), getHeight());
  1085. isLowerZoneButton.setBounds (r.removeFromTop (controlHeight));
  1086. r.removeFromTop (controlSeparation);
  1087. for (auto& comboBox : { &memberChannels, &masterPitchbendRange, &notePitchbendRange })
  1088. {
  1089. comboBox->setBounds (r.removeFromTop (controlHeight));
  1090. r.removeFromTop (controlSeparation);
  1091. }
  1092. r.removeFromTop (controlSeparation);
  1093. auto buttonLeft = proportionOfWidth (0.5f);
  1094. setZoneButton.setBounds (r.removeFromTop (controlHeight).withLeft (buttonLeft));
  1095. r.removeFromTop (controlSeparation);
  1096. clearAllZonesButton.setBounds (r.removeFromTop (controlHeight).withLeft (buttonLeft));
  1097. }
  1098. void mpeZoneLayoutChanged (const MPEZoneLayout& value) override
  1099. {
  1100. zoneLayout = value;
  1101. }
  1102. MPESettingsDataModel dataModel;
  1103. MPEZoneLayout zoneLayout;
  1104. ComboBox memberChannels, masterPitchbendRange, notePitchbendRange;
  1105. ToggleButton isLowerZoneButton { "Lower zone" };
  1106. Label memberChannelsLabel { {}, "Nr. of member channels" },
  1107. masterPitchbendRangeLabel { {}, "Master pitchbend range (semitones)" },
  1108. notePitchbendRangeLabel { {}, "Note pitchbend range (semitones)" };
  1109. TextButton setZoneButton { "Set zone" },
  1110. clearAllZonesButton { "Clear all zones" };
  1111. UndoManager* undoManager;
  1112. };
  1113. //==============================================================================
  1114. class MPESettingsComponent final : public Component,
  1115. private MPESettingsDataModel::Listener
  1116. {
  1117. public:
  1118. MPESettingsComponent (const MPESettingsDataModel& model,
  1119. UndoManager& um)
  1120. : dataModel (model),
  1121. legacySettings (dataModel, um),
  1122. newSettings (dataModel, um),
  1123. undoManager (&um)
  1124. {
  1125. dataModel.addListener (*this);
  1126. addAndMakeVisible (newSettings);
  1127. addChildComponent (legacySettings);
  1128. initialiseComboBoxWithConsecutiveIntegers (*this, numberOfVoices, numberOfVoicesLabel, 1, 20, 15);
  1129. numberOfVoices.onChange = [this]
  1130. {
  1131. undoManager->beginNewTransaction();
  1132. dataModel.setSynthVoices (numberOfVoices.getText().getIntValue(), undoManager);
  1133. };
  1134. for (auto& button : { &legacyModeEnabledToggle, &voiceStealingEnabledToggle })
  1135. {
  1136. addAndMakeVisible (button);
  1137. }
  1138. legacyModeEnabledToggle.onClick = [this]
  1139. {
  1140. undoManager->beginNewTransaction();
  1141. dataModel.setLegacyModeEnabled (legacyModeEnabledToggle.getToggleState(), undoManager);
  1142. };
  1143. voiceStealingEnabledToggle.onClick = [this]
  1144. {
  1145. undoManager->beginNewTransaction();
  1146. dataModel.setVoiceStealingEnabled (voiceStealingEnabledToggle.getToggleState(), undoManager);
  1147. };
  1148. }
  1149. private:
  1150. void resized() override
  1151. {
  1152. auto topHeight = jmax (legacySettings.getMinHeight(), newSettings.getMinHeight());
  1153. auto r = getLocalBounds();
  1154. r.removeFromTop (15);
  1155. auto top = r.removeFromTop (topHeight);
  1156. legacySettings.setBounds (top);
  1157. newSettings.setBounds (top);
  1158. r.removeFromLeft (proportionOfWidth (0.65f));
  1159. r = r.removeFromLeft (proportionOfWidth (0.25f));
  1160. auto toggleLeft = proportionOfWidth (0.25f);
  1161. legacyModeEnabledToggle.setBounds (r.removeFromTop (controlHeight).withLeft (toggleLeft));
  1162. r.removeFromTop (controlSeparation);
  1163. voiceStealingEnabledToggle.setBounds (r.removeFromTop (controlHeight).withLeft (toggleLeft));
  1164. r.removeFromTop (controlSeparation);
  1165. numberOfVoices.setBounds (r.removeFromTop (controlHeight));
  1166. }
  1167. void legacyModeEnabledChanged (bool value) override
  1168. {
  1169. legacySettings.setVisible (value);
  1170. newSettings.setVisible (! value);
  1171. legacyModeEnabledToggle.setToggleState (value, dontSendNotification);
  1172. }
  1173. void voiceStealingEnabledChanged (bool value) override
  1174. {
  1175. voiceStealingEnabledToggle.setToggleState (value, dontSendNotification);
  1176. }
  1177. void synthVoicesChanged (int value) override
  1178. {
  1179. numberOfVoices.setSelectedId (value, dontSendNotification);
  1180. }
  1181. MPESettingsDataModel dataModel;
  1182. MPELegacySettingsComponent legacySettings;
  1183. MPENewSettingsComponent newSettings;
  1184. ToggleButton legacyModeEnabledToggle { "Enable Legacy Mode" },
  1185. voiceStealingEnabledToggle { "Enable synth voice stealing" };
  1186. ComboBox numberOfVoices;
  1187. Label numberOfVoicesLabel { {}, "Number of synth voices" };
  1188. UndoManager* undoManager;
  1189. };
  1190. //==============================================================================
  1191. class LoopPointMarker : public Component
  1192. {
  1193. public:
  1194. using MouseCallback = std::function<void (LoopPointMarker&, const MouseEvent&)>;
  1195. LoopPointMarker (String marker,
  1196. MouseCallback onMouseDownIn,
  1197. MouseCallback onMouseDragIn,
  1198. MouseCallback onMouseUpIn)
  1199. : text (std::move (marker)),
  1200. onMouseDown (std::move (onMouseDownIn)),
  1201. onMouseDrag (std::move (onMouseDragIn)),
  1202. onMouseUp (std::move (onMouseUpIn))
  1203. {
  1204. setMouseCursor (MouseCursor::LeftRightResizeCursor);
  1205. }
  1206. private:
  1207. void resized() override
  1208. {
  1209. auto height = 20;
  1210. auto triHeight = 6;
  1211. auto bounds = getLocalBounds();
  1212. Path newPath;
  1213. newPath.addRectangle (bounds.removeFromBottom (height));
  1214. newPath.startNewSubPath (bounds.getBottomLeft().toFloat());
  1215. newPath.lineTo (bounds.getBottomRight().toFloat());
  1216. Point<float> apex (static_cast<float> (bounds.getX() + (bounds.getWidth() / 2)),
  1217. static_cast<float> (bounds.getBottom() - triHeight));
  1218. newPath.lineTo (apex);
  1219. newPath.closeSubPath();
  1220. newPath.addLineSegment (Line<float> (apex, Point<float> (apex.getX(), 0)), 1);
  1221. path = newPath;
  1222. }
  1223. void paint (Graphics& g) override
  1224. {
  1225. g.setColour (Colours::deepskyblue);
  1226. g.fillPath (path);
  1227. auto height = 20;
  1228. g.setColour (Colours::white);
  1229. g.drawText (text, getLocalBounds().removeFromBottom (height), Justification::centred);
  1230. }
  1231. bool hitTest (int x, int y) override
  1232. {
  1233. return path.contains ((float) x, (float) y);
  1234. }
  1235. void mouseDown (const MouseEvent& e) override
  1236. {
  1237. onMouseDown (*this, e);
  1238. }
  1239. void mouseDrag (const MouseEvent& e) override
  1240. {
  1241. onMouseDrag (*this, e);
  1242. }
  1243. void mouseUp (const MouseEvent& e) override
  1244. {
  1245. onMouseUp (*this, e);
  1246. }
  1247. String text;
  1248. Path path;
  1249. MouseCallback onMouseDown;
  1250. MouseCallback onMouseDrag;
  1251. MouseCallback onMouseUp;
  1252. };
  1253. //==============================================================================
  1254. class Ruler : public Component,
  1255. private VisibleRangeDataModel::Listener
  1256. {
  1257. public:
  1258. explicit Ruler (const VisibleRangeDataModel& model)
  1259. : visibleRange (model)
  1260. {
  1261. visibleRange.addListener (*this);
  1262. setMouseCursor (MouseCursor::LeftRightResizeCursor);
  1263. }
  1264. private:
  1265. void paint (Graphics& g) override
  1266. {
  1267. auto minDivisionWidth = 50.0f;
  1268. auto maxDivisions = (float) getWidth() / minDivisionWidth;
  1269. auto lookFeel = dynamic_cast<LookAndFeel_V4*> (&getLookAndFeel());
  1270. auto bg = lookFeel->getCurrentColourScheme()
  1271. .getUIColour (LookAndFeel_V4::ColourScheme::UIColour::widgetBackground);
  1272. g.setGradientFill (ColourGradient (bg.brighter(),
  1273. 0,
  1274. 0,
  1275. bg.darker(),
  1276. 0,
  1277. (float) getHeight(),
  1278. false));
  1279. g.fillAll();
  1280. g.setColour (bg.brighter());
  1281. g.drawHorizontalLine (0, 0.0f, (float) getWidth());
  1282. g.setColour (bg.darker());
  1283. g.drawHorizontalLine (1, 0.0f, (float) getWidth());
  1284. g.setColour (Colours::lightgrey);
  1285. auto minLog = std::ceil (std::log10 (visibleRange.getVisibleRange().getLength() / maxDivisions));
  1286. auto precision = 2 + std::abs (minLog);
  1287. auto divisionMagnitude = std::pow (10, minLog);
  1288. auto startingDivision = std::ceil (visibleRange.getVisibleRange().getStart() / divisionMagnitude);
  1289. for (auto div = startingDivision; div * divisionMagnitude < visibleRange.getVisibleRange().getEnd(); ++div)
  1290. {
  1291. auto time = div * divisionMagnitude;
  1292. auto xPos = (time - visibleRange.getVisibleRange().getStart()) * getWidth()
  1293. / visibleRange.getVisibleRange().getLength();
  1294. std::ostringstream outStream;
  1295. outStream << std::setprecision (roundToInt (precision)) << time;
  1296. const auto bounds = Rectangle<int> (Point<int> (roundToInt (xPos) + 3, 0),
  1297. Point<int> (roundToInt (xPos + minDivisionWidth), getHeight()));
  1298. g.drawText (outStream.str(), bounds, Justification::centredLeft, false);
  1299. g.drawVerticalLine (roundToInt (xPos), 2.0f, (float) getHeight());
  1300. }
  1301. }
  1302. void mouseDown (const MouseEvent& e) override
  1303. {
  1304. visibleRangeOnMouseDown = visibleRange.getVisibleRange();
  1305. timeOnMouseDown = visibleRange.getVisibleRange().getStart()
  1306. + (visibleRange.getVisibleRange().getLength() * e.getMouseDownX()) / getWidth();
  1307. }
  1308. void mouseDrag (const MouseEvent& e) override
  1309. {
  1310. // Work out the scale of the new range
  1311. auto unitDistance = 100.0f;
  1312. auto scaleFactor = 1.0 / std::pow (2, (float) e.getDistanceFromDragStartY() / unitDistance);
  1313. // Now position it so that the mouse continues to point at the same
  1314. // place on the ruler.
  1315. auto visibleLength = std::max (0.12, visibleRangeOnMouseDown.getLength() * scaleFactor);
  1316. auto rangeBegin = timeOnMouseDown - visibleLength * e.x / getWidth();
  1317. const Range<double> range (rangeBegin, rangeBegin + visibleLength);
  1318. visibleRange.setVisibleRange (range, nullptr);
  1319. }
  1320. void visibleRangeChanged (Range<double>) override
  1321. {
  1322. repaint();
  1323. }
  1324. VisibleRangeDataModel visibleRange;
  1325. Range<double> visibleRangeOnMouseDown;
  1326. double timeOnMouseDown;
  1327. };
  1328. //==============================================================================
  1329. class LoopPointsOverlay : public Component,
  1330. private DataModel::Listener,
  1331. private VisibleRangeDataModel::Listener
  1332. {
  1333. public:
  1334. LoopPointsOverlay (const DataModel& dModel,
  1335. const VisibleRangeDataModel& vModel,
  1336. UndoManager& undoManagerIn)
  1337. : dataModel (dModel),
  1338. visibleRange (vModel),
  1339. beginMarker ("B",
  1340. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseDown (m, e); },
  1341. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointDragged (m, e); },
  1342. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseUp (m, e); }),
  1343. endMarker ("E",
  1344. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseDown (m, e); },
  1345. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointDragged (m, e); },
  1346. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseUp (m, e); }),
  1347. undoManager (&undoManagerIn)
  1348. {
  1349. dataModel .addListener (*this);
  1350. visibleRange.addListener (*this);
  1351. for (auto ptr : { &beginMarker, &endMarker })
  1352. addAndMakeVisible (ptr);
  1353. }
  1354. private:
  1355. void resized() override
  1356. {
  1357. positionLoopPointMarkers();
  1358. }
  1359. void loopPointMouseDown (LoopPointMarker&, const MouseEvent&)
  1360. {
  1361. loopPointsOnMouseDown = dataModel.getLoopPointsSeconds();
  1362. undoManager->beginNewTransaction();
  1363. }
  1364. void loopPointDragged (LoopPointMarker& marker, const MouseEvent& e)
  1365. {
  1366. auto x = xPositionToTime (e.getEventRelativeTo (this).position.x);
  1367. const Range<double> newLoopRange (&marker == &beginMarker ? x : loopPointsOnMouseDown.getStart(),
  1368. &marker == &endMarker ? x : loopPointsOnMouseDown.getEnd());
  1369. dataModel.setLoopPointsSeconds (newLoopRange, undoManager);
  1370. }
  1371. void loopPointMouseUp (LoopPointMarker& marker, const MouseEvent& e)
  1372. {
  1373. auto x = xPositionToTime (e.getEventRelativeTo (this).position.x);
  1374. const Range<double> newLoopRange (&marker == &beginMarker ? x : loopPointsOnMouseDown.getStart(),
  1375. &marker == &endMarker ? x : loopPointsOnMouseDown.getEnd());
  1376. dataModel.setLoopPointsSeconds (newLoopRange, undoManager);
  1377. }
  1378. void loopPointsSecondsChanged (Range<double>) override
  1379. {
  1380. positionLoopPointMarkers();
  1381. }
  1382. void visibleRangeChanged (Range<double>) override
  1383. {
  1384. positionLoopPointMarkers();
  1385. }
  1386. double timeToXPosition (double time) const
  1387. {
  1388. return (time - visibleRange.getVisibleRange().getStart()) * getWidth()
  1389. / visibleRange.getVisibleRange().getLength();
  1390. }
  1391. double xPositionToTime (double xPosition) const
  1392. {
  1393. return ((xPosition * visibleRange.getVisibleRange().getLength()) / getWidth())
  1394. + visibleRange.getVisibleRange().getStart();
  1395. }
  1396. void positionLoopPointMarkers()
  1397. {
  1398. auto halfMarkerWidth = 7;
  1399. for (auto tup : { std::make_tuple (&beginMarker, dataModel.getLoopPointsSeconds().getStart()),
  1400. std::make_tuple (&endMarker, dataModel.getLoopPointsSeconds().getEnd()) })
  1401. {
  1402. auto ptr = std::get<0> (tup);
  1403. auto time = std::get<1> (tup);
  1404. ptr->setSize (halfMarkerWidth * 2, getHeight());
  1405. ptr->setTopLeftPosition (roundToInt (timeToXPosition (time) - halfMarkerWidth), 0);
  1406. }
  1407. }
  1408. DataModel dataModel;
  1409. VisibleRangeDataModel visibleRange;
  1410. Range<double> loopPointsOnMouseDown;
  1411. LoopPointMarker beginMarker, endMarker;
  1412. UndoManager* undoManager;
  1413. };
  1414. //==============================================================================
  1415. class PlaybackPositionOverlay : public Component,
  1416. private Timer,
  1417. private VisibleRangeDataModel::Listener
  1418. {
  1419. public:
  1420. using Provider = std::function<std::vector<float>()>;
  1421. PlaybackPositionOverlay (const VisibleRangeDataModel& model,
  1422. Provider providerIn)
  1423. : visibleRange (model),
  1424. provider (std::move (providerIn))
  1425. {
  1426. visibleRange.addListener (*this);
  1427. startTimer (16);
  1428. }
  1429. private:
  1430. void paint (Graphics& g) override
  1431. {
  1432. g.setColour (Colours::red);
  1433. for (auto position : provider())
  1434. {
  1435. g.drawVerticalLine (roundToInt (timeToXPosition (position)), 0.0f, (float) getHeight());
  1436. }
  1437. }
  1438. void timerCallback() override
  1439. {
  1440. repaint();
  1441. }
  1442. void visibleRangeChanged (Range<double>) override
  1443. {
  1444. repaint();
  1445. }
  1446. double timeToXPosition (double time) const
  1447. {
  1448. return (time - visibleRange.getVisibleRange().getStart()) * getWidth()
  1449. / visibleRange.getVisibleRange().getLength();
  1450. }
  1451. VisibleRangeDataModel visibleRange;
  1452. Provider provider;
  1453. };
  1454. //==============================================================================
  1455. class WaveformView : public Component,
  1456. private ChangeListener,
  1457. private DataModel::Listener,
  1458. private VisibleRangeDataModel::Listener
  1459. {
  1460. public:
  1461. WaveformView (const DataModel& model,
  1462. const VisibleRangeDataModel& vr)
  1463. : dataModel (model),
  1464. visibleRange (vr),
  1465. thumbnailCache (4),
  1466. thumbnail (4, dataModel.getAudioFormatManager(), thumbnailCache)
  1467. {
  1468. dataModel .addListener (*this);
  1469. visibleRange.addListener (*this);
  1470. thumbnail .addChangeListener (this);
  1471. }
  1472. private:
  1473. void paint (Graphics& g) override
  1474. {
  1475. // Draw the waveforms
  1476. g.fillAll (Colours::black);
  1477. auto numChannels = thumbnail.getNumChannels();
  1478. if (numChannels == 0)
  1479. {
  1480. g.setColour (Colours::white);
  1481. g.drawFittedText ("No File Loaded", getLocalBounds(), Justification::centred, 1);
  1482. return;
  1483. }
  1484. auto bounds = getLocalBounds();
  1485. auto channelHeight = bounds.getHeight() / numChannels;
  1486. for (auto i = 0; i != numChannels; ++i)
  1487. {
  1488. drawChannel (g, i, bounds.removeFromTop (channelHeight));
  1489. }
  1490. }
  1491. void changeListenerCallback (ChangeBroadcaster* source) override
  1492. {
  1493. if (source == &thumbnail)
  1494. repaint();
  1495. }
  1496. void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory> value) override
  1497. {
  1498. if (value != nullptr)
  1499. {
  1500. if (auto reader = value->make (dataModel.getAudioFormatManager()))
  1501. {
  1502. thumbnail.setReader (reader.release(), currentHashCode);
  1503. currentHashCode += 1;
  1504. return;
  1505. }
  1506. }
  1507. thumbnail.clear();
  1508. }
  1509. void visibleRangeChanged (Range<double>) override
  1510. {
  1511. repaint();
  1512. }
  1513. void drawChannel (Graphics& g, int channel, Rectangle<int> bounds)
  1514. {
  1515. g.setGradientFill (ColourGradient (Colours::lightblue,
  1516. bounds.getTopLeft().toFloat(),
  1517. Colours::darkgrey,
  1518. bounds.getBottomLeft().toFloat(),
  1519. false));
  1520. thumbnail.drawChannel (g,
  1521. bounds,
  1522. visibleRange.getVisibleRange().getStart(),
  1523. visibleRange.getVisibleRange().getEnd(),
  1524. channel,
  1525. 1.0f);
  1526. }
  1527. DataModel dataModel;
  1528. VisibleRangeDataModel visibleRange;
  1529. AudioThumbnailCache thumbnailCache;
  1530. AudioThumbnail thumbnail;
  1531. int64 currentHashCode = 0;
  1532. };
  1533. //==============================================================================
  1534. class WaveformEditor : public Component,
  1535. private DataModel::Listener
  1536. {
  1537. public:
  1538. WaveformEditor (const DataModel& model,
  1539. PlaybackPositionOverlay::Provider provider,
  1540. UndoManager& undoManager)
  1541. : dataModel (model),
  1542. waveformView (model, visibleRange),
  1543. playbackOverlay (visibleRange, move (provider)),
  1544. loopPoints (dataModel, visibleRange, undoManager),
  1545. ruler (visibleRange)
  1546. {
  1547. dataModel.addListener (*this);
  1548. addAndMakeVisible (waveformView);
  1549. addAndMakeVisible (playbackOverlay);
  1550. addChildComponent (loopPoints);
  1551. loopPoints.setAlwaysOnTop (true);
  1552. waveformView.toBack();
  1553. addAndMakeVisible (ruler);
  1554. }
  1555. private:
  1556. void resized() override
  1557. {
  1558. auto bounds = getLocalBounds();
  1559. ruler .setBounds (bounds.removeFromTop (25));
  1560. waveformView .setBounds (bounds);
  1561. playbackOverlay.setBounds (bounds);
  1562. loopPoints .setBounds (bounds);
  1563. }
  1564. void loopModeChanged (LoopMode value) override
  1565. {
  1566. loopPoints.setVisible (value != LoopMode::none);
  1567. }
  1568. void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory>) override
  1569. {
  1570. auto lengthInSeconds = dataModel.getSampleLengthSeconds();
  1571. visibleRange.setTotalRange (Range<double> (0, lengthInSeconds), nullptr);
  1572. visibleRange.setVisibleRange (Range<double> (0, lengthInSeconds), nullptr);
  1573. }
  1574. DataModel dataModel;
  1575. VisibleRangeDataModel visibleRange;
  1576. WaveformView waveformView;
  1577. PlaybackPositionOverlay playbackOverlay;
  1578. LoopPointsOverlay loopPoints;
  1579. Ruler ruler;
  1580. };
  1581. //==============================================================================
  1582. class MainSamplerView : public Component,
  1583. private DataModel::Listener,
  1584. private ChangeListener
  1585. {
  1586. public:
  1587. MainSamplerView (const DataModel& model,
  1588. PlaybackPositionOverlay::Provider provider,
  1589. UndoManager& um)
  1590. : dataModel (model),
  1591. waveformEditor (dataModel, move (provider), um),
  1592. undoManager (um)
  1593. {
  1594. dataModel.addListener (*this);
  1595. addAndMakeVisible (waveformEditor);
  1596. addAndMakeVisible (loadNewSampleButton);
  1597. addAndMakeVisible (undoButton);
  1598. addAndMakeVisible (redoButton);
  1599. auto setReader = [this] (const FileChooser& fc)
  1600. {
  1601. const auto result = fc.getResult();
  1602. if (result != File())
  1603. {
  1604. undoManager.beginNewTransaction();
  1605. auto readerFactory = new FileAudioFormatReaderFactory (result);
  1606. dataModel.setSampleReader (std::unique_ptr<AudioFormatReaderFactory> (readerFactory),
  1607. &undoManager);
  1608. }
  1609. };
  1610. loadNewSampleButton.onClick = [this, setReader]
  1611. {
  1612. fileChooser.launchAsync (FileBrowserComponent::FileChooserFlags::openMode |
  1613. FileBrowserComponent::FileChooserFlags::canSelectFiles,
  1614. setReader);
  1615. };
  1616. addAndMakeVisible (centreFrequency);
  1617. centreFrequency.onValueChange = [this]
  1618. {
  1619. undoManager.beginNewTransaction();
  1620. dataModel.setCentreFrequencyHz (centreFrequency.getValue(),
  1621. centreFrequency.isMouseButtonDown() ? nullptr : &undoManager);
  1622. };
  1623. centreFrequency.setRange (20, 20000, 1);
  1624. centreFrequency.setSliderStyle (Slider::SliderStyle::IncDecButtons);
  1625. centreFrequency.setIncDecButtonsMode (Slider::IncDecButtonMode::incDecButtonsDraggable_Vertical);
  1626. auto radioGroupId = 1;
  1627. for (auto buttonPtr : { &loopKindNone, &loopKindForward, &loopKindPingpong })
  1628. {
  1629. addAndMakeVisible (buttonPtr);
  1630. buttonPtr->setRadioGroupId (radioGroupId, dontSendNotification);
  1631. buttonPtr->setClickingTogglesState (true);
  1632. }
  1633. loopKindNone.onClick = [this]
  1634. {
  1635. if (loopKindNone.getToggleState())
  1636. {
  1637. undoManager.beginNewTransaction();
  1638. dataModel.setLoopMode (LoopMode::none, &undoManager);
  1639. }
  1640. };
  1641. loopKindForward.onClick = [this]
  1642. {
  1643. if (loopKindForward.getToggleState())
  1644. {
  1645. undoManager.beginNewTransaction();
  1646. dataModel.setLoopMode (LoopMode::forward, &undoManager);
  1647. }
  1648. };
  1649. loopKindPingpong.onClick = [this]
  1650. {
  1651. if (loopKindPingpong.getToggleState())
  1652. {
  1653. undoManager.beginNewTransaction();
  1654. dataModel.setLoopMode (LoopMode::pingpong, &undoManager);
  1655. }
  1656. };
  1657. undoButton.onClick = [this] { undoManager.undo(); };
  1658. redoButton.onClick = [this] { undoManager.redo(); };
  1659. addAndMakeVisible (centreFrequencyLabel);
  1660. addAndMakeVisible (loopKindLabel);
  1661. changeListenerCallback (&undoManager);
  1662. undoManager.addChangeListener (this);
  1663. }
  1664. ~MainSamplerView() override
  1665. {
  1666. undoManager.removeChangeListener (this);
  1667. }
  1668. private:
  1669. void changeListenerCallback (ChangeBroadcaster* source) override
  1670. {
  1671. if (source == &undoManager)
  1672. {
  1673. undoButton.setEnabled (undoManager.canUndo());
  1674. redoButton.setEnabled (undoManager.canRedo());
  1675. }
  1676. }
  1677. void resized() override
  1678. {
  1679. auto bounds = getLocalBounds();
  1680. auto topBar = bounds.removeFromTop (50);
  1681. auto padding = 4;
  1682. loadNewSampleButton .setBounds (topBar.removeFromRight (100).reduced (padding));
  1683. redoButton .setBounds (topBar.removeFromRight (100).reduced (padding));
  1684. undoButton .setBounds (topBar.removeFromRight (100).reduced (padding));
  1685. centreFrequencyLabel.setBounds (topBar.removeFromLeft (100).reduced (padding));
  1686. centreFrequency .setBounds (topBar.removeFromLeft (100).reduced (padding));
  1687. auto bottomBar = bounds.removeFromBottom (50);
  1688. loopKindLabel .setBounds (bottomBar.removeFromLeft (100).reduced (padding));
  1689. loopKindNone .setBounds (bottomBar.removeFromLeft (80) .reduced (padding));
  1690. loopKindForward .setBounds (bottomBar.removeFromLeft (80) .reduced (padding));
  1691. loopKindPingpong.setBounds (bottomBar.removeFromLeft (80) .reduced (padding));
  1692. waveformEditor.setBounds (bounds);
  1693. }
  1694. void loopModeChanged (LoopMode value) override
  1695. {
  1696. switch (value)
  1697. {
  1698. case LoopMode::none:
  1699. loopKindNone.setToggleState (true, dontSendNotification);
  1700. break;
  1701. case LoopMode::forward:
  1702. loopKindForward.setToggleState (true, dontSendNotification);
  1703. break;
  1704. case LoopMode::pingpong:
  1705. loopKindPingpong.setToggleState (true, dontSendNotification);
  1706. break;
  1707. default:
  1708. break;
  1709. }
  1710. }
  1711. void centreFrequencyHzChanged (double value) override
  1712. {
  1713. centreFrequency.setValue (value, dontSendNotification);
  1714. }
  1715. DataModel dataModel;
  1716. WaveformEditor waveformEditor;
  1717. TextButton loadNewSampleButton { "Load New Sample" };
  1718. TextButton undoButton { "Undo" };
  1719. TextButton redoButton { "Redo" };
  1720. Slider centreFrequency;
  1721. TextButton loopKindNone { "None" },
  1722. loopKindForward { "Forward" },
  1723. loopKindPingpong { "Ping Pong" };
  1724. Label centreFrequencyLabel { {}, "Sample Centre Freq / Hz" },
  1725. loopKindLabel { {}, "Looping Mode" };
  1726. FileChooser fileChooser { "Select a file to load...", File(),
  1727. dataModel.getAudioFormatManager().getWildcardForAllFormats() };
  1728. UndoManager& undoManager;
  1729. };
  1730. //==============================================================================
  1731. struct ProcessorState
  1732. {
  1733. int synthVoices;
  1734. bool legacyModeEnabled;
  1735. Range<int> legacyChannels;
  1736. int legacyPitchbendRange;
  1737. bool voiceStealingEnabled;
  1738. MPEZoneLayout mpeZoneLayout;
  1739. std::unique_ptr<AudioFormatReaderFactory> readerFactory;
  1740. Range<double> loopPointsSeconds;
  1741. double centreFrequencyHz;
  1742. LoopMode loopMode;
  1743. };
  1744. //==============================================================================
  1745. class SamplerAudioProcessor : public AudioProcessor
  1746. {
  1747. public:
  1748. SamplerAudioProcessor()
  1749. : AudioProcessor (BusesProperties().withOutput ("Output", AudioChannelSet::stereo(), true))
  1750. {
  1751. if (auto inputStream = createAssetInputStream ("cello.wav"))
  1752. {
  1753. inputStream->readIntoMemoryBlock (mb);
  1754. readerFactory.reset (new MemoryAudioFormatReaderFactory (mb.getData(), mb.getSize()));
  1755. }
  1756. // Set up initial sample, which we load from a binary resource
  1757. AudioFormatManager manager;
  1758. manager.registerBasicFormats();
  1759. auto reader = readerFactory->make (manager);
  1760. jassert (reader != nullptr); // Failed to load resource!
  1761. auto sound = samplerSound;
  1762. auto sample = std::unique_ptr<Sample> (new Sample (*reader, 10.0));
  1763. auto lengthInSeconds = sample->getLength() / sample->getSampleRate();
  1764. sound->setLoopPointsInSeconds ({lengthInSeconds * 0.1, lengthInSeconds * 0.9 });
  1765. sound->setSample (move (sample));
  1766. // Start with the max number of voices
  1767. for (auto i = 0; i != maxVoices; ++i)
  1768. synthesiser.addVoice (new MPESamplerVoice (sound));
  1769. }
  1770. void prepareToPlay (double sampleRate, int) override
  1771. {
  1772. synthesiser.setCurrentPlaybackSampleRate (sampleRate);
  1773. }
  1774. void releaseResources() override {}
  1775. bool isBusesLayoutSupported (const BusesLayout& layouts) const override
  1776. {
  1777. return layouts.getMainOutputChannelSet() == AudioChannelSet::mono()
  1778. || layouts.getMainOutputChannelSet() == AudioChannelSet::stereo();
  1779. }
  1780. //==============================================================================
  1781. AudioProcessorEditor* createEditor() override
  1782. {
  1783. // This function will be called from the message thread. We lock the command
  1784. // queue to ensure that no messages are processed for the duration of this
  1785. // call.
  1786. SpinLock::ScopedLockType lock (commandQueueMutex);
  1787. ProcessorState state;
  1788. state.synthVoices = synthesiser.getNumVoices();
  1789. state.legacyModeEnabled = synthesiser.isLegacyModeEnabled();
  1790. state.legacyChannels = synthesiser.getLegacyModeChannelRange();
  1791. state.legacyPitchbendRange = synthesiser.getLegacyModePitchbendRange();
  1792. state.voiceStealingEnabled = synthesiser.isVoiceStealingEnabled();
  1793. state.mpeZoneLayout = synthesiser.getZoneLayout();
  1794. state.readerFactory = readerFactory == nullptr ? nullptr : readerFactory->clone();
  1795. auto sound = samplerSound;
  1796. state.loopPointsSeconds = sound->getLoopPointsInSeconds();
  1797. state.centreFrequencyHz = sound->getCentreFrequencyInHz();
  1798. state.loopMode = sound->getLoopMode();
  1799. return new SamplerAudioProcessorEditor (*this, std::move (state));
  1800. }
  1801. bool hasEditor() const override { return true; }
  1802. //==============================================================================
  1803. const String getName() const override { return "SamplerPlugin"; }
  1804. bool acceptsMidi() const override { return true; }
  1805. bool producesMidi() const override { return false; }
  1806. bool isMidiEffect() const override { return false; }
  1807. double getTailLengthSeconds() const override { return 0.0; }
  1808. //==============================================================================
  1809. int getNumPrograms() override { return 1; }
  1810. int getCurrentProgram() override { return 0; }
  1811. void setCurrentProgram (int) override {}
  1812. const String getProgramName (int) override { return {}; }
  1813. void changeProgramName (int, const String&) override {}
  1814. //==============================================================================
  1815. void getStateInformation (MemoryBlock&) override {}
  1816. void setStateInformation (const void*, int) override {}
  1817. //==============================================================================
  1818. void processBlock (AudioBuffer<float>& buffer, MidiBuffer& midi) override
  1819. {
  1820. process (buffer, midi);
  1821. }
  1822. void processBlock (AudioBuffer<double>& buffer, MidiBuffer& midi) override
  1823. {
  1824. process (buffer, midi);
  1825. }
  1826. // These should be called from the GUI thread, and will block until the
  1827. // command buffer has enough room to accept a command.
  1828. void setSample (std::unique_ptr<AudioFormatReaderFactory> fact, AudioFormatManager& formatManager)
  1829. {
  1830. class SetSampleCommand
  1831. {
  1832. public:
  1833. SetSampleCommand (std::unique_ptr<AudioFormatReaderFactory> r,
  1834. std::unique_ptr<Sample> sampleIn,
  1835. std::vector<std::unique_ptr<MPESamplerVoice>> newVoicesIn)
  1836. : readerFactory (std::move (r)),
  1837. sample (std::move (sampleIn)),
  1838. newVoices (std::move (newVoicesIn))
  1839. {}
  1840. void operator() (SamplerAudioProcessor& proc)
  1841. {
  1842. proc.readerFactory = move (readerFactory);
  1843. auto sound = proc.samplerSound;
  1844. sound->setSample (std::move (sample));
  1845. auto numberOfVoices = proc.synthesiser.getNumVoices();
  1846. proc.synthesiser.clearVoices();
  1847. for (auto it = begin (newVoices); proc.synthesiser.getNumVoices() < numberOfVoices; ++it)
  1848. {
  1849. proc.synthesiser.addVoice (it->release());
  1850. }
  1851. }
  1852. private:
  1853. std::unique_ptr<AudioFormatReaderFactory> readerFactory;
  1854. std::unique_ptr<Sample> sample;
  1855. std::vector<std::unique_ptr<MPESamplerVoice>> newVoices;
  1856. };
  1857. // Note that all allocation happens here, on the main message thread. Then,
  1858. // we transfer ownership across to the audio thread.
  1859. auto loadedSamplerSound = samplerSound;
  1860. std::vector<std::unique_ptr<MPESamplerVoice>> newSamplerVoices;
  1861. newSamplerVoices.reserve (maxVoices);
  1862. for (auto i = 0; i != maxVoices; ++i)
  1863. newSamplerVoices.emplace_back (new MPESamplerVoice (loadedSamplerSound));
  1864. if (fact == nullptr)
  1865. {
  1866. commands.push (SetSampleCommand (move (fact),
  1867. nullptr,
  1868. move (newSamplerVoices)));
  1869. }
  1870. else if (auto reader = fact->make (formatManager))
  1871. {
  1872. commands.push (SetSampleCommand (move (fact),
  1873. std::unique_ptr<Sample> (new Sample (*reader, 10.0)),
  1874. move (newSamplerVoices)));
  1875. }
  1876. }
  1877. void setCentreFrequency (double centreFrequency)
  1878. {
  1879. commands.push ([centreFrequency] (SamplerAudioProcessor& proc)
  1880. {
  1881. auto loaded = proc.samplerSound;
  1882. if (loaded != nullptr)
  1883. loaded->setCentreFrequencyInHz (centreFrequency);
  1884. });
  1885. }
  1886. void setLoopMode (LoopMode loopMode)
  1887. {
  1888. commands.push ([loopMode] (SamplerAudioProcessor& proc)
  1889. {
  1890. auto loaded = proc.samplerSound;
  1891. if (loaded != nullptr)
  1892. loaded->setLoopMode (loopMode);
  1893. });
  1894. }
  1895. void setLoopPoints (Range<double> loopPoints)
  1896. {
  1897. commands.push ([loopPoints] (SamplerAudioProcessor& proc)
  1898. {
  1899. auto loaded = proc.samplerSound;
  1900. if (loaded != nullptr)
  1901. loaded->setLoopPointsInSeconds (loopPoints);
  1902. });
  1903. }
  1904. void setMPEZoneLayout (MPEZoneLayout layout)
  1905. {
  1906. commands.push ([layout] (SamplerAudioProcessor& proc)
  1907. {
  1908. // setZoneLayout will lock internally, so we don't care too much about
  1909. // ensuring that the layout doesn't get copied or destroyed on the
  1910. // audio thread. If the audio glitches while updating midi settings
  1911. // it doesn't matter too much.
  1912. proc.synthesiser.setZoneLayout (layout);
  1913. });
  1914. }
  1915. void setLegacyModeEnabled (int pitchbendRange, Range<int> channelRange)
  1916. {
  1917. commands.push ([pitchbendRange, channelRange] (SamplerAudioProcessor& proc)
  1918. {
  1919. proc.synthesiser.enableLegacyMode (pitchbendRange, channelRange);
  1920. });
  1921. }
  1922. void setVoiceStealingEnabled (bool voiceStealingEnabled)
  1923. {
  1924. commands.push ([voiceStealingEnabled] (SamplerAudioProcessor& proc)
  1925. {
  1926. proc.synthesiser.setVoiceStealingEnabled (voiceStealingEnabled);
  1927. });
  1928. }
  1929. void setNumberOfVoices (int numberOfVoices)
  1930. {
  1931. // We don't want to call 'new' on the audio thread. Normally, we'd
  1932. // construct things here, on the GUI thread, and then move them into the
  1933. // command lambda. Unfortunately, C++11 doesn't have extended lambda
  1934. // capture, so we use a custom struct instead.
  1935. class SetNumVoicesCommand
  1936. {
  1937. public:
  1938. SetNumVoicesCommand (std::vector<std::unique_ptr<MPESamplerVoice>> newVoicesIn)
  1939. : newVoices (std::move (newVoicesIn))
  1940. {}
  1941. void operator() (SamplerAudioProcessor& proc)
  1942. {
  1943. if ((int) newVoices.size() < proc.synthesiser.getNumVoices())
  1944. proc.synthesiser.reduceNumVoices (int (newVoices.size()));
  1945. else
  1946. for (auto it = begin (newVoices); (size_t) proc.synthesiser.getNumVoices() < newVoices.size(); ++it)
  1947. proc.synthesiser.addVoice (it->release());
  1948. }
  1949. private:
  1950. std::vector<std::unique_ptr<MPESamplerVoice>> newVoices;
  1951. };
  1952. numberOfVoices = std::min (maxVoices, numberOfVoices);
  1953. auto loadedSamplerSound = samplerSound;
  1954. std::vector<std::unique_ptr<MPESamplerVoice>> newSamplerVoices;
  1955. newSamplerVoices.reserve ((size_t) numberOfVoices);
  1956. for (auto i = 0; i != numberOfVoices; ++i)
  1957. newSamplerVoices.emplace_back (new MPESamplerVoice (loadedSamplerSound));
  1958. commands.push (SetNumVoicesCommand (move (newSamplerVoices)));
  1959. }
  1960. // These accessors are just for an 'overview' and won't give the exact
  1961. // state of the audio engine at a particular point in time.
  1962. // If you call getNumVoices(), get the result '10', and then call
  1963. // getPlaybackPosiiton(9), there's a chance the audio engine will have
  1964. // been updated to remove some voices in the meantime, so the returned
  1965. // value won't correspond to an existing voice.
  1966. int getNumVoices() const { return synthesiser.getNumVoices(); }
  1967. float getPlaybackPosition (int voice) const { return playbackPositions.at ((size_t) voice); }
  1968. private:
  1969. //==============================================================================
  1970. class SamplerAudioProcessorEditor : public AudioProcessorEditor,
  1971. public FileDragAndDropTarget,
  1972. private DataModel::Listener,
  1973. private MPESettingsDataModel::Listener
  1974. {
  1975. public:
  1976. SamplerAudioProcessorEditor (SamplerAudioProcessor& p, ProcessorState state)
  1977. : AudioProcessorEditor (&p),
  1978. samplerAudioProcessor (p),
  1979. mainSamplerView (dataModel,
  1980. [&p]
  1981. {
  1982. std::vector<float> ret;
  1983. auto voices = p.getNumVoices();
  1984. ret.reserve ((size_t) voices);
  1985. for (auto i = 0; i != voices; ++i)
  1986. ret.emplace_back (p.getPlaybackPosition (i));
  1987. return ret;
  1988. },
  1989. undoManager)
  1990. {
  1991. dataModel.addListener (*this);
  1992. mpeSettings.addListener (*this);
  1993. formatManager.registerBasicFormats();
  1994. addAndMakeVisible (tabbedComponent);
  1995. auto lookFeel = dynamic_cast<LookAndFeel_V4*> (&getLookAndFeel());
  1996. auto bg = lookFeel->getCurrentColourScheme()
  1997. .getUIColour (LookAndFeel_V4::ColourScheme::UIColour::widgetBackground);
  1998. tabbedComponent.addTab ("Sample Editor", bg, &mainSamplerView, false);
  1999. tabbedComponent.addTab ("MPE Settings", bg, &settingsComponent, false);
  2000. mpeSettings.setSynthVoices (state.synthVoices, nullptr);
  2001. mpeSettings.setLegacyModeEnabled (state.legacyModeEnabled, nullptr);
  2002. mpeSettings.setLegacyFirstChannel (state.legacyChannels.getStart(), nullptr);
  2003. mpeSettings.setLegacyLastChannel (state.legacyChannels.getEnd(), nullptr);
  2004. mpeSettings.setLegacyPitchbendRange (state.legacyPitchbendRange, nullptr);
  2005. mpeSettings.setVoiceStealingEnabled (state.voiceStealingEnabled, nullptr);
  2006. mpeSettings.setMPEZoneLayout (state.mpeZoneLayout, nullptr);
  2007. dataModel.setSampleReader (move (state.readerFactory), nullptr);
  2008. dataModel.setLoopPointsSeconds (state.loopPointsSeconds, nullptr);
  2009. dataModel.setCentreFrequencyHz (state.centreFrequencyHz, nullptr);
  2010. dataModel.setLoopMode (state.loopMode, nullptr);
  2011. // Make sure that before the constructor has finished, you've set the
  2012. // editor's size to whatever you need it to be.
  2013. setResizable (true, true);
  2014. setResizeLimits (640, 480, 2560, 1440);
  2015. setSize (640, 480);
  2016. }
  2017. private:
  2018. void resized() override
  2019. {
  2020. tabbedComponent.setBounds (getLocalBounds());
  2021. }
  2022. bool keyPressed (const KeyPress& key) override
  2023. {
  2024. if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  2025. {
  2026. undoManager.undo();
  2027. return true;
  2028. }
  2029. if (key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  2030. {
  2031. undoManager.redo();
  2032. return true;
  2033. }
  2034. return Component::keyPressed (key);
  2035. }
  2036. bool isInterestedInFileDrag (const StringArray& files) override
  2037. {
  2038. WildcardFileFilter filter (formatManager.getWildcardForAllFormats(), {}, "Known Audio Formats");
  2039. return files.size() == 1 && filter.isFileSuitable (files[0]);
  2040. }
  2041. void filesDropped (const StringArray& files, int, int) override
  2042. {
  2043. jassert (files.size() == 1);
  2044. undoManager.beginNewTransaction();
  2045. auto r = new FileAudioFormatReaderFactory (files[0]);
  2046. dataModel.setSampleReader (std::unique_ptr<AudioFormatReaderFactory> (r),
  2047. &undoManager);
  2048. }
  2049. void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory> value) override
  2050. {
  2051. samplerAudioProcessor.setSample (value == nullptr ? nullptr : value->clone(),
  2052. dataModel.getAudioFormatManager());
  2053. }
  2054. void centreFrequencyHzChanged (double value) override
  2055. {
  2056. samplerAudioProcessor.setCentreFrequency (value);
  2057. }
  2058. void loopPointsSecondsChanged (Range<double> value) override
  2059. {
  2060. samplerAudioProcessor.setLoopPoints (value);
  2061. }
  2062. void loopModeChanged (LoopMode value) override
  2063. {
  2064. samplerAudioProcessor.setLoopMode (value);
  2065. }
  2066. void synthVoicesChanged (int value) override
  2067. {
  2068. samplerAudioProcessor.setNumberOfVoices (value);
  2069. }
  2070. void voiceStealingEnabledChanged (bool value) override
  2071. {
  2072. samplerAudioProcessor.setVoiceStealingEnabled (value);
  2073. }
  2074. void legacyModeEnabledChanged (bool value) override
  2075. {
  2076. if (value)
  2077. setProcessorLegacyMode();
  2078. else
  2079. setProcessorMPEMode();
  2080. }
  2081. void mpeZoneLayoutChanged (const MPEZoneLayout&) override
  2082. {
  2083. setProcessorMPEMode();
  2084. }
  2085. void legacyFirstChannelChanged (int) override
  2086. {
  2087. setProcessorLegacyMode();
  2088. }
  2089. void legacyLastChannelChanged (int) override
  2090. {
  2091. setProcessorLegacyMode();
  2092. }
  2093. void legacyPitchbendRangeChanged (int) override
  2094. {
  2095. setProcessorLegacyMode();
  2096. }
  2097. void setProcessorLegacyMode()
  2098. {
  2099. samplerAudioProcessor.setLegacyModeEnabled (mpeSettings.getLegacyPitchbendRange(),
  2100. Range<int> (mpeSettings.getLegacyFirstChannel(),
  2101. mpeSettings.getLegacyLastChannel()));
  2102. }
  2103. void setProcessorMPEMode()
  2104. {
  2105. samplerAudioProcessor.setMPEZoneLayout (mpeSettings.getMPEZoneLayout());
  2106. }
  2107. SamplerAudioProcessor& samplerAudioProcessor;
  2108. AudioFormatManager formatManager;
  2109. DataModel dataModel { formatManager };
  2110. UndoManager undoManager;
  2111. MPESettingsDataModel mpeSettings { dataModel.mpeSettings() };
  2112. TabbedComponent tabbedComponent { TabbedButtonBar::Orientation::TabsAtTop };
  2113. MPESettingsComponent settingsComponent { dataModel.mpeSettings(), undoManager };
  2114. MainSamplerView mainSamplerView;
  2115. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SamplerAudioProcessorEditor)
  2116. };
  2117. //==============================================================================
  2118. template <typename Element>
  2119. void process (AudioBuffer<Element>& buffer, MidiBuffer& midiMessages)
  2120. {
  2121. // Try to acquire a lock on the command queue.
  2122. // If we were successful, we pop all pending commands off the queue and
  2123. // apply them to the processor.
  2124. // If we weren't able to acquire the lock, it's because someone called
  2125. // createEditor, which requires that the processor data model stays in
  2126. // a valid state for the duration of the call.
  2127. const GenericScopedTryLock<SpinLock> lock (commandQueueMutex);
  2128. if (lock.isLocked())
  2129. commands.call (*this);
  2130. synthesiser.renderNextBlock (buffer, midiMessages, 0, buffer.getNumSamples());
  2131. auto loadedSamplerSound = samplerSound;
  2132. if (loadedSamplerSound->getSample() == nullptr)
  2133. return;
  2134. auto numVoices = synthesiser.getNumVoices();
  2135. // Update the current playback positions
  2136. for (auto i = 0; i < maxVoices; ++i)
  2137. {
  2138. auto* voicePtr = dynamic_cast<MPESamplerVoice*> (synthesiser.getVoice (i));
  2139. if (i < numVoices && voicePtr != nullptr)
  2140. playbackPositions[(size_t) i] = static_cast<float> (voicePtr->getCurrentSamplePosition() / loadedSamplerSound->getSample()->getSampleRate());
  2141. else
  2142. playbackPositions[(size_t) i] = 0.0f;
  2143. }
  2144. }
  2145. CommandFifo<SamplerAudioProcessor> commands;
  2146. MemoryBlock mb;
  2147. std::unique_ptr<AudioFormatReaderFactory> readerFactory;
  2148. std::shared_ptr<MPESamplerSound> samplerSound = std::make_shared<MPESamplerSound>();
  2149. MPESynthesiser synthesiser;
  2150. // This mutex is used to ensure we don't modify the processor state during
  2151. // a call to createEditor, which would cause the UI to become desynched
  2152. // with the real state of the processor.
  2153. SpinLock commandQueueMutex;
  2154. static constexpr auto maxVoices { 20 };
  2155. // This is used for visualising the current playback position of each voice.
  2156. std::array<std::atomic<float>, maxVoices> playbackPositions;
  2157. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SamplerAudioProcessor)
  2158. };
  2159. const int SamplerAudioProcessor::maxVoices;