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.

507 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. ScopedLock locker(m_cs);
  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. ScopedLock locker(m_cs);
  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(cpi_pitchshift) * 100.0;
  291. m_ppar.freq_shift.Hz = *getFloatParameter(cpi_frequencyshift);
  292. m_ppar.spread.enabled = *getFloatParameter(cpi_spreadamount) > 0.0f;
  293. m_ppar.spread.bandwidth = *getFloatParameter(cpi_spreadamount);
  294. m_ppar.compressor.power = *getFloatParameter(cpi_compress);
  295. m_ppar.harmonics.enabled = *getFloatParameter(cpi_numharmonics)>=1.0;
  296. m_ppar.harmonics.nharmonics = *getFloatParameter(cpi_numharmonics);
  297. m_ppar.harmonics.freq = *getFloatParameter(cpi_harmonicsfreq);
  298. m_ppar.octave.om2 = *getFloatParameter(cpi_octavesm2);
  299. m_ppar.octave.om1 = *getFloatParameter(cpi_octavesm1);
  300. m_ppar.octave.o0 = *getFloatParameter(cpi_octaves0);
  301. m_ppar.octave.o1 = *getFloatParameter(cpi_octaves1);
  302. m_ppar.octave.o15 = *getFloatParameter(cpi_octaves15);
  303. m_ppar.octave.o2 = *getFloatParameter(cpi_octaves2);
  304. m_ppar.octave.enabled = true;
  305. m_stretch_source->setLoopXFadeLength(*getFloatParameter(cpi_loopxfadelen));
  306. double t0 = *getFloatParameter(cpi_soundstart);
  307. double t1 = *getFloatParameter(cpi_soundend);
  308. if (t0 > t1)
  309. std::swap(t0, t1);
  310. if (t1 - t0 < 0.001)
  311. t1 = t0 + 0.001;
  312. m_stretch_source->setPlayRange({ t0,t1 }, true);
  313. m_stretch_source->setFreezing(getParameter(cpi_freeze));
  314. m_stretch_source->setProcessParameters(&m_ppar);
  315. AudioSourceChannelInfo aif(buffer);
  316. m_buffering_source->getNextAudioBlock(aif);
  317. }
  318. //==============================================================================
  319. bool PaulstretchpluginAudioProcessor::hasEditor() const
  320. {
  321. return true; // (change this to false if you choose to not supply an editor)
  322. }
  323. AudioProcessorEditor* PaulstretchpluginAudioProcessor::createEditor()
  324. {
  325. return new PaulstretchpluginAudioProcessorEditor (*this);
  326. }
  327. //==============================================================================
  328. void PaulstretchpluginAudioProcessor::getStateInformation (MemoryBlock& destData)
  329. {
  330. ValueTree paramtree("paulstretch3pluginstate");
  331. for (int i=0;i<getNumParameters();++i)
  332. {
  333. auto par = getFloatParameter(i);
  334. if (par != nullptr)
  335. {
  336. paramtree.setProperty(par->paramID, (double)*par, nullptr);
  337. }
  338. }
  339. if (m_current_file != File())
  340. {
  341. paramtree.setProperty("importedfile", m_current_file.getFullPathName(), nullptr);
  342. }
  343. MemoryOutputStream stream(destData,true);
  344. paramtree.writeToStream(stream);
  345. }
  346. void PaulstretchpluginAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
  347. {
  348. ValueTree tree = ValueTree::readFromData(data, sizeInBytes);
  349. if (tree.isValid())
  350. {
  351. {
  352. ScopedLock locker(m_cs);
  353. for (int i = 0; i < getNumParameters(); ++i)
  354. {
  355. auto par = getFloatParameter(i);
  356. if (par != nullptr)
  357. {
  358. double parval = tree.getProperty(par->paramID, (double)*par);
  359. *par = parval;
  360. }
  361. }
  362. }
  363. String fn = tree.getProperty("importedfile");
  364. if (fn.isEmpty() == false)
  365. {
  366. File f(fn);
  367. setAudioFile(f);
  368. }
  369. }
  370. }
  371. void PaulstretchpluginAudioProcessor::setRecordingEnabled(bool b)
  372. {
  373. ScopedLock locker(m_cs);
  374. int lenbufframes = getSampleRate()*m_max_reclen;
  375. if (b == true)
  376. {
  377. m_using_memory_buffer = true;
  378. m_current_file = File();
  379. m_recbuffer.setSize(2, m_max_reclen*getSampleRate()+4096);
  380. m_recbuffer.clear();
  381. m_rec_pos = 0;
  382. callGUI(this,[this,lenbufframes](PaulstretchpluginAudioProcessorEditor* ed)
  383. {
  384. ed->beginAddingAudioBlocks(2, getSampleRate(), lenbufframes);
  385. },false);
  386. m_is_recording = true;
  387. }
  388. else
  389. {
  390. if (m_is_recording == true)
  391. {
  392. finishRecording(lenbufframes);
  393. }
  394. }
  395. }
  396. double PaulstretchpluginAudioProcessor::getRecordingPositionPercent()
  397. {
  398. if (m_is_recording==false)
  399. return 0.0;
  400. return 1.0 / m_recbuffer.getNumSamples()*m_rec_pos;
  401. }
  402. String PaulstretchpluginAudioProcessor::setAudioFile(File f)
  403. {
  404. auto ai = unique_from_raw(m_afm->createReaderFor(f));
  405. if (ai != nullptr)
  406. {
  407. if (ai->numChannels > 32)
  408. {
  409. //MessageManager::callAsync([cb, file]() { cb("Too many channels in file " + file.getFullPathName()); });
  410. return "Too many channels in file "+f.getFullPathName();
  411. }
  412. if (ai->bitsPerSample>32)
  413. {
  414. //MessageManager::callAsync([cb, file]() { cb("Too high bit depth in file " + file.getFullPathName()); });
  415. return "Too high bit depth in file " + f.getFullPathName();
  416. }
  417. ScopedLock locker(m_cs);
  418. m_stretch_source->setAudioFile(f);
  419. m_current_file = f;
  420. m_using_memory_buffer = false;
  421. return String();
  422. //MessageManager::callAsync([cb, file]() { cb(String()); });
  423. }
  424. return "Could not open file " + f.getFullPathName();
  425. }
  426. Range<double> PaulstretchpluginAudioProcessor::getTimeSelection()
  427. {
  428. return { *getFloatParameter(5),*getFloatParameter(6) };
  429. }
  430. double PaulstretchpluginAudioProcessor::getPreBufferingPercent()
  431. {
  432. if (m_buffering_source==nullptr)
  433. return 0.0;
  434. return m_buffering_source->getPercentReady();
  435. }
  436. void PaulstretchpluginAudioProcessor::finishRecording(int lenrecording)
  437. {
  438. m_is_recording = false;
  439. m_stretch_source->setAudioBufferAsInputSource(&m_recbuffer, getSampleRate(), lenrecording);
  440. m_stretch_source->setPlayRange({ *getFloatParameter(5),*getFloatParameter(6) }, true);
  441. auto ed = dynamic_cast<PaulstretchpluginAudioProcessorEditor*>(getActiveEditor());
  442. if (ed)
  443. {
  444. //ed->setAudioBuffer(&m_recbuffer, getSampleRate(), lenrecording);
  445. }
  446. }
  447. //==============================================================================
  448. // This creates new instances of the plugin..
  449. AudioProcessor* JUCE_CALLTYPE createPluginFilter()
  450. {
  451. return new PaulstretchpluginAudioProcessor();
  452. }