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.

2635 lines
90KB

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