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.

500 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file was auto-generated!
  4. It contains the basic framework code for a JUCE plugin processor.
  5. ==============================================================================
  6. */
  7. #include "PluginProcessor.h"
  8. #include "PluginEditor.h"
  9. #include <set>
  10. #ifdef WIN32
  11. #undef min
  12. #undef max
  13. #endif
  14. std::set<PaulstretchpluginAudioProcessor*> g_activeprocessors;
  15. template<typename F>
  16. void callGUI(AudioProcessor* ap, F&& f, bool async)
  17. {
  18. auto ed = dynamic_cast<PaulstretchpluginAudioProcessorEditor*>(ap->getActiveEditor());
  19. if (ed)
  20. {
  21. if (async == false)
  22. f(ed);
  23. else
  24. MessageManager::callAsync([ed,f]() { f(ed); });
  25. }
  26. }
  27. int get_optimized_updown(int n, bool up) {
  28. int orig_n = n;
  29. while (true) {
  30. n = orig_n;
  31. while (!(n % 11)) n /= 11;
  32. while (!(n % 7)) n /= 7;
  33. while (!(n % 5)) n /= 5;
  34. while (!(n % 3)) n /= 3;
  35. while (!(n % 2)) n /= 2;
  36. if (n<2) break;
  37. if (up) orig_n++;
  38. else orig_n--;
  39. if (orig_n<4) return 4;
  40. };
  41. return orig_n;
  42. };
  43. int optimizebufsize(int n) {
  44. int n1 = get_optimized_updown(n, false);
  45. int n2 = get_optimized_updown(n, true);
  46. if ((n - n1)<(n2 - n)) return n1;
  47. else return n2;
  48. };
  49. //==============================================================================
  50. PaulstretchpluginAudioProcessor::PaulstretchpluginAudioProcessor()
  51. : m_bufferingthread("pspluginprebufferthread")
  52. #ifndef JucePlugin_PreferredChannelConfigurations
  53. : AudioProcessor (BusesProperties()
  54. #if ! JucePlugin_IsMidiEffect
  55. #if ! JucePlugin_IsSynth
  56. .withInput ("Input", AudioChannelSet::stereo(), true)
  57. #endif
  58. .withOutput ("Output", AudioChannelSet::stereo(), true)
  59. #endif
  60. )
  61. #endif
  62. {
  63. g_activeprocessors.insert(this);
  64. m_recbuffer.setSize(2, 44100);
  65. m_recbuffer.clear();
  66. if (m_afm->getNumKnownFormats()==0)
  67. m_afm->registerBasicFormats();
  68. m_stretch_source = std::make_unique<StretchAudioSource>(2, m_afm);
  69. setPreBufferAmount(2);
  70. m_ppar.pitch_shift.enabled = true;
  71. m_ppar.freq_shift.enabled = true;
  72. m_stretch_source->setOnsetDetection(0.0);
  73. m_stretch_source->setLoopingEnabled(true);
  74. m_stretch_source->setFFTWindowingType(1);
  75. addParameter(new AudioParameterFloat("mainvolume0", "Main volume", -24.0f, 12.0f, -3.0f)); // 0
  76. addParameter(new AudioParameterFloat("stretchamount0", "Stretch amount",
  77. NormalisableRange<float>(0.1f, 128.0f, 0.01f, 0.5),1.0f)); // 1
  78. addParameter(new AudioParameterFloat("fftsize0", "FFT size", 0.0f, 1.0f, 0.7f)); // 2
  79. addParameter(new AudioParameterFloat("pitchshift0", "Pitch shift", -24.0f, 24.0f, 0.0f)); // 3
  80. addParameter(new AudioParameterFloat("freqshift0", "Frequency shift", -1000.0f, 1000.0f, 0.0f)); // 4
  81. addParameter(new AudioParameterFloat("playrange_start0", "Sound start", 0.0f, 1.0f, 0.0f)); // 5
  82. addParameter(new AudioParameterFloat("playrange_end0", "Sound end", 0.0f, 1.0f, 1.0f)); // 6
  83. addParameter(new AudioParameterBool("freeze0", "Freeze", false)); // 7
  84. addParameter(new AudioParameterFloat("spread0", "Frequency spread", 0.0f, 1.0f, 0.0f)); // 8
  85. addParameter(new AudioParameterFloat("compress0", "Compress", 0.0f, 1.0f, 0.0f)); // 9
  86. addParameter(new AudioParameterFloat("loopxfadelen0", "Loop xfade length", 0.0f, 1.0f, 0.0f)); // 10
  87. addParameter(new AudioParameterFloat("numharmonics0", "Num harmonics", 0.0f, 100.0f, 0.0f)); // 11
  88. addParameter(new AudioParameterFloat("harmonicsfreq0", "Harmonics base freq",
  89. NormalisableRange<float>(1.0f, 5000.0f, 1.00f, 0.5), 128.0f)); // 12
  90. addParameter(new AudioParameterFloat("harmonicsbw0", "Harmonics bandwidth", 0.1f, 200.0f, 25.0f)); // 13
  91. addParameter(new AudioParameterBool("harmonicsgauss0", "Gaussian harmonics", false)); // 14
  92. addParameter(new AudioParameterFloat("octavemixm2_0", "2 octaves down level", 0.0f, 1.0f, 0.0f)); // 15
  93. addParameter(new AudioParameterFloat("octavemixm1_0", "Octave down level", 0.0f, 1.0f, 0.0f)); // 16
  94. addParameter(new AudioParameterFloat("octavemix0_0", "Normal pitch level", 0.0f, 1.0f, 0.0f)); // 17
  95. addParameter(new AudioParameterFloat("octavemix1_0", "1 octave up level", 0.0f, 1.0f, 0.0f)); // 18
  96. addParameter(new AudioParameterFloat("octavemix15_0", "1 octave and fifth up level", 0.0f, 1.0f, 0.0f)); // 19
  97. addParameter(new AudioParameterFloat("octavemix2_0", "2 octaves up level", 0.0f, 1.0f, 0.0f)); // 20
  98. }
  99. PaulstretchpluginAudioProcessor::~PaulstretchpluginAudioProcessor()
  100. {
  101. g_activeprocessors.erase(this);
  102. m_bufferingthread.stopThread(1000);
  103. }
  104. void PaulstretchpluginAudioProcessor::setPreBufferAmount(int x)
  105. {
  106. int temp = jlimit(0, 5, x);
  107. if (temp != m_prebuffer_amount)
  108. {
  109. m_prebuffer_amount = temp;
  110. m_recreate_buffering_source = true;
  111. }
  112. }
  113. //==============================================================================
  114. const String PaulstretchpluginAudioProcessor::getName() const
  115. {
  116. return JucePlugin_Name;
  117. }
  118. bool PaulstretchpluginAudioProcessor::acceptsMidi() const
  119. {
  120. #if JucePlugin_WantsMidiInput
  121. return true;
  122. #else
  123. return false;
  124. #endif
  125. }
  126. bool PaulstretchpluginAudioProcessor::producesMidi() const
  127. {
  128. #if JucePlugin_ProducesMidiOutput
  129. return true;
  130. #else
  131. return false;
  132. #endif
  133. }
  134. bool PaulstretchpluginAudioProcessor::isMidiEffect() const
  135. {
  136. #if JucePlugin_IsMidiEffect
  137. return true;
  138. #else
  139. return false;
  140. #endif
  141. }
  142. double PaulstretchpluginAudioProcessor::getTailLengthSeconds() const
  143. {
  144. return (double)m_bufamounts[m_prebuffer_amount]/getSampleRate();
  145. }
  146. int PaulstretchpluginAudioProcessor::getNumPrograms()
  147. {
  148. return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs,
  149. // so this should be at least 1, even if you're not really implementing programs.
  150. }
  151. int PaulstretchpluginAudioProcessor::getCurrentProgram()
  152. {
  153. return 0;
  154. }
  155. void PaulstretchpluginAudioProcessor::setCurrentProgram (int index)
  156. {
  157. }
  158. const String PaulstretchpluginAudioProcessor::getProgramName (int index)
  159. {
  160. return {};
  161. }
  162. void PaulstretchpluginAudioProcessor::changeProgramName (int index, const String& newName)
  163. {
  164. }
  165. void PaulstretchpluginAudioProcessor::setFFTSize(double size)
  166. {
  167. if (m_prebuffer_amount == 5)
  168. m_fft_size_to_use = pow(2, 7.0 + size * 14.5);
  169. else m_fft_size_to_use = pow(2, 7.0 + size * 10.0); // chicken out from allowing huge FFT sizes if not enough prebuffering
  170. int optim = optimizebufsize(m_fft_size_to_use);
  171. m_fft_size_to_use = optim;
  172. m_stretch_source->setFFTSize(optim);
  173. //Logger::writeToLog(String(m_fft_size_to_use));
  174. }
  175. void PaulstretchpluginAudioProcessor::startplay(Range<double> playrange, int numoutchans, String& err)
  176. {
  177. m_stretch_source->setPlayRange(playrange, true);
  178. int bufamt = m_bufamounts[m_prebuffer_amount];
  179. if (m_buffering_source != nullptr && numoutchans != m_buffering_source->getNumberOfChannels())
  180. m_recreate_buffering_source = true;
  181. if (m_recreate_buffering_source == true)
  182. {
  183. m_buffering_source = std::make_unique<MyBufferingAudioSource>(m_stretch_source.get(),
  184. m_bufferingthread, false, bufamt, numoutchans, false);
  185. m_recreate_buffering_source = false;
  186. }
  187. if (m_bufferingthread.isThreadRunning() == false)
  188. m_bufferingthread.startThread();
  189. m_stretch_source->setNumOutChannels(numoutchans);
  190. m_stretch_source->setFFTSize(m_fft_size_to_use);
  191. m_stretch_source->setProcessParameters(&m_ppar);
  192. m_last_outpos_pos = 0.0;
  193. m_last_in_pos = playrange.getStart()*m_stretch_source->getInfileLengthSeconds();
  194. m_buffering_source->prepareToPlay(1024, 44100.0);
  195. };
  196. void PaulstretchpluginAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)
  197. {
  198. std::lock_guard<std::mutex> locker(m_mutex);
  199. if (getNumOutputChannels() != m_cur_num_out_chans)
  200. m_ready_to_play = false;
  201. if (m_using_memory_buffer == true)
  202. {
  203. int len = jlimit(100,m_recbuffer.getNumSamples(), m_rec_pos);
  204. m_stretch_source->setAudioBufferAsInputSource(&m_recbuffer,
  205. getSampleRate(),
  206. len);
  207. callGUI(this,[this,len](auto ed) { ed->setAudioBuffer(&m_recbuffer, getSampleRate(), len); },false);
  208. }
  209. if (m_ready_to_play == false)
  210. {
  211. setFFTSize(*getFloatParameter(2));
  212. m_stretch_source->setProcessParameters(&m_ppar);
  213. String err;
  214. startplay({ *getFloatParameter(5),*getFloatParameter(6) },
  215. 2, err);
  216. m_cur_num_out_chans = getNumOutputChannels();
  217. m_ready_to_play = true;
  218. }
  219. }
  220. void PaulstretchpluginAudioProcessor::releaseResources()
  221. {
  222. //m_control->stopplay();
  223. //m_ready_to_play = false;
  224. }
  225. #ifndef JucePlugin_PreferredChannelConfigurations
  226. bool PaulstretchpluginAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const
  227. {
  228. #if JucePlugin_IsMidiEffect
  229. ignoreUnused (layouts);
  230. return true;
  231. #else
  232. // This is the place where you check if the layout is supported.
  233. // In this template code we only support mono or stereo.
  234. if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono()
  235. && layouts.getMainOutputChannelSet() != AudioChannelSet::stereo())
  236. return false;
  237. // This checks if the input layout matches the output layout
  238. #if ! JucePlugin_IsSynth
  239. if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
  240. return false;
  241. #endif
  242. return true;
  243. #endif
  244. }
  245. #endif
  246. void copyAudioBufferWrappingPosition(const AudioBuffer<float>& src, AudioBuffer<float>& dest, int destbufpos, int maxdestpos)
  247. {
  248. for (int i = 0; i < dest.getNumChannels(); ++i)
  249. {
  250. int channel_to_copy = i % src.getNumChannels();
  251. if (destbufpos + src.getNumSamples() > maxdestpos)
  252. {
  253. int wrappos = (destbufpos + src.getNumSamples()) % maxdestpos;
  254. int partial_len = src.getNumSamples() - wrappos;
  255. dest.copyFrom(channel_to_copy, destbufpos, src, channel_to_copy, 0, partial_len);
  256. dest.copyFrom(channel_to_copy, partial_len, src, channel_to_copy, 0, wrappos);
  257. }
  258. else
  259. {
  260. dest.copyFrom(channel_to_copy, destbufpos, src, channel_to_copy, 0, src.getNumSamples());
  261. }
  262. }
  263. }
  264. void PaulstretchpluginAudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  265. {
  266. std::lock_guard<std::mutex> locker(m_mutex);
  267. ScopedNoDenormals noDenormals;
  268. const int totalNumInputChannels = getTotalNumInputChannels();
  269. const int totalNumOutputChannels = getTotalNumOutputChannels();
  270. for (int i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
  271. buffer.clear (i, 0, buffer.getNumSamples());
  272. if (m_ready_to_play == false)
  273. return;
  274. if (m_is_recording == true)
  275. {
  276. int recbuflenframes = m_max_reclen * getSampleRate();
  277. copyAudioBufferWrappingPosition(buffer, m_recbuffer, m_rec_pos, recbuflenframes);
  278. callGUI(this,[this, &buffer](PaulstretchpluginAudioProcessorEditor*ed)
  279. {
  280. ed->addAudioBlock(buffer, getSampleRate(), m_rec_pos);
  281. }, false);
  282. m_rec_pos = (m_rec_pos + buffer.getNumSamples()) % recbuflenframes;
  283. return;
  284. }
  285. jassert(m_buffering_source != nullptr);
  286. jassert(m_bufferingthread.isThreadRunning());
  287. m_stretch_source->setMainVolume(*getFloatParameter(0));
  288. m_stretch_source->setRate(*getFloatParameter(1));
  289. setFFTSize(*getFloatParameter(2));
  290. m_ppar.pitch_shift.cents = *getFloatParameter(3) * 100.0;
  291. m_ppar.freq_shift.Hz = *getFloatParameter(4);
  292. m_ppar.spread.enabled = *getFloatParameter(8) > 0.0f;
  293. m_ppar.spread.bandwidth = *getFloatParameter(8);
  294. m_ppar.compressor.power = *getFloatParameter(9);
  295. m_ppar.harmonics.enabled = *getFloatParameter(11)>=1.0;
  296. m_ppar.harmonics.nharmonics = *getFloatParameter(11);
  297. m_ppar.harmonics.freq = *getFloatParameter(12);
  298. m_stretch_source->setLoopXFadeLength(*getFloatParameter(10));
  299. double t0 = *getFloatParameter(5);
  300. double t1 = *getFloatParameter(6);
  301. if (t0 > t1)
  302. std::swap(t0, t1);
  303. if (t1 - t0 < 0.001)
  304. t1 = t0 + 0.001;
  305. m_stretch_source->setPlayRange({ t0,t1 }, true);
  306. m_stretch_source->setFreezing(getParameter(7));
  307. m_stretch_source->setProcessParameters(&m_ppar);
  308. AudioSourceChannelInfo aif(buffer);
  309. m_buffering_source->getNextAudioBlock(aif);
  310. }
  311. //==============================================================================
  312. bool PaulstretchpluginAudioProcessor::hasEditor() const
  313. {
  314. return true; // (change this to false if you choose to not supply an editor)
  315. }
  316. AudioProcessorEditor* PaulstretchpluginAudioProcessor::createEditor()
  317. {
  318. return new PaulstretchpluginAudioProcessorEditor (*this);
  319. }
  320. //==============================================================================
  321. void PaulstretchpluginAudioProcessor::getStateInformation (MemoryBlock& destData)
  322. {
  323. ValueTree paramtree("paulstretch3pluginstate");
  324. for (int i=0;i<getNumParameters();++i)
  325. {
  326. auto par = getFloatParameter(i);
  327. if (par != nullptr)
  328. {
  329. paramtree.setProperty(par->paramID, (double)*par, nullptr);
  330. }
  331. }
  332. if (m_current_file != File())
  333. {
  334. paramtree.setProperty("importedfile", m_current_file.getFullPathName(), nullptr);
  335. }
  336. MemoryOutputStream stream(destData,true);
  337. paramtree.writeToStream(stream);
  338. }
  339. void PaulstretchpluginAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
  340. {
  341. ValueTree tree = ValueTree::readFromData(data, sizeInBytes);
  342. if (tree.isValid())
  343. {
  344. {
  345. std::lock_guard<std::mutex> locker(m_mutex);
  346. for (int i = 0; i < getNumParameters(); ++i)
  347. {
  348. auto par = getFloatParameter(i);
  349. if (par != nullptr)
  350. {
  351. double parval = tree.getProperty(par->paramID, (double)*par);
  352. *par = parval;
  353. }
  354. }
  355. }
  356. String fn = tree.getProperty("importedfile");
  357. if (fn.isEmpty() == false)
  358. {
  359. File f(fn);
  360. setAudioFile(f);
  361. }
  362. }
  363. }
  364. void PaulstretchpluginAudioProcessor::setRecordingEnabled(bool b)
  365. {
  366. std::lock_guard<std::mutex> locker(m_mutex);
  367. int lenbufframes = getSampleRate()*m_max_reclen;
  368. if (b == true)
  369. {
  370. m_using_memory_buffer = true;
  371. m_current_file = File();
  372. m_recbuffer.setSize(2, m_max_reclen*getSampleRate()+4096);
  373. m_recbuffer.clear();
  374. m_rec_pos = 0;
  375. callGUI(this,[this,lenbufframes](PaulstretchpluginAudioProcessorEditor* ed)
  376. {
  377. ed->beginAddingAudioBlocks(2, getSampleRate(), lenbufframes);
  378. },false);
  379. m_is_recording = true;
  380. }
  381. else
  382. {
  383. if (m_is_recording == true)
  384. {
  385. finishRecording(lenbufframes);
  386. }
  387. }
  388. }
  389. double PaulstretchpluginAudioProcessor::getRecordingPositionPercent()
  390. {
  391. if (m_is_recording==false)
  392. return 0.0;
  393. return 1.0 / m_recbuffer.getNumSamples()*m_rec_pos;
  394. }
  395. String PaulstretchpluginAudioProcessor::setAudioFile(File f)
  396. {
  397. auto ai = unique_from_raw(m_afm->createReaderFor(f));
  398. if (ai != nullptr)
  399. {
  400. if (ai->numChannels > 32)
  401. {
  402. //MessageManager::callAsync([cb, file]() { cb("Too many channels in file " + file.getFullPathName()); });
  403. return "Too many channels in file "+f.getFullPathName();
  404. }
  405. if (ai->bitsPerSample>32)
  406. {
  407. //MessageManager::callAsync([cb, file]() { cb("Too high bit depth in file " + file.getFullPathName()); });
  408. return "Too high bit depth in file " + f.getFullPathName();
  409. }
  410. std::lock_guard<std::mutex> locker(m_mutex);
  411. m_stretch_source->setAudioFile(f);
  412. m_current_file = f;
  413. m_using_memory_buffer = false;
  414. return String();
  415. //MessageManager::callAsync([cb, file]() { cb(String()); });
  416. }
  417. return "Could not open file " + f.getFullPathName();
  418. }
  419. Range<double> PaulstretchpluginAudioProcessor::getTimeSelection()
  420. {
  421. return { *getFloatParameter(5),*getFloatParameter(6) };
  422. }
  423. double PaulstretchpluginAudioProcessor::getPreBufferingPercent()
  424. {
  425. if (m_buffering_source==nullptr)
  426. return 0.0;
  427. return m_buffering_source->getPercentReady();
  428. }
  429. void PaulstretchpluginAudioProcessor::finishRecording(int lenrecording)
  430. {
  431. m_is_recording = false;
  432. m_stretch_source->setAudioBufferAsInputSource(&m_recbuffer, getSampleRate(), lenrecording);
  433. m_stretch_source->setPlayRange({ *getFloatParameter(5),*getFloatParameter(6) }, true);
  434. auto ed = dynamic_cast<PaulstretchpluginAudioProcessorEditor*>(getActiveEditor());
  435. if (ed)
  436. {
  437. //ed->setAudioBuffer(&m_recbuffer, getSampleRate(), lenrecording);
  438. }
  439. }
  440. //==============================================================================
  441. // This creates new instances of the plugin..
  442. AudioProcessor* JUCE_CALLTYPE createPluginFilter()
  443. {
  444. return new PaulstretchpluginAudioProcessor();
  445. }