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.

2636 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. type: AudioProcessor
  30. mainClass: SamplerAudioProcessor
  31. useLocalCopy: 1
  32. END_JUCE_PIP_METADATA
  33. *******************************************************************************/
  34. #pragma once
  35. #include "../Assets/DemoUtilities.h"
  36. #include <array>
  37. #include <atomic>
  38. #include <memory>
  39. #include <vector>
  40. #include <tuple>
  41. #include <iomanip>
  42. #include <sstream>
  43. #include <functional>
  44. #include <mutex>
  45. namespace IDs
  46. {
  47. #define DECLARE_ID(name) const juce::Identifier name (#name);
  48. DECLARE_ID (DATA_MODEL)
  49. DECLARE_ID (sampleReader)
  50. DECLARE_ID (centreFrequencyHz)
  51. DECLARE_ID (loopMode)
  52. DECLARE_ID (loopPointsSeconds)
  53. DECLARE_ID (MPE_SETTINGS)
  54. DECLARE_ID (synthVoices)
  55. DECLARE_ID (voiceStealingEnabled)
  56. DECLARE_ID (legacyModeEnabled)
  57. DECLARE_ID (mpeZoneLayout)
  58. DECLARE_ID (legacyFirstChannel)
  59. DECLARE_ID (legacyLastChannel)
  60. DECLARE_ID (legacyPitchbendRange)
  61. DECLARE_ID (VISIBLE_RANGE)
  62. DECLARE_ID (totalRange)
  63. DECLARE_ID (visibleRange)
  64. #undef DECLARE_ID
  65. } // namespace IDs
  66. enum class LoopMode
  67. {
  68. none,
  69. forward,
  70. pingpong
  71. };
  72. template <typename Movable>
  73. class MoveOnlyFifo final
  74. {
  75. public:
  76. explicit MoveOnlyFifo (int size)
  77. : buffer (size),
  78. abstractFifo (size)
  79. {}
  80. MoveOnlyFifo()
  81. : MoveOnlyFifo (1024)
  82. {}
  83. template <typename Convertible>
  84. Convertible push (Convertible item) noexcept
  85. {
  86. auto writer = abstractFifo.write (1);
  87. if (writer.blockSize1 == 1)
  88. {
  89. buffer[writer.startIndex1] = move (item);
  90. item = {};
  91. }
  92. else if (writer.blockSize2 == 1)
  93. {
  94. buffer[writer.startIndex2] = move (item);
  95. item = {};
  96. }
  97. return item;
  98. }
  99. Movable pop() noexcept
  100. {
  101. auto reader = abstractFifo.read (1);
  102. if (reader.blockSize1 == 1)
  103. return move (buffer[reader.startIndex1]);
  104. if (reader.blockSize2 == 1)
  105. return move (buffer[reader.startIndex2]);
  106. return {};
  107. }
  108. private:
  109. std::vector<Movable> buffer;
  110. AbstractFifo abstractFifo;
  111. };
  112. //==============================================================================
  113. // Represents the constant parts of an audio sample: its name, sample rate,
  114. // length, and the audio sample data itself.
  115. // Samples might be pretty big, so we'll keep shared_ptrs to them most of the
  116. // time, to reduce duplication and copying.
  117. class Sample final
  118. {
  119. public:
  120. Sample (AudioFormatReader& source, double maxSampleLengthSecs)
  121. : sourceSampleRate (source.sampleRate),
  122. length (jmin (int (source.lengthInSamples),
  123. int (maxSampleLengthSecs * sourceSampleRate))),
  124. data (jmin (2, int (source.numChannels)), length + 4)
  125. {
  126. if (length == 0)
  127. throw std::runtime_error ("Unable to load sample");
  128. source.read (&data, 0, length + 4, 0, true, true);
  129. }
  130. double getSampleRate() const { return sourceSampleRate; }
  131. int getLength() const { return length; }
  132. const AudioSampleBuffer& getBuffer() const { return data; }
  133. private:
  134. double sourceSampleRate;
  135. int length;
  136. AudioSampleBuffer data;
  137. };
  138. //==============================================================================
  139. // A class which contains all the information related to sample-playback, such
  140. // as sample data, loop points, and loop kind.
  141. // It is expected that multiple sampler voices will maintain pointers to a
  142. // single instance of this class, to avoid redundant duplication of sample
  143. // data in memory.
  144. class MPESamplerSound final
  145. {
  146. public:
  147. void setSample (std::unique_ptr<Sample> value)
  148. {
  149. sample = move (value);
  150. setLoopPointsInSeconds (loopPoints);
  151. }
  152. Sample* getSample() const
  153. {
  154. return sample.get();
  155. }
  156. void setLoopPointsInSeconds (Range<double> value)
  157. {
  158. loopPoints = sample == nullptr ? value
  159. : Range<double> (0, sample->getLength() / sample->getSampleRate())
  160. .constrainRange (value);
  161. }
  162. Range<double> getLoopPointsInSeconds() const
  163. {
  164. return loopPoints;
  165. }
  166. void setCentreFrequencyInHz (double centre)
  167. {
  168. centreFrequencyInHz = centre;
  169. }
  170. double getCentreFrequencyInHz() const
  171. {
  172. return centreFrequencyInHz;
  173. }
  174. void setLoopMode (LoopMode type)
  175. {
  176. loopMode = type;
  177. }
  178. LoopMode getLoopMode() const
  179. {
  180. return loopMode;
  181. }
  182. private:
  183. std::unique_ptr<Sample> sample;
  184. double centreFrequencyInHz { 440.0 };
  185. Range<double> loopPoints;
  186. LoopMode loopMode { LoopMode::none };
  187. };
  188. //==============================================================================
  189. class MPESamplerVoice : public MPESynthesiserVoice
  190. {
  191. public:
  192. explicit MPESamplerVoice (std::shared_ptr<const MPESamplerSound> sound)
  193. : samplerSound (move (sound))
  194. {
  195. jassert (samplerSound != nullptr);
  196. }
  197. void noteStarted() override
  198. {
  199. jassert (currentlyPlayingNote.isValid());
  200. jassert (currentlyPlayingNote.keyState == MPENote::keyDown
  201. || currentlyPlayingNote.keyState == MPENote::keyDownAndSustained);
  202. level .setValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  203. frequency.setValue (currentlyPlayingNote.getFrequencyInHertz());
  204. auto loopPoints = samplerSound->getLoopPointsInSeconds();
  205. loopBegin.setValue (loopPoints.getStart() * samplerSound->getSample()->getSampleRate());
  206. loopEnd .setValue (loopPoints.getEnd() * samplerSound->getSample()->getSampleRate());
  207. for (auto smoothed : { &level, &frequency, &loopBegin, &loopEnd })
  208. smoothed->reset (currentSampleRate, smoothingLengthInSeconds);
  209. currentSamplePos = 0.0;
  210. tailOff = 0.0;
  211. }
  212. void noteStopped (bool allowTailOff) override
  213. {
  214. jassert (currentlyPlayingNote.keyState == MPENote::off);
  215. if (allowTailOff && tailOff == 0.0)
  216. tailOff = 1.0;
  217. else
  218. stopNote();
  219. }
  220. void notePressureChanged() override
  221. {
  222. level.setValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  223. }
  224. void notePitchbendChanged() override
  225. {
  226. frequency.setValue (currentlyPlayingNote.getFrequencyInHertz());
  227. }
  228. void noteTimbreChanged() override {}
  229. void noteKeyStateChanged() override {}
  230. void renderNextBlock (AudioBuffer<float>& outputBuffer,
  231. int startSample,
  232. int numSamples) override
  233. {
  234. jassert (samplerSound->getSample() != nullptr);
  235. auto loopPoints = samplerSound->getLoopPointsInSeconds();
  236. loopBegin.setValue (loopPoints.getStart() * samplerSound->getSample()->getSampleRate());
  237. loopEnd .setValue (loopPoints.getEnd() * samplerSound->getSample()->getSampleRate());
  238. auto& data = samplerSound->getSample()->getBuffer();
  239. auto inL = data.getReadPointer (0);
  240. auto inR = data.getNumChannels() > 1 ? data.getReadPointer (1) : nullptr;
  241. auto outL = outputBuffer.getWritePointer (0, startSample);
  242. if (outL == nullptr)
  243. return;
  244. auto outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getWritePointer (1, startSample)
  245. : nullptr;
  246. size_t writePos = 0;
  247. while (--numSamples >= 0 && renderNextSample (inL, inR, outL, outR, writePos))
  248. writePos += 1;
  249. }
  250. double getCurrentSamplePosition() const
  251. {
  252. return currentSamplePos;
  253. }
  254. private:
  255. bool renderNextSample (const float* inL,
  256. const float* inR,
  257. float* outL,
  258. float* outR,
  259. size_t writePos)
  260. {
  261. auto currentLevel = level.getNextValue();
  262. auto currentFrequency = frequency.getNextValue();
  263. auto currentLoopBegin = loopBegin.getNextValue();
  264. auto currentLoopEnd = loopEnd.getNextValue();
  265. if (isTailingOff())
  266. {
  267. currentLevel *= tailOff;
  268. tailOff *= 0.9999;
  269. if (tailOff < 0.005)
  270. {
  271. stopNote();
  272. return false;
  273. }
  274. }
  275. auto pos = (int) currentSamplePos;
  276. auto nextPos = pos + 1;
  277. auto alpha = (float) (currentSamplePos - pos);
  278. auto invAlpha = 1.0f - alpha;
  279. // just using a very simple linear interpolation here..
  280. auto l = static_cast<float> (currentLevel * (inL[pos] * invAlpha + inL[nextPos] * alpha));
  281. auto r = static_cast<float> ((inR != nullptr) ? currentLevel * (inR[pos] * invAlpha + inR[nextPos] * alpha)
  282. : l);
  283. if (outR != nullptr)
  284. {
  285. outL[writePos] += l;
  286. outR[writePos] += r;
  287. }
  288. else
  289. {
  290. outL[writePos] += (l + r) * 0.5f;
  291. }
  292. std::tie (currentSamplePos, currentDirection) = getNextState (currentFrequency,
  293. currentLoopBegin,
  294. currentLoopEnd);
  295. if (currentSamplePos > samplerSound->getSample()->getLength())
  296. {
  297. stopNote();
  298. return false;
  299. }
  300. return true;
  301. }
  302. double getSampleValue() const;
  303. bool isTailingOff() const
  304. {
  305. return tailOff != 0.0;
  306. }
  307. void stopNote()
  308. {
  309. clearCurrentNote();
  310. currentSamplePos = 0.0;
  311. }
  312. enum class Direction
  313. {
  314. forward,
  315. backward
  316. };
  317. std::tuple<double, Direction> getNextState (double freq,
  318. double begin,
  319. double end) const
  320. {
  321. auto nextPitchRatio = freq / samplerSound->getCentreFrequencyInHz();
  322. auto nextSamplePos = currentSamplePos;
  323. auto nextDirection = currentDirection;
  324. // Move the current sample pos in the correct direction
  325. switch (currentDirection)
  326. {
  327. case Direction::forward:
  328. nextSamplePos += nextPitchRatio;
  329. break;
  330. case Direction::backward:
  331. nextSamplePos -= nextPitchRatio;
  332. break;
  333. }
  334. // Update current sample position, taking loop mode into account
  335. // If the loop mode was changed while we were travelling backwards, deal
  336. // with it gracefully.
  337. if (nextDirection == Direction::backward && nextSamplePos < begin)
  338. {
  339. nextSamplePos = begin;
  340. nextDirection = Direction::forward;
  341. return { nextSamplePos, nextDirection };
  342. }
  343. if (samplerSound->getLoopMode() == LoopMode::none)
  344. return { nextSamplePos, nextDirection };
  345. if (nextDirection == Direction::forward && end < nextSamplePos && !isTailingOff())
  346. {
  347. if (samplerSound->getLoopMode() == LoopMode::forward)
  348. nextSamplePos = begin;
  349. else if (samplerSound->getLoopMode() == LoopMode::pingpong)
  350. {
  351. nextSamplePos = end;
  352. nextDirection = Direction::backward;
  353. }
  354. }
  355. return { nextSamplePos, nextDirection };
  356. }
  357. std::shared_ptr<const MPESamplerSound> samplerSound;
  358. LinearSmoothedValue<double> level { 0 };
  359. LinearSmoothedValue<double> frequency { 0 };
  360. LinearSmoothedValue<double> loopBegin;
  361. LinearSmoothedValue<double> loopEnd;
  362. double currentSamplePos { 0 };
  363. double tailOff { 0 };
  364. Direction currentDirection { Direction::forward };
  365. double smoothingLengthInSeconds { 0.01 };
  366. };
  367. template <typename Contents>
  368. class ReferenceCountingAdapter : public ReferenceCountedObject
  369. {
  370. public:
  371. template <typename... Args>
  372. explicit ReferenceCountingAdapter (Args&&... args)
  373. : contents (std::forward<Args> (args)...)
  374. {}
  375. const Contents& get() const
  376. {
  377. return contents;
  378. }
  379. Contents& get()
  380. {
  381. return contents;
  382. }
  383. private:
  384. Contents contents;
  385. };
  386. template <typename Contents, typename... Args>
  387. std::unique_ptr<ReferenceCountingAdapter<Contents>>
  388. make_reference_counted (Args&&... args)
  389. {
  390. auto adapter = new ReferenceCountingAdapter<Contents> (std::forward<Args> (args)...);
  391. return std::unique_ptr<ReferenceCountingAdapter<Contents>> (adapter);
  392. }
  393. //==============================================================================
  394. inline std::unique_ptr<AudioFormatReader> makeAudioFormatReader (AudioFormatManager& manager,
  395. const void* sampleData,
  396. size_t dataSize)
  397. {
  398. return std::unique_ptr<AudioFormatReader> (manager.createReaderFor (new MemoryInputStream (sampleData,
  399. dataSize,
  400. false)));
  401. }
  402. inline std::unique_ptr<AudioFormatReader> makeAudioFormatReader (AudioFormatManager& manager,
  403. const File& file)
  404. {
  405. return std::unique_ptr<AudioFormatReader> (manager.createReaderFor (file));
  406. }
  407. //==============================================================================
  408. class AudioFormatReaderFactory
  409. {
  410. public:
  411. virtual ~AudioFormatReaderFactory() noexcept = default;
  412. virtual std::unique_ptr<AudioFormatReader> make (AudioFormatManager&) const = 0;
  413. virtual std::unique_ptr<AudioFormatReaderFactory> clone() const = 0;
  414. };
  415. //==============================================================================
  416. class MemoryAudioFormatReaderFactory : public AudioFormatReaderFactory
  417. {
  418. public:
  419. MemoryAudioFormatReaderFactory (const void* sampleData, size_t dataSize)
  420. : sampleData (sampleData),
  421. dataSize (dataSize)
  422. {}
  423. std::unique_ptr<AudioFormatReader> make (AudioFormatManager&manager ) const override
  424. {
  425. return makeAudioFormatReader (manager, sampleData, dataSize);
  426. }
  427. std::unique_ptr<AudioFormatReaderFactory> clone() const override
  428. {
  429. return std::unique_ptr<AudioFormatReaderFactory> (new MemoryAudioFormatReaderFactory (*this));
  430. }
  431. private:
  432. const void* sampleData;
  433. size_t dataSize;
  434. };
  435. //==============================================================================
  436. class FileAudioFormatReaderFactory : public AudioFormatReaderFactory
  437. {
  438. public:
  439. explicit FileAudioFormatReaderFactory (File file)
  440. : file (std::move (file))
  441. {}
  442. std::unique_ptr<AudioFormatReader> make (AudioFormatManager& manager) const override
  443. {
  444. return makeAudioFormatReader (manager, file);
  445. }
  446. std::unique_ptr<AudioFormatReaderFactory> clone() const override
  447. {
  448. return std::unique_ptr<AudioFormatReaderFactory> (new FileAudioFormatReaderFactory (*this));
  449. }
  450. private:
  451. File file;
  452. };
  453. namespace juce
  454. {
  455. bool operator== (const MPEZoneLayout& a, const MPEZoneLayout& b)
  456. {
  457. if (a.getLowerZone() != b.getLowerZone())
  458. return false;
  459. if (a.getUpperZone() != b.getUpperZone())
  460. return false;
  461. return true;
  462. }
  463. bool operator!= (const MPEZoneLayout& a, const MPEZoneLayout& b)
  464. {
  465. return ! (a == b);
  466. }
  467. template<>
  468. struct VariantConverter<LoopMode>
  469. {
  470. static LoopMode fromVar (const var& v)
  471. {
  472. return static_cast<LoopMode> (int (v));
  473. }
  474. static var toVar (LoopMode loopMode)
  475. {
  476. return static_cast<int> (loopMode);
  477. }
  478. };
  479. template <typename Wrapped>
  480. struct GenericVariantConverter
  481. {
  482. static Wrapped fromVar (const var& v)
  483. {
  484. auto cast = dynamic_cast<ReferenceCountingAdapter<Wrapped>*> (v.getObject());
  485. jassert (cast != nullptr);
  486. return cast->get();
  487. }
  488. static var toVar (Wrapped range)
  489. {
  490. return { make_reference_counted<Wrapped> (std::move (range)).release() };
  491. }
  492. };
  493. template <typename Numeric>
  494. struct VariantConverter<Range<Numeric>> : GenericVariantConverter<Range<Numeric>> {};
  495. template<>
  496. struct VariantConverter<MPEZoneLayout> : GenericVariantConverter<MPEZoneLayout> {};
  497. template<>
  498. struct VariantConverter<std::shared_ptr<AudioFormatReaderFactory>>
  499. : GenericVariantConverter<std::shared_ptr<AudioFormatReaderFactory>>
  500. {};
  501. } // namespace juce
  502. //==============================================================================
  503. class VisibleRangeDataModel : public ValueTree::Listener
  504. {
  505. public:
  506. class Listener
  507. {
  508. public:
  509. virtual ~Listener() noexcept = default;
  510. virtual void totalRangeChanged (Range<double>) {}
  511. virtual void visibleRangeChanged (Range<double>) {}
  512. };
  513. VisibleRangeDataModel()
  514. : VisibleRangeDataModel (ValueTree (IDs::VISIBLE_RANGE))
  515. {}
  516. explicit VisibleRangeDataModel (const ValueTree& vt)
  517. : valueTree (vt),
  518. totalRange (valueTree, IDs::totalRange, nullptr),
  519. visibleRange (valueTree, IDs::visibleRange, nullptr)
  520. {
  521. jassert (valueTree.hasType (IDs::VISIBLE_RANGE));
  522. valueTree.addListener (this);
  523. }
  524. VisibleRangeDataModel (const VisibleRangeDataModel& other)
  525. : VisibleRangeDataModel (other.valueTree)
  526. {}
  527. VisibleRangeDataModel& operator= (const VisibleRangeDataModel& other)
  528. {
  529. auto copy (other);
  530. swap (copy);
  531. return *this;
  532. }
  533. Range<double> getTotalRange() const
  534. {
  535. return totalRange;
  536. }
  537. void setTotalRange (Range<double> value, UndoManager* undoManager)
  538. {
  539. totalRange.setValue (value, undoManager);
  540. setVisibleRange (visibleRange, undoManager);
  541. }
  542. Range<double> getVisibleRange() const
  543. {
  544. return visibleRange;
  545. }
  546. void setVisibleRange (Range<double> value, UndoManager* undoManager)
  547. {
  548. visibleRange.setValue (totalRange.get().constrainRange (value), undoManager);
  549. }
  550. void addListener (Listener& listener)
  551. {
  552. listenerList.add (&listener);
  553. }
  554. void removeListener (Listener& listener)
  555. {
  556. listenerList.remove (&listener);
  557. }
  558. void swap (VisibleRangeDataModel& other) noexcept
  559. {
  560. using std::swap;
  561. swap (other.valueTree, valueTree);
  562. }
  563. private:
  564. void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
  565. {
  566. if (property == IDs::totalRange)
  567. {
  568. totalRange.forceUpdateOfCachedValue();
  569. listenerList.call ([this] (Listener& l) { l.totalRangeChanged (totalRange); });
  570. }
  571. else if (property == IDs::visibleRange)
  572. {
  573. visibleRange.forceUpdateOfCachedValue();
  574. listenerList.call ([this] (Listener& l) { l.visibleRangeChanged (visibleRange); });
  575. }
  576. }
  577. void valueTreeChildAdded (ValueTree&, ValueTree&) override { jassertfalse; }
  578. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { jassertfalse; }
  579. void valueTreeChildOrderChanged (ValueTree&, int, int) override { jassertfalse; }
  580. void valueTreeParentChanged (ValueTree&) override { jassertfalse; }
  581. ValueTree valueTree;
  582. CachedValue<Range<double>> totalRange;
  583. CachedValue<Range<double>> visibleRange;
  584. ListenerList<Listener> listenerList;
  585. };
  586. //==============================================================================
  587. class MPESettingsDataModel : public ValueTree::Listener
  588. {
  589. public:
  590. class Listener
  591. {
  592. public:
  593. virtual ~Listener() noexcept = default;
  594. virtual void synthVoicesChanged (int) {}
  595. virtual void voiceStealingEnabledChanged (bool) {}
  596. virtual void legacyModeEnabledChanged (bool) {}
  597. virtual void mpeZoneLayoutChanged (const MPEZoneLayout&) {}
  598. virtual void legacyFirstChannelChanged (int) {}
  599. virtual void legacyLastChannelChanged (int) {}
  600. virtual void legacyPitchbendRangeChanged (int) {}
  601. };
  602. MPESettingsDataModel()
  603. : MPESettingsDataModel (ValueTree (IDs::MPE_SETTINGS))
  604. {}
  605. explicit MPESettingsDataModel (const ValueTree& vt)
  606. : valueTree (vt),
  607. synthVoices (valueTree, IDs::synthVoices, nullptr, 15),
  608. voiceStealingEnabled (valueTree, IDs::voiceStealingEnabled, nullptr, false),
  609. legacyModeEnabled (valueTree, IDs::legacyModeEnabled, nullptr, true),
  610. mpeZoneLayout (valueTree, IDs::mpeZoneLayout, nullptr, {}),
  611. legacyFirstChannel (valueTree, IDs::legacyFirstChannel, nullptr, 1),
  612. legacyLastChannel (valueTree, IDs::legacyLastChannel, nullptr, 15),
  613. legacyPitchbendRange (valueTree, IDs::legacyPitchbendRange, nullptr, 48)
  614. {
  615. jassert (valueTree.hasType (IDs::MPE_SETTINGS));
  616. valueTree.addListener (this);
  617. }
  618. MPESettingsDataModel (const MPESettingsDataModel& other)
  619. : MPESettingsDataModel (other.valueTree)
  620. {}
  621. MPESettingsDataModel& operator= (const MPESettingsDataModel& other)
  622. {
  623. auto copy (other);
  624. swap (copy);
  625. return *this;
  626. }
  627. int getSynthVoices() const
  628. {
  629. return synthVoices;
  630. }
  631. void setSynthVoices (int value, UndoManager* undoManager)
  632. {
  633. synthVoices.setValue (Range<int> (1, 20).clipValue (value), undoManager);
  634. }
  635. bool getVoiceStealingEnabled() const
  636. {
  637. return voiceStealingEnabled;
  638. }
  639. void setVoiceStealingEnabled (bool value, UndoManager* undoManager)
  640. {
  641. voiceStealingEnabled.setValue (value, undoManager);
  642. }
  643. bool getLegacyModeEnabled() const
  644. {
  645. return legacyModeEnabled;
  646. }
  647. void setLegacyModeEnabled (bool value, UndoManager* undoManager)
  648. {
  649. legacyModeEnabled.setValue (value, undoManager);
  650. }
  651. MPEZoneLayout getMPEZoneLayout() const
  652. {
  653. return mpeZoneLayout;
  654. }
  655. void setMPEZoneLayout (MPEZoneLayout value, UndoManager* undoManager)
  656. {
  657. mpeZoneLayout.setValue (value, undoManager);
  658. }
  659. int getLegacyFirstChannel() const
  660. {
  661. return legacyFirstChannel;
  662. }
  663. void setLegacyFirstChannel (int value, UndoManager* undoManager)
  664. {
  665. legacyFirstChannel.setValue (Range<int> (1, legacyLastChannel).clipValue (value), undoManager);
  666. }
  667. int getLegacyLastChannel() const
  668. {
  669. return legacyLastChannel;
  670. }
  671. void setLegacyLastChannel (int value, UndoManager* undoManager)
  672. {
  673. legacyLastChannel.setValue (Range<int> (legacyFirstChannel, 15).clipValue (value), undoManager);
  674. }
  675. int getLegacyPitchbendRange() const
  676. {
  677. return legacyPitchbendRange;
  678. }
  679. void setLegacyPitchbendRange (int value, UndoManager* undoManager)
  680. {
  681. legacyPitchbendRange.setValue (Range<int> (0, 95).clipValue (value), undoManager);
  682. }
  683. void addListener (Listener& listener)
  684. {
  685. listenerList.add (&listener);
  686. }
  687. void removeListener (Listener& listener)
  688. {
  689. listenerList.remove (&listener);
  690. }
  691. void swap (MPESettingsDataModel& other) noexcept
  692. {
  693. using std::swap;
  694. swap (other.valueTree, valueTree);
  695. }
  696. private:
  697. void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
  698. {
  699. if (property == IDs::synthVoices)
  700. {
  701. synthVoices.forceUpdateOfCachedValue();
  702. listenerList.call ([this] (Listener& l) { l.synthVoicesChanged (synthVoices); });
  703. }
  704. else if (property == IDs::voiceStealingEnabled)
  705. {
  706. voiceStealingEnabled.forceUpdateOfCachedValue();
  707. listenerList.call ([this] (Listener& l) { l.voiceStealingEnabledChanged (voiceStealingEnabled); });
  708. }
  709. else if (property == IDs::legacyModeEnabled)
  710. {
  711. legacyModeEnabled.forceUpdateOfCachedValue();
  712. listenerList.call ([this] (Listener& l) { l.legacyModeEnabledChanged (legacyModeEnabled); });
  713. }
  714. else if (property == IDs::mpeZoneLayout)
  715. {
  716. mpeZoneLayout.forceUpdateOfCachedValue();
  717. listenerList.call ([this] (Listener& l) { l.mpeZoneLayoutChanged (mpeZoneLayout); });
  718. }
  719. else if (property == IDs::legacyFirstChannel)
  720. {
  721. legacyFirstChannel.forceUpdateOfCachedValue();
  722. listenerList.call ([this] (Listener& l) { l.legacyFirstChannelChanged (legacyFirstChannel); });
  723. }
  724. else if (property == IDs::legacyLastChannel)
  725. {
  726. legacyLastChannel.forceUpdateOfCachedValue();
  727. listenerList.call ([this] (Listener& l) { l.legacyLastChannelChanged (legacyLastChannel); });
  728. }
  729. else if (property == IDs::legacyPitchbendRange)
  730. {
  731. legacyPitchbendRange.forceUpdateOfCachedValue();
  732. listenerList.call ([this] (Listener& l) { l.legacyPitchbendRangeChanged (legacyPitchbendRange); });
  733. }
  734. }
  735. void valueTreeChildAdded (ValueTree&, ValueTree&) override { jassertfalse; }
  736. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { jassertfalse; }
  737. void valueTreeChildOrderChanged (ValueTree&, int, int) override { jassertfalse; }
  738. void valueTreeParentChanged (ValueTree&) override { jassertfalse; }
  739. ValueTree valueTree;
  740. CachedValue<int> synthVoices;
  741. CachedValue<bool> voiceStealingEnabled;
  742. CachedValue<bool> legacyModeEnabled;
  743. CachedValue<MPEZoneLayout> mpeZoneLayout;
  744. CachedValue<int> legacyFirstChannel;
  745. CachedValue<int> legacyLastChannel;
  746. CachedValue<int> legacyPitchbendRange;
  747. ListenerList<Listener> listenerList;
  748. };
  749. //==============================================================================
  750. class DataModel : public ValueTree::Listener
  751. {
  752. public:
  753. class Listener
  754. {
  755. public:
  756. virtual ~Listener() noexcept = default;
  757. virtual void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory>) {}
  758. virtual void centreFrequencyHzChanged (double) {}
  759. virtual void loopModeChanged (LoopMode) {}
  760. virtual void loopPointsSecondsChanged (Range<double>) {}
  761. };
  762. explicit DataModel (AudioFormatManager& audioFormatManager)
  763. : DataModel (audioFormatManager, ValueTree (IDs::DATA_MODEL))
  764. {}
  765. DataModel (AudioFormatManager& audioFormatManager, const ValueTree& vt)
  766. : audioFormatManager (&audioFormatManager),
  767. valueTree (vt),
  768. sampleReader (valueTree, IDs::sampleReader, nullptr),
  769. centreFrequencyHz (valueTree, IDs::centreFrequencyHz, nullptr),
  770. loopMode (valueTree, IDs::loopMode, nullptr, LoopMode::none),
  771. loopPointsSeconds (valueTree, IDs::loopPointsSeconds, nullptr)
  772. {
  773. jassert (valueTree.hasType (IDs::DATA_MODEL));
  774. valueTree.addListener (this);
  775. }
  776. DataModel (const DataModel& other)
  777. : DataModel (*other.audioFormatManager, other.valueTree)
  778. {}
  779. DataModel& operator= (const DataModel& other)
  780. {
  781. auto copy (other);
  782. swap (copy);
  783. return *this;
  784. }
  785. std::unique_ptr<AudioFormatReader> getSampleReader() const
  786. {
  787. return sampleReader != nullptr ? sampleReader.get()->make (*audioFormatManager) : nullptr;
  788. }
  789. void setSampleReader (std::unique_ptr<AudioFormatReaderFactory> readerFactory,
  790. UndoManager* undoManager)
  791. {
  792. sampleReader.setValue (move (readerFactory), undoManager);
  793. setLoopPointsSeconds (Range<double> (0, getSampleLengthSeconds()).constrainRange (loopPointsSeconds),
  794. undoManager);
  795. }
  796. double getSampleLengthSeconds() const
  797. {
  798. if (auto r = getSampleReader())
  799. return r->lengthInSamples / r->sampleRate;
  800. return 1.0;
  801. }
  802. double getCentreFrequencyHz() const
  803. {
  804. return centreFrequencyHz;
  805. }
  806. void setCentreFrequencyHz (double value, UndoManager* undoManager)
  807. {
  808. centreFrequencyHz.setValue (Range<double> (20, 20000).clipValue (value),
  809. undoManager);
  810. }
  811. LoopMode getLoopMode() const
  812. {
  813. return loopMode;
  814. }
  815. void setLoopMode (LoopMode value, UndoManager* undoManager)
  816. {
  817. loopMode.setValue (value, undoManager);
  818. }
  819. Range<double> getLoopPointsSeconds() const
  820. {
  821. return loopPointsSeconds;
  822. }
  823. void setLoopPointsSeconds (Range<double> value, UndoManager* undoManager)
  824. {
  825. loopPointsSeconds.setValue (Range<double> (0, getSampleLengthSeconds()).constrainRange (value),
  826. undoManager);
  827. }
  828. MPESettingsDataModel mpeSettings()
  829. {
  830. return MPESettingsDataModel (valueTree.getOrCreateChildWithName (IDs::MPE_SETTINGS, nullptr));
  831. }
  832. void addListener (Listener& listener)
  833. {
  834. listenerList.add (&listener);
  835. }
  836. void removeListener (Listener& listener)
  837. {
  838. listenerList.remove (&listener);
  839. }
  840. void swap (DataModel& other) noexcept
  841. {
  842. using std::swap;
  843. swap (other.valueTree, valueTree);
  844. }
  845. AudioFormatManager& getAudioFormatManager() const
  846. {
  847. return *audioFormatManager;
  848. }
  849. private:
  850. void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
  851. {
  852. if (property == IDs::sampleReader)
  853. {
  854. sampleReader.forceUpdateOfCachedValue();
  855. listenerList.call ([this] (Listener& l) { l.sampleReaderChanged (sampleReader); });
  856. }
  857. else if (property == IDs::centreFrequencyHz)
  858. {
  859. centreFrequencyHz.forceUpdateOfCachedValue();
  860. listenerList.call ([this] (Listener& l) { l.centreFrequencyHzChanged (centreFrequencyHz); });
  861. }
  862. else if (property == IDs::loopMode)
  863. {
  864. loopMode.forceUpdateOfCachedValue();
  865. listenerList.call ([this] (Listener& l) { l.loopModeChanged (loopMode); });
  866. }
  867. else if (property == IDs::loopPointsSeconds)
  868. {
  869. loopPointsSeconds.forceUpdateOfCachedValue();
  870. listenerList.call ([this] (Listener& l) { l.loopPointsSecondsChanged (loopPointsSeconds); });
  871. }
  872. }
  873. void valueTreeChildAdded (ValueTree&, ValueTree&) override {}
  874. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { jassertfalse; }
  875. void valueTreeChildOrderChanged (ValueTree&, int, int) override { jassertfalse; }
  876. void valueTreeParentChanged (ValueTree&) override { jassertfalse; }
  877. AudioFormatManager* audioFormatManager;
  878. ValueTree valueTree;
  879. CachedValue<std::shared_ptr<AudioFormatReaderFactory>> sampleReader;
  880. CachedValue<double> centreFrequencyHz;
  881. CachedValue<LoopMode> loopMode;
  882. CachedValue<Range<double>> loopPointsSeconds;
  883. ListenerList<Listener> listenerList;
  884. };
  885. namespace
  886. {
  887. void initialiseComboBoxWithConsecutiveIntegers (Component& owner,
  888. ComboBox& comboBox,
  889. Label& label,
  890. int firstValue,
  891. int numValues,
  892. int valueToSelect)
  893. {
  894. for (auto i = 0; i < numValues; ++i)
  895. comboBox.addItem (String (i + firstValue), i + 1);
  896. comboBox.setSelectedId (valueToSelect - firstValue + 1);
  897. label.attachToComponent (&comboBox, true);
  898. owner.addAndMakeVisible (comboBox);
  899. }
  900. constexpr int controlHeight = 24;
  901. constexpr int controlSeparation = 6;
  902. } // namespace
  903. //==============================================================================
  904. class MPELegacySettingsComponent final : public Component,
  905. public MPESettingsDataModel::Listener
  906. {
  907. public:
  908. explicit MPELegacySettingsComponent (const MPESettingsDataModel& model,
  909. UndoManager& um)
  910. : dataModel (model),
  911. undoManager (&um)
  912. {
  913. dataModel.addListener (*this);
  914. initialiseComboBoxWithConsecutiveIntegers (*this, legacyStartChannel, legacyStartChannelLabel, 1, 16, 1);
  915. initialiseComboBoxWithConsecutiveIntegers (*this, legacyEndChannel, legacyEndChannelLabel, 1, 16, 16);
  916. initialiseComboBoxWithConsecutiveIntegers (*this, legacyPitchbendRange, legacyPitchbendRangeLabel, 0, 96, 2);
  917. legacyStartChannel.onChange = [this]
  918. {
  919. if (isLegacyModeValid())
  920. {
  921. undoManager->beginNewTransaction();
  922. dataModel.setLegacyFirstChannel (getFirstChannel(), undoManager);
  923. }
  924. };
  925. legacyEndChannel.onChange = [this]
  926. {
  927. if (isLegacyModeValid())
  928. {
  929. undoManager->beginNewTransaction();
  930. dataModel.setLegacyLastChannel (getLastChannel(), undoManager);
  931. }
  932. };
  933. legacyPitchbendRange.onChange = [this]
  934. {
  935. if (isLegacyModeValid())
  936. {
  937. undoManager->beginNewTransaction();
  938. dataModel.setLegacyPitchbendRange (legacyPitchbendRange.getText().getIntValue(), undoManager);
  939. }
  940. };
  941. }
  942. int getMinHeight() const
  943. {
  944. return (controlHeight * 3) + (controlSeparation * 2);
  945. }
  946. private:
  947. void resized() override
  948. {
  949. Rectangle<int> r (proportionOfWidth (0.65f), 0, proportionOfWidth (0.25f), getHeight());
  950. for (auto& comboBox : { &legacyStartChannel, &legacyEndChannel, &legacyPitchbendRange })
  951. {
  952. comboBox->setBounds (r.removeFromTop (controlHeight));
  953. r.removeFromTop (controlSeparation);
  954. }
  955. }
  956. bool isLegacyModeValid() const
  957. {
  958. if (! areLegacyModeParametersValid())
  959. {
  960. handleInvalidLegacyModeParameters();
  961. return false;
  962. }
  963. return true;
  964. }
  965. void legacyFirstChannelChanged (int value) override
  966. {
  967. legacyStartChannel.setSelectedId (value, dontSendNotification);
  968. }
  969. void legacyLastChannelChanged (int value) override
  970. {
  971. legacyEndChannel.setSelectedId (value, dontSendNotification);
  972. }
  973. void legacyPitchbendRangeChanged (int value) override
  974. {
  975. legacyPitchbendRange.setSelectedId (value + 1, dontSendNotification);
  976. }
  977. int getFirstChannel() const
  978. {
  979. return legacyStartChannel.getText().getIntValue();
  980. }
  981. int getLastChannel() const
  982. {
  983. return legacyEndChannel.getText().getIntValue();
  984. }
  985. bool areLegacyModeParametersValid() const
  986. {
  987. return getFirstChannel() <= getLastChannel();
  988. }
  989. void handleInvalidLegacyModeParameters() const
  990. {
  991. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  992. "Invalid legacy mode channel layout",
  993. "Cannot set legacy mode start/end channel:\n"
  994. "The end channel must not be less than the start channel!",
  995. "Got it");
  996. }
  997. MPESettingsDataModel dataModel;
  998. ComboBox legacyStartChannel, legacyEndChannel, legacyPitchbendRange;
  999. Label legacyStartChannelLabel { {}, "First channel" },
  1000. legacyEndChannelLabel { {}, "Last channel" },
  1001. legacyPitchbendRangeLabel { {}, "Pitchbend range (semitones)" };
  1002. UndoManager* undoManager;
  1003. };
  1004. //==============================================================================
  1005. class MPENewSettingsComponent final : public Component,
  1006. public MPESettingsDataModel::Listener
  1007. {
  1008. public:
  1009. MPENewSettingsComponent (const MPESettingsDataModel& model,
  1010. UndoManager& um)
  1011. : dataModel (model),
  1012. undoManager (&um)
  1013. {
  1014. dataModel.addListener (*this);
  1015. addAndMakeVisible (isLowerZoneButton);
  1016. isLowerZoneButton.setToggleState (true, NotificationType::dontSendNotification);
  1017. initialiseComboBoxWithConsecutiveIntegers (*this, memberChannels, memberChannelsLabel, 0, 16, 15);
  1018. initialiseComboBoxWithConsecutiveIntegers (*this, masterPitchbendRange, masterPitchbendRangeLabel, 0, 96, 2);
  1019. initialiseComboBoxWithConsecutiveIntegers (*this, notePitchbendRange, notePitchbendRangeLabel, 0, 96, 48);
  1020. for (auto& button : { &setZoneButton, &clearAllZonesButton })
  1021. addAndMakeVisible (button);
  1022. setZoneButton.onClick = [this]
  1023. {
  1024. auto isLowerZone = isLowerZoneButton.getToggleState();
  1025. auto numMemberChannels = memberChannels.getText().getIntValue();
  1026. auto perNotePb = notePitchbendRange.getText().getIntValue();
  1027. auto masterPb = masterPitchbendRange.getText().getIntValue();
  1028. if (isLowerZone)
  1029. zoneLayout.setLowerZone (numMemberChannels, perNotePb, masterPb);
  1030. else
  1031. zoneLayout.setUpperZone (numMemberChannels, perNotePb, masterPb);
  1032. undoManager->beginNewTransaction();
  1033. dataModel.setMPEZoneLayout (zoneLayout, undoManager);
  1034. };
  1035. clearAllZonesButton.onClick = [this]
  1036. {
  1037. zoneLayout.clearAllZones();
  1038. undoManager->beginNewTransaction();
  1039. dataModel.setMPEZoneLayout (zoneLayout, undoManager);
  1040. };
  1041. }
  1042. int getMinHeight() const
  1043. {
  1044. return (controlHeight * 6) + (controlSeparation * 6);
  1045. }
  1046. private:
  1047. void resized() override
  1048. {
  1049. Rectangle<int> r (proportionOfWidth (0.65f), 0, proportionOfWidth (0.25f), getHeight());
  1050. isLowerZoneButton.setBounds (r.removeFromTop (controlHeight));
  1051. r.removeFromTop (controlSeparation);
  1052. for (auto& comboBox : { &memberChannels, &masterPitchbendRange, &notePitchbendRange })
  1053. {
  1054. comboBox->setBounds (r.removeFromTop (controlHeight));
  1055. r.removeFromTop (controlSeparation);
  1056. }
  1057. r.removeFromTop (controlSeparation);
  1058. auto buttonLeft = proportionOfWidth (0.5f);
  1059. setZoneButton.setBounds (r.removeFromTop (controlHeight).withLeft (buttonLeft));
  1060. r.removeFromTop (controlSeparation);
  1061. clearAllZonesButton.setBounds (r.removeFromTop (controlHeight).withLeft (buttonLeft));
  1062. }
  1063. void mpeZoneLayoutChanged (const MPEZoneLayout& value) override
  1064. {
  1065. zoneLayout = value;
  1066. }
  1067. MPESettingsDataModel dataModel;
  1068. MPEZoneLayout zoneLayout;
  1069. ComboBox memberChannels, masterPitchbendRange, notePitchbendRange;
  1070. ToggleButton isLowerZoneButton { "Lower zone" };
  1071. Label memberChannelsLabel { {}, "Nr. of member channels" },
  1072. masterPitchbendRangeLabel { {}, "Master pitchbend range (semitones)" },
  1073. notePitchbendRangeLabel { {}, "Note pitchbend range (semitones)" };
  1074. TextButton setZoneButton { "Set zone" },
  1075. clearAllZonesButton { "Clear all zones" };
  1076. UndoManager* undoManager;
  1077. };
  1078. //==============================================================================
  1079. class MPESettingsComponent final : public Component,
  1080. public MPESettingsDataModel::Listener
  1081. {
  1082. public:
  1083. MPESettingsComponent (const MPESettingsDataModel& model,
  1084. UndoManager& um)
  1085. : dataModel (model),
  1086. legacySettings (dataModel, um),
  1087. newSettings (dataModel, um),
  1088. undoManager (&um)
  1089. {
  1090. dataModel.addListener (*this);
  1091. addAndMakeVisible (newSettings);
  1092. addChildComponent (legacySettings);
  1093. initialiseComboBoxWithConsecutiveIntegers (*this, numberOfVoices, numberOfVoicesLabel, 1, 20, 15);
  1094. numberOfVoices.onChange = [this]
  1095. {
  1096. undoManager->beginNewTransaction();
  1097. dataModel.setSynthVoices (numberOfVoices.getText().getIntValue(), undoManager);
  1098. };
  1099. for (auto& button : { &legacyModeEnabledToggle, &voiceStealingEnabledToggle })
  1100. {
  1101. addAndMakeVisible (button);
  1102. }
  1103. legacyModeEnabledToggle.onClick = [this]
  1104. {
  1105. undoManager->beginNewTransaction();
  1106. dataModel.setLegacyModeEnabled (legacyModeEnabledToggle.getToggleState(), undoManager);
  1107. };
  1108. voiceStealingEnabledToggle.onClick = [this]
  1109. {
  1110. undoManager->beginNewTransaction();
  1111. dataModel.setVoiceStealingEnabled (voiceStealingEnabledToggle.getToggleState(), undoManager);
  1112. };
  1113. }
  1114. private:
  1115. void resized() override
  1116. {
  1117. auto topHeight = jmax (legacySettings.getMinHeight(), newSettings.getMinHeight());
  1118. auto r = getLocalBounds();
  1119. r.removeFromTop (15);
  1120. auto top = r.removeFromTop (topHeight);
  1121. legacySettings.setBounds (top);
  1122. newSettings.setBounds (top);
  1123. r.removeFromLeft (proportionOfWidth (0.65f));
  1124. r = r.removeFromLeft (proportionOfWidth (0.25f));
  1125. auto toggleLeft = proportionOfWidth (0.25f);
  1126. legacyModeEnabledToggle.setBounds (r.removeFromTop (controlHeight).withLeft (toggleLeft));
  1127. r.removeFromTop (controlSeparation);
  1128. voiceStealingEnabledToggle.setBounds (r.removeFromTop (controlHeight).withLeft (toggleLeft));
  1129. r.removeFromTop (controlSeparation);
  1130. numberOfVoices.setBounds (r.removeFromTop (controlHeight));
  1131. }
  1132. void legacyModeEnabledChanged (bool value) override
  1133. {
  1134. legacySettings.setVisible (value);
  1135. newSettings.setVisible (! value);
  1136. legacyModeEnabledToggle.setToggleState (value, dontSendNotification);
  1137. }
  1138. void voiceStealingEnabledChanged (bool value) override
  1139. {
  1140. voiceStealingEnabledToggle.setToggleState (value, dontSendNotification);
  1141. }
  1142. void synthVoicesChanged (int value) override
  1143. {
  1144. numberOfVoices.setSelectedId (value, dontSendNotification);
  1145. }
  1146. MPESettingsDataModel dataModel;
  1147. MPELegacySettingsComponent legacySettings;
  1148. MPENewSettingsComponent newSettings;
  1149. ToggleButton legacyModeEnabledToggle { "Enable Legacy Mode" },
  1150. voiceStealingEnabledToggle { "Enable synth voice stealing" };
  1151. ComboBox numberOfVoices;
  1152. Label numberOfVoicesLabel { {}, "Number of synth voices" };
  1153. UndoManager* undoManager;
  1154. };
  1155. //==============================================================================
  1156. class LoopPointMarker : public Component
  1157. {
  1158. public:
  1159. using MouseCallback = std::function<void (LoopPointMarker&, const MouseEvent&)>;
  1160. LoopPointMarker (String marker,
  1161. MouseCallback onMouseDown,
  1162. MouseCallback onMouseDrag,
  1163. MouseCallback onMouseUp)
  1164. : text (std::move (marker)),
  1165. onMouseDown (move (onMouseDown)),
  1166. onMouseDrag (move (onMouseDrag)),
  1167. onMouseUp (move (onMouseUp))
  1168. {
  1169. setMouseCursor (MouseCursor::LeftRightResizeCursor);
  1170. }
  1171. private:
  1172. void resized() override
  1173. {
  1174. auto height = 20;
  1175. auto triHeight = 6;
  1176. auto bounds = getLocalBounds();
  1177. Path newPath;
  1178. newPath.addRectangle (bounds.removeFromBottom (height));
  1179. newPath.startNewSubPath (bounds.getBottomLeft().toFloat());
  1180. newPath.lineTo (bounds.getBottomRight().toFloat());
  1181. Point<float> apex (static_cast<float> (bounds.getX() + (bounds.getWidth() / 2)),
  1182. static_cast<float> (bounds.getBottom() - triHeight));
  1183. newPath.lineTo (apex);
  1184. newPath.closeSubPath();
  1185. newPath.addLineSegment (Line<float> (apex, Point<float> (apex.getX(), 0)), 1);
  1186. path = newPath;
  1187. }
  1188. void paint (Graphics& g) override
  1189. {
  1190. g.setColour (Colours::deepskyblue);
  1191. g.fillPath (path);
  1192. auto height = 20;
  1193. g.setColour (Colours::white);
  1194. g.drawText (text, getLocalBounds().removeFromBottom (height), Justification::centred);
  1195. }
  1196. bool hitTest (int x, int y) override
  1197. {
  1198. return path.contains ((float) x, (float) y);
  1199. }
  1200. void mouseDown (const MouseEvent& e) override
  1201. {
  1202. onMouseDown (*this, e);
  1203. }
  1204. void mouseDrag (const MouseEvent& e) override
  1205. {
  1206. onMouseDrag (*this, e);
  1207. }
  1208. void mouseUp (const MouseEvent& e) override
  1209. {
  1210. onMouseUp (*this, e);
  1211. }
  1212. String text;
  1213. Path path;
  1214. MouseCallback onMouseDown;
  1215. MouseCallback onMouseDrag;
  1216. MouseCallback onMouseUp;
  1217. };
  1218. //==============================================================================
  1219. class Ruler : public Component,
  1220. public VisibleRangeDataModel::Listener
  1221. {
  1222. public:
  1223. explicit Ruler (const VisibleRangeDataModel& model)
  1224. : visibleRange (model)
  1225. {
  1226. visibleRange.addListener (*this);
  1227. setMouseCursor (MouseCursor::LeftRightResizeCursor);
  1228. }
  1229. private:
  1230. void paint (Graphics& g) override
  1231. {
  1232. auto minDivisionWidth = 50.0f;
  1233. auto maxDivisions = getWidth() / minDivisionWidth;
  1234. auto lookFeel = dynamic_cast<LookAndFeel_V4*> (&getLookAndFeel());
  1235. auto bg = lookFeel->getCurrentColourScheme()
  1236. .getUIColour (LookAndFeel_V4::ColourScheme::UIColour::widgetBackground);
  1237. g.setGradientFill (ColourGradient (bg.brighter(),
  1238. 0,
  1239. 0,
  1240. bg.darker(),
  1241. 0,
  1242. (float) getHeight(),
  1243. false));
  1244. g.fillAll();
  1245. g.setColour (bg.brighter());
  1246. g.drawHorizontalLine (0, 0.0f, (float) getWidth());
  1247. g.setColour (bg.darker());
  1248. g.drawHorizontalLine (1, 0.0f, (float) getWidth());
  1249. g.setColour (Colours::lightgrey);
  1250. auto minLog = std::ceil (std::log10 (visibleRange.getVisibleRange().getLength() / maxDivisions));
  1251. auto precision = 2 + std::abs (minLog);
  1252. auto divisionMagnitude = std::pow (10, minLog);
  1253. auto startingDivision = std::ceil (visibleRange.getVisibleRange().getStart() / divisionMagnitude);
  1254. for (auto div = startingDivision; div * divisionMagnitude < visibleRange.getVisibleRange().getEnd(); ++div)
  1255. {
  1256. auto time = div * divisionMagnitude;
  1257. auto xPos = (time - visibleRange.getVisibleRange().getStart()) * getWidth()
  1258. / visibleRange.getVisibleRange().getLength();
  1259. std::ostringstream out_stream;
  1260. out_stream << std::setprecision (roundToInt (precision)) << roundToInt (time);
  1261. g.drawText (out_stream.str(),
  1262. Rectangle<int> (Point<int> (roundToInt (xPos) + 3, 0),
  1263. Point<int> (roundToInt (xPos + minDivisionWidth), getHeight())),
  1264. Justification::centredLeft,
  1265. false);
  1266. g.drawVerticalLine (roundToInt (xPos), 2.0f, (float) getHeight());
  1267. }
  1268. }
  1269. void mouseDown (const MouseEvent& e) override
  1270. {
  1271. visibleRangeOnMouseDown = visibleRange.getVisibleRange();
  1272. timeOnMouseDown = visibleRange.getVisibleRange().getStart()
  1273. + (visibleRange.getVisibleRange().getLength() * e.getMouseDownX()) / getWidth();
  1274. }
  1275. void mouseDrag (const MouseEvent& e) override
  1276. {
  1277. // Work out the scale of the new range
  1278. auto unitDistance = 100.0f;
  1279. auto scaleFactor = 1.0 / std::pow (2, e.getDistanceFromDragStartY() / unitDistance);
  1280. // Now position it so that the mouse continues to point at the same
  1281. // place on the ruler.
  1282. auto visibleLength = std::max (0.12, visibleRangeOnMouseDown.getLength() * scaleFactor);
  1283. auto rangeBegin = timeOnMouseDown - visibleLength * e.x / getWidth();
  1284. const Range<double> range (rangeBegin, rangeBegin + visibleLength);
  1285. visibleRange.setVisibleRange (range, nullptr);
  1286. }
  1287. void visibleRangeChanged (Range<double>) override
  1288. {
  1289. repaint();
  1290. }
  1291. VisibleRangeDataModel visibleRange;
  1292. Range<double> visibleRangeOnMouseDown;
  1293. double timeOnMouseDown;
  1294. };
  1295. //==============================================================================
  1296. class LoopPointsOverlay : public Component,
  1297. public DataModel::Listener,
  1298. public VisibleRangeDataModel::Listener
  1299. {
  1300. public:
  1301. LoopPointsOverlay (const DataModel& dModel,
  1302. const VisibleRangeDataModel& vModel,
  1303. UndoManager& undoManager)
  1304. : dataModel (dModel),
  1305. visibleRange (vModel),
  1306. beginMarker ("B",
  1307. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseDown (m, e); },
  1308. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointDragged (m, e); },
  1309. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseUp (m, e); }),
  1310. endMarker ("E",
  1311. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseDown (m, e); },
  1312. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointDragged (m, e); },
  1313. [this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseUp (m, e); }),
  1314. undoManager (&undoManager)
  1315. {
  1316. dataModel .addListener (*this);
  1317. visibleRange.addListener (*this);
  1318. for (auto ptr : { &beginMarker, &endMarker })
  1319. addAndMakeVisible (ptr);
  1320. }
  1321. private:
  1322. void resized() override
  1323. {
  1324. positionLoopPointMarkers();
  1325. }
  1326. void loopPointMouseDown (LoopPointMarker&, const MouseEvent&)
  1327. {
  1328. loopPointsOnMouseDown = dataModel.getLoopPointsSeconds();
  1329. undoManager->beginNewTransaction();
  1330. }
  1331. void loopPointDragged (LoopPointMarker& marker, const MouseEvent& e)
  1332. {
  1333. auto x = xPositionToTime (e.getEventRelativeTo (this).position.x);
  1334. const Range<double> newLoopRange (&marker == &beginMarker ? x : loopPointsOnMouseDown.getStart(),
  1335. &marker == &endMarker ? x : loopPointsOnMouseDown.getEnd());
  1336. dataModel.setLoopPointsSeconds (newLoopRange, undoManager);
  1337. }
  1338. void loopPointMouseUp (LoopPointMarker& marker, const MouseEvent& e)
  1339. {
  1340. auto x = xPositionToTime (e.getEventRelativeTo (this).position.x);
  1341. const Range<double> newLoopRange (&marker == &beginMarker ? x : loopPointsOnMouseDown.getStart(),
  1342. &marker == &endMarker ? x : loopPointsOnMouseDown.getEnd());
  1343. dataModel.setLoopPointsSeconds (newLoopRange, undoManager);
  1344. }
  1345. void loopPointsSecondsChanged (Range<double>) override
  1346. {
  1347. positionLoopPointMarkers();
  1348. }
  1349. void visibleRangeChanged (Range<double>) override
  1350. {
  1351. positionLoopPointMarkers();
  1352. }
  1353. double timeToXPosition (double time) const
  1354. {
  1355. return (time - visibleRange.getVisibleRange().getStart()) * getWidth()
  1356. / visibleRange.getVisibleRange().getLength();
  1357. }
  1358. double xPositionToTime (double xPosition) const
  1359. {
  1360. return ((xPosition * visibleRange.getVisibleRange().getLength()) / getWidth())
  1361. + visibleRange.getVisibleRange().getStart();
  1362. }
  1363. void positionLoopPointMarkers()
  1364. {
  1365. auto halfMarkerWidth = 7;
  1366. for (auto tup : { std::make_tuple (&beginMarker, dataModel.getLoopPointsSeconds().getStart()),
  1367. std::make_tuple (&endMarker, dataModel.getLoopPointsSeconds().getEnd()) })
  1368. {
  1369. auto ptr = std::get<0> (tup);
  1370. auto time = std::get<1> (tup);
  1371. ptr->setSize (halfMarkerWidth * 2, getHeight());
  1372. ptr->setTopLeftPosition (roundToInt (timeToXPosition (time) - halfMarkerWidth), 0);
  1373. }
  1374. }
  1375. DataModel dataModel;
  1376. VisibleRangeDataModel visibleRange;
  1377. Range<double> loopPointsOnMouseDown;
  1378. LoopPointMarker beginMarker, endMarker;
  1379. UndoManager* undoManager;
  1380. };
  1381. //==============================================================================
  1382. class PlaybackPositionOverlay : public Component,
  1383. public Timer,
  1384. public VisibleRangeDataModel::Listener
  1385. {
  1386. public:
  1387. using Provider = std::function<std::vector<float>()>;
  1388. PlaybackPositionOverlay (const VisibleRangeDataModel& model,
  1389. Provider provider)
  1390. : visibleRange (model),
  1391. provider (move (provider))
  1392. {
  1393. visibleRange.addListener (*this);
  1394. startTimer (16);
  1395. }
  1396. private:
  1397. void paint (Graphics& g) override
  1398. {
  1399. g.setColour (Colours::red);
  1400. for (auto position : provider())
  1401. {
  1402. g.drawVerticalLine (roundToInt (timeToXPosition (position)), 0.0f, (float) getHeight());
  1403. }
  1404. }
  1405. void timerCallback() override
  1406. {
  1407. repaint();
  1408. }
  1409. void visibleRangeChanged (Range<double>) override
  1410. {
  1411. repaint();
  1412. }
  1413. double timeToXPosition (double time) const
  1414. {
  1415. return (time - visibleRange.getVisibleRange().getStart()) * getWidth()
  1416. / visibleRange.getVisibleRange().getLength();
  1417. }
  1418. VisibleRangeDataModel visibleRange;
  1419. Provider provider;
  1420. };
  1421. //==============================================================================
  1422. class WaveformView : public Component,
  1423. public ChangeListener,
  1424. public DataModel::Listener,
  1425. public VisibleRangeDataModel::Listener
  1426. {
  1427. public:
  1428. WaveformView (const DataModel& model,
  1429. const VisibleRangeDataModel& vr)
  1430. : dataModel (model),
  1431. visibleRange (vr),
  1432. thumbnailCache (4),
  1433. thumbnail (4, dataModel.getAudioFormatManager(), thumbnailCache)
  1434. {
  1435. dataModel .addListener (*this);
  1436. visibleRange.addListener (*this);
  1437. thumbnail .addChangeListener (this);
  1438. }
  1439. private:
  1440. void paint (Graphics& g) override
  1441. {
  1442. // Draw the waveforms
  1443. g.fillAll (Colours::black);
  1444. auto numChannels = thumbnail.getNumChannels();
  1445. if (numChannels == 0)
  1446. {
  1447. g.setColour (Colours::white);
  1448. g.drawFittedText ("No File Loaded", getLocalBounds(), Justification::centred, 1);
  1449. return;
  1450. }
  1451. auto bounds = getLocalBounds();
  1452. auto channelHeight = bounds.getHeight() / numChannels;
  1453. for (auto i = 0; i != numChannels; ++i)
  1454. {
  1455. drawChannel (g, i, bounds.removeFromTop (channelHeight));
  1456. }
  1457. }
  1458. void changeListenerCallback (ChangeBroadcaster* source) override
  1459. {
  1460. if (source == &thumbnail)
  1461. repaint();
  1462. }
  1463. void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory> value) override
  1464. {
  1465. if (value == nullptr)
  1466. thumbnail.clear();
  1467. else
  1468. {
  1469. auto reader = value->make (dataModel.getAudioFormatManager());
  1470. thumbnail.setReader (reader.release(), currentHashCode);
  1471. currentHashCode += 1;
  1472. }
  1473. }
  1474. void visibleRangeChanged (Range<double>) override
  1475. {
  1476. repaint();
  1477. }
  1478. void drawChannel (Graphics& g, int channel, Rectangle<int> bounds)
  1479. {
  1480. g.setGradientFill (ColourGradient (Colours::lightblue,
  1481. bounds.getTopLeft().toFloat(),
  1482. Colours::darkgrey,
  1483. bounds.getBottomLeft().toFloat(),
  1484. false));
  1485. thumbnail.drawChannel (g,
  1486. bounds,
  1487. visibleRange.getVisibleRange().getStart(),
  1488. visibleRange.getVisibleRange().getEnd(),
  1489. channel,
  1490. 1.0f);
  1491. }
  1492. DataModel dataModel;
  1493. VisibleRangeDataModel visibleRange;
  1494. AudioThumbnailCache thumbnailCache;
  1495. AudioThumbnail thumbnail;
  1496. int64 currentHashCode = 0;
  1497. };
  1498. //==============================================================================
  1499. class WaveformEditor : public Component,
  1500. public DataModel::Listener
  1501. {
  1502. public:
  1503. WaveformEditor (const DataModel& model,
  1504. PlaybackPositionOverlay::Provider provider,
  1505. UndoManager& undoManager)
  1506. : dataModel (model),
  1507. waveformView (model, visibleRange),
  1508. playbackOverlay (visibleRange, move (provider)),
  1509. loopPoints (dataModel, visibleRange, undoManager),
  1510. ruler (visibleRange)
  1511. {
  1512. dataModel.addListener (*this);
  1513. addAndMakeVisible (waveformView);
  1514. addAndMakeVisible (playbackOverlay);
  1515. addChildComponent (loopPoints);
  1516. loopPoints.setAlwaysOnTop (true);
  1517. waveformView.toBack();
  1518. addAndMakeVisible (ruler);
  1519. }
  1520. private:
  1521. void resized() override
  1522. {
  1523. auto bounds = getLocalBounds();
  1524. ruler .setBounds (bounds.removeFromTop (25));
  1525. waveformView .setBounds (bounds);
  1526. playbackOverlay.setBounds (bounds);
  1527. loopPoints .setBounds (bounds);
  1528. }
  1529. void loopModeChanged (LoopMode value) override
  1530. {
  1531. loopPoints.setVisible (value != LoopMode::none);
  1532. }
  1533. void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory> value) override
  1534. {
  1535. auto lengthInSeconds = dataModel.getSampleLengthSeconds();
  1536. visibleRange.setTotalRange (Range<double> (0, lengthInSeconds), nullptr);
  1537. visibleRange.setVisibleRange (Range<double> (0, lengthInSeconds), nullptr);
  1538. }
  1539. DataModel dataModel;
  1540. VisibleRangeDataModel visibleRange;
  1541. WaveformView waveformView;
  1542. PlaybackPositionOverlay playbackOverlay;
  1543. LoopPointsOverlay loopPoints;
  1544. Ruler ruler;
  1545. };
  1546. //==============================================================================
  1547. class MainSamplerView : public Component,
  1548. public DataModel::Listener
  1549. {
  1550. public:
  1551. MainSamplerView (const DataModel& model,
  1552. PlaybackPositionOverlay::Provider provider,
  1553. UndoManager& um)
  1554. : dataModel (model),
  1555. waveformEditor (dataModel, move (provider), um),
  1556. undoManager (&um)
  1557. {
  1558. dataModel.addListener (*this);
  1559. addAndMakeVisible (waveformEditor);
  1560. addAndMakeVisible (loadNewSampleButton);
  1561. auto setReader = [this] (const FileChooser& fc)
  1562. {
  1563. undoManager->beginNewTransaction();
  1564. auto readerFactory = new FileAudioFormatReaderFactory (fc.getResult());
  1565. dataModel.setSampleReader (std::unique_ptr<AudioFormatReaderFactory> (readerFactory),
  1566. undoManager);
  1567. };
  1568. loadNewSampleButton.onClick = [this, setReader]
  1569. {
  1570. fileChooser.launchAsync (FileBrowserComponent::FileChooserFlags::openMode |
  1571. FileBrowserComponent::FileChooserFlags::canSelectFiles,
  1572. setReader);
  1573. };
  1574. addAndMakeVisible (centreFrequency);
  1575. centreFrequency.onValueChange = [this]
  1576. {
  1577. undoManager->beginNewTransaction();
  1578. dataModel.setCentreFrequencyHz (centreFrequency.getValue(),
  1579. centreFrequency.isMouseButtonDown() ? nullptr : undoManager);
  1580. };
  1581. centreFrequency.setRange (20, 20000, 1);
  1582. centreFrequency.setSliderStyle (Slider::SliderStyle::IncDecButtons);
  1583. centreFrequency.setIncDecButtonsMode (Slider::IncDecButtonMode::incDecButtonsDraggable_Vertical);
  1584. auto radioGroupId = 1;
  1585. for (auto buttonPtr : { &loopKindNone, &loopKindForward, &loopKindPingpong })
  1586. {
  1587. addAndMakeVisible (buttonPtr);
  1588. buttonPtr->setRadioGroupId (radioGroupId, dontSendNotification);
  1589. buttonPtr->setClickingTogglesState (true);
  1590. }
  1591. loopKindNone.onClick = [this]
  1592. {
  1593. if (loopKindNone.getToggleState())
  1594. {
  1595. undoManager->beginNewTransaction();
  1596. dataModel.setLoopMode (LoopMode::none, undoManager);
  1597. }
  1598. };
  1599. loopKindForward.onClick = [this]
  1600. {
  1601. if (loopKindForward.getToggleState())
  1602. {
  1603. undoManager->beginNewTransaction();
  1604. dataModel.setLoopMode (LoopMode::forward, undoManager);
  1605. }
  1606. };
  1607. loopKindPingpong.onClick = [this]
  1608. {
  1609. if (loopKindPingpong.getToggleState())
  1610. {
  1611. undoManager->beginNewTransaction();
  1612. dataModel.setLoopMode (LoopMode::pingpong, undoManager);
  1613. }
  1614. };
  1615. addAndMakeVisible (centreFrequencyLabel);
  1616. addAndMakeVisible (loopKindLabel);
  1617. }
  1618. private:
  1619. void resized() override
  1620. {
  1621. auto bounds = getLocalBounds();
  1622. auto topBar = bounds.removeFromTop (50);
  1623. auto padding = 4;
  1624. loadNewSampleButton .setBounds (topBar.removeFromRight (100).reduced (padding));
  1625. centreFrequencyLabel.setBounds (topBar.removeFromLeft (100).reduced (padding));
  1626. centreFrequency .setBounds (topBar.removeFromLeft (100).reduced (padding));
  1627. auto bottomBar = bounds.removeFromBottom (50);
  1628. loopKindLabel .setBounds (bottomBar.removeFromLeft (100).reduced (padding));
  1629. loopKindNone .setBounds (bottomBar.removeFromLeft (80) .reduced (padding));
  1630. loopKindForward .setBounds (bottomBar.removeFromLeft (80) .reduced (padding));
  1631. loopKindPingpong.setBounds (bottomBar.removeFromLeft (80) .reduced (padding));
  1632. waveformEditor.setBounds (bounds);
  1633. }
  1634. void loopModeChanged (LoopMode value) override
  1635. {
  1636. switch (value)
  1637. {
  1638. case LoopMode::none:
  1639. loopKindNone.setToggleState (true, dontSendNotification);
  1640. break;
  1641. case LoopMode::forward:
  1642. loopKindForward.setToggleState (true, dontSendNotification);
  1643. break;
  1644. case LoopMode::pingpong:
  1645. loopKindPingpong.setToggleState (true, dontSendNotification);
  1646. break;
  1647. }
  1648. }
  1649. void centreFrequencyHzChanged (double value) override
  1650. {
  1651. centreFrequency.setValue (value, dontSendNotification);
  1652. }
  1653. DataModel dataModel;
  1654. WaveformEditor waveformEditor;
  1655. TextButton loadNewSampleButton { "Load New Sample" };
  1656. Slider centreFrequency;
  1657. TextButton loopKindNone { "None" },
  1658. loopKindForward { "Forward" },
  1659. loopKindPingpong { "Ping Pong" };
  1660. Label centreFrequencyLabel { {}, "Sample Centre Freq / Hz" },
  1661. loopKindLabel { {}, "Looping Mode" };
  1662. FileChooser fileChooser { "Select a file to load...",
  1663. File::nonexistent,
  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;