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.

490 lines
15KB

  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", 1.0f, 5000.0f, 100.0f)); // 12
  89. }
  90. PaulstretchpluginAudioProcessor::~PaulstretchpluginAudioProcessor()
  91. {
  92. g_activeprocessors.erase(this);
  93. m_bufferingthread.stopThread(1000);
  94. }
  95. void PaulstretchpluginAudioProcessor::setPreBufferAmount(int x)
  96. {
  97. int temp = jlimit(0, 5, x);
  98. if (temp != m_prebuffer_amount)
  99. {
  100. m_prebuffer_amount = temp;
  101. m_recreate_buffering_source = true;
  102. }
  103. }
  104. //==============================================================================
  105. const String PaulstretchpluginAudioProcessor::getName() const
  106. {
  107. return JucePlugin_Name;
  108. }
  109. bool PaulstretchpluginAudioProcessor::acceptsMidi() const
  110. {
  111. #if JucePlugin_WantsMidiInput
  112. return true;
  113. #else
  114. return false;
  115. #endif
  116. }
  117. bool PaulstretchpluginAudioProcessor::producesMidi() const
  118. {
  119. #if JucePlugin_ProducesMidiOutput
  120. return true;
  121. #else
  122. return false;
  123. #endif
  124. }
  125. bool PaulstretchpluginAudioProcessor::isMidiEffect() const
  126. {
  127. #if JucePlugin_IsMidiEffect
  128. return true;
  129. #else
  130. return false;
  131. #endif
  132. }
  133. double PaulstretchpluginAudioProcessor::getTailLengthSeconds() const
  134. {
  135. return (double)m_bufamounts[m_prebuffer_amount]/getSampleRate();
  136. }
  137. int PaulstretchpluginAudioProcessor::getNumPrograms()
  138. {
  139. return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs,
  140. // so this should be at least 1, even if you're not really implementing programs.
  141. }
  142. int PaulstretchpluginAudioProcessor::getCurrentProgram()
  143. {
  144. return 0;
  145. }
  146. void PaulstretchpluginAudioProcessor::setCurrentProgram (int index)
  147. {
  148. }
  149. const String PaulstretchpluginAudioProcessor::getProgramName (int index)
  150. {
  151. return {};
  152. }
  153. void PaulstretchpluginAudioProcessor::changeProgramName (int index, const String& newName)
  154. {
  155. }
  156. void PaulstretchpluginAudioProcessor::setFFTSize(double size)
  157. {
  158. if (m_prebuffer_amount == 5)
  159. m_fft_size_to_use = pow(2, 7.0 + size * 14.5);
  160. else m_fft_size_to_use = pow(2, 7.0 + size * 10.0); // chicken out from allowing huge FFT sizes if not enough prebuffering
  161. int optim = optimizebufsize(m_fft_size_to_use);
  162. m_fft_size_to_use = optim;
  163. m_stretch_source->setFFTSize(optim);
  164. //Logger::writeToLog(String(m_fft_size_to_use));
  165. }
  166. void PaulstretchpluginAudioProcessor::startplay(Range<double> playrange, int numoutchans, String& err)
  167. {
  168. m_stretch_source->setPlayRange(playrange, true);
  169. int bufamt = m_bufamounts[m_prebuffer_amount];
  170. if (m_buffering_source != nullptr && numoutchans != m_buffering_source->getNumberOfChannels())
  171. m_recreate_buffering_source = true;
  172. if (m_recreate_buffering_source == true)
  173. {
  174. m_buffering_source = std::make_unique<MyBufferingAudioSource>(m_stretch_source.get(),
  175. m_bufferingthread, false, bufamt, numoutchans, false);
  176. m_recreate_buffering_source = false;
  177. }
  178. if (m_bufferingthread.isThreadRunning() == false)
  179. m_bufferingthread.startThread();
  180. m_stretch_source->setNumOutChannels(numoutchans);
  181. m_stretch_source->setFFTSize(m_fft_size_to_use);
  182. m_stretch_source->setProcessParameters(&m_ppar);
  183. m_last_outpos_pos = 0.0;
  184. m_last_in_pos = playrange.getStart()*m_stretch_source->getInfileLengthSeconds();
  185. m_buffering_source->prepareToPlay(1024, 44100.0);
  186. };
  187. void PaulstretchpluginAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)
  188. {
  189. std::lock_guard<std::mutex> locker(m_mutex);
  190. if (getNumOutputChannels() != m_cur_num_out_chans)
  191. m_ready_to_play = false;
  192. if (m_using_memory_buffer == true)
  193. {
  194. int len = jlimit(100,m_recbuffer.getNumSamples(), m_rec_pos);
  195. m_stretch_source->setAudioBufferAsInputSource(&m_recbuffer,
  196. getSampleRate(),
  197. len);
  198. callGUI(this,[this,len](auto ed) { ed->setAudioBuffer(&m_recbuffer, getSampleRate(), len); },false);
  199. }
  200. if (m_ready_to_play == false)
  201. {
  202. setFFTSize(*getFloatParameter(2));
  203. m_stretch_source->setProcessParameters(&m_ppar);
  204. String err;
  205. startplay({ *getFloatParameter(5),*getFloatParameter(6) },
  206. 2, err);
  207. m_cur_num_out_chans = getNumOutputChannels();
  208. m_ready_to_play = true;
  209. }
  210. }
  211. void PaulstretchpluginAudioProcessor::releaseResources()
  212. {
  213. //m_control->stopplay();
  214. //m_ready_to_play = false;
  215. }
  216. #ifndef JucePlugin_PreferredChannelConfigurations
  217. bool PaulstretchpluginAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const
  218. {
  219. #if JucePlugin_IsMidiEffect
  220. ignoreUnused (layouts);
  221. return true;
  222. #else
  223. // This is the place where you check if the layout is supported.
  224. // In this template code we only support mono or stereo.
  225. if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono()
  226. && layouts.getMainOutputChannelSet() != AudioChannelSet::stereo())
  227. return false;
  228. // This checks if the input layout matches the output layout
  229. #if ! JucePlugin_IsSynth
  230. if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
  231. return false;
  232. #endif
  233. return true;
  234. #endif
  235. }
  236. #endif
  237. void copyAudioBufferWrappingPosition(const AudioBuffer<float>& src, AudioBuffer<float>& dest, int destbufpos, int maxdestpos)
  238. {
  239. for (int i = 0; i < dest.getNumChannels(); ++i)
  240. {
  241. int channel_to_copy = i % src.getNumChannels();
  242. if (destbufpos + src.getNumSamples() > maxdestpos)
  243. {
  244. int wrappos = (destbufpos + src.getNumSamples()) % maxdestpos;
  245. int partial_len = src.getNumSamples() - wrappos;
  246. dest.copyFrom(channel_to_copy, destbufpos, src, channel_to_copy, 0, partial_len);
  247. dest.copyFrom(channel_to_copy, partial_len, src, channel_to_copy, 0, wrappos);
  248. }
  249. else
  250. {
  251. dest.copyFrom(channel_to_copy, destbufpos, src, channel_to_copy, 0, src.getNumSamples());
  252. }
  253. }
  254. }
  255. void PaulstretchpluginAudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  256. {
  257. std::lock_guard<std::mutex> locker(m_mutex);
  258. ScopedNoDenormals noDenormals;
  259. const int totalNumInputChannels = getTotalNumInputChannels();
  260. const int totalNumOutputChannels = getTotalNumOutputChannels();
  261. for (int i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
  262. buffer.clear (i, 0, buffer.getNumSamples());
  263. if (m_ready_to_play == false)
  264. return;
  265. if (m_is_recording == true)
  266. {
  267. int recbuflenframes = m_max_reclen * getSampleRate();
  268. copyAudioBufferWrappingPosition(buffer, m_recbuffer, m_rec_pos, recbuflenframes);
  269. callGUI(this,[this, &buffer](PaulstretchpluginAudioProcessorEditor*ed)
  270. {
  271. ed->addAudioBlock(buffer, getSampleRate(), m_rec_pos);
  272. }, false);
  273. m_rec_pos = (m_rec_pos + buffer.getNumSamples()) % recbuflenframes;
  274. return;
  275. }
  276. jassert(m_buffering_source != nullptr);
  277. jassert(m_bufferingthread.isThreadRunning());
  278. m_stretch_source->setMainVolume(*getFloatParameter(0));
  279. m_stretch_source->setRate(*getFloatParameter(1));
  280. setFFTSize(*getFloatParameter(2));
  281. m_ppar.pitch_shift.cents = *getFloatParameter(3) * 100.0;
  282. m_ppar.freq_shift.Hz = *getFloatParameter(4);
  283. m_ppar.spread.enabled = *getFloatParameter(8) > 0.0f;
  284. m_ppar.spread.bandwidth = *getFloatParameter(8);
  285. m_ppar.compressor.power = *getFloatParameter(9);
  286. m_ppar.harmonics.enabled = *getFloatParameter(11)>=1.0;
  287. m_ppar.harmonics.nharmonics = *getFloatParameter(11);
  288. m_ppar.harmonics.freq = *getFloatParameter(12);
  289. m_stretch_source->setLoopXFadeLength(*getFloatParameter(10));
  290. double t0 = *getFloatParameter(5);
  291. double t1 = *getFloatParameter(6);
  292. if (t0 > t1)
  293. std::swap(t0, t1);
  294. if (t1 - t0 < 0.001)
  295. t1 = t0 + 0.001;
  296. m_stretch_source->setPlayRange({ t0,t1 }, true);
  297. m_stretch_source->setFreezing(getParameter(7));
  298. m_stretch_source->setProcessParameters(&m_ppar);
  299. AudioSourceChannelInfo aif(buffer);
  300. m_buffering_source->getNextAudioBlock(aif);
  301. }
  302. //==============================================================================
  303. bool PaulstretchpluginAudioProcessor::hasEditor() const
  304. {
  305. return true; // (change this to false if you choose to not supply an editor)
  306. }
  307. AudioProcessorEditor* PaulstretchpluginAudioProcessor::createEditor()
  308. {
  309. return new PaulstretchpluginAudioProcessorEditor (*this);
  310. }
  311. //==============================================================================
  312. void PaulstretchpluginAudioProcessor::getStateInformation (MemoryBlock& destData)
  313. {
  314. ValueTree paramtree("paulstretch3pluginstate");
  315. for (int i=0;i<getNumParameters();++i)
  316. {
  317. auto par = getFloatParameter(i);
  318. if (par != nullptr)
  319. {
  320. paramtree.setProperty(par->paramID, (double)*par, nullptr);
  321. }
  322. }
  323. if (m_current_file != File())
  324. {
  325. paramtree.setProperty("importedfile", m_current_file.getFullPathName(), nullptr);
  326. }
  327. MemoryOutputStream stream(destData,true);
  328. paramtree.writeToStream(stream);
  329. }
  330. void PaulstretchpluginAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
  331. {
  332. ValueTree tree = ValueTree::readFromData(data, sizeInBytes);
  333. if (tree.isValid())
  334. {
  335. {
  336. std::lock_guard<std::mutex> locker(m_mutex);
  337. for (int i = 0; i < getNumParameters(); ++i)
  338. {
  339. auto par = getFloatParameter(i);
  340. if (par != nullptr)
  341. {
  342. double parval = tree.getProperty(par->paramID, (double)*par);
  343. *par = parval;
  344. }
  345. }
  346. }
  347. String fn = tree.getProperty("importedfile");
  348. if (fn.isEmpty() == false)
  349. {
  350. File f(fn);
  351. setAudioFile(f);
  352. }
  353. }
  354. }
  355. void PaulstretchpluginAudioProcessor::setRecordingEnabled(bool b)
  356. {
  357. std::lock_guard<std::mutex> locker(m_mutex);
  358. int lenbufframes = getSampleRate()*m_max_reclen;
  359. if (b == true)
  360. {
  361. m_using_memory_buffer = true;
  362. m_current_file = File();
  363. m_recbuffer.setSize(2, m_max_reclen*getSampleRate()+4096);
  364. m_recbuffer.clear();
  365. m_rec_pos = 0;
  366. callGUI(this,[this,lenbufframes](PaulstretchpluginAudioProcessorEditor* ed)
  367. {
  368. ed->beginAddingAudioBlocks(2, getSampleRate(), lenbufframes);
  369. },false);
  370. m_is_recording = true;
  371. }
  372. else
  373. {
  374. if (m_is_recording == true)
  375. {
  376. finishRecording(lenbufframes);
  377. }
  378. }
  379. }
  380. double PaulstretchpluginAudioProcessor::getRecordingPositionPercent()
  381. {
  382. if (m_is_recording==false)
  383. return 0.0;
  384. return 1.0 / m_recbuffer.getNumSamples()*m_rec_pos;
  385. }
  386. String PaulstretchpluginAudioProcessor::setAudioFile(File f)
  387. {
  388. auto ai = unique_from_raw(m_afm->createReaderFor(f));
  389. if (ai != nullptr)
  390. {
  391. if (ai->numChannels > 32)
  392. {
  393. //MessageManager::callAsync([cb, file]() { cb("Too many channels in file " + file.getFullPathName()); });
  394. return "Too many channels in file "+f.getFullPathName();
  395. }
  396. if (ai->bitsPerSample>32)
  397. {
  398. //MessageManager::callAsync([cb, file]() { cb("Too high bit depth in file " + file.getFullPathName()); });
  399. return "Too high bit depth in file " + f.getFullPathName();
  400. }
  401. std::lock_guard<std::mutex> locker(m_mutex);
  402. m_stretch_source->setAudioFile(f);
  403. m_current_file = f;
  404. m_using_memory_buffer = false;
  405. return String();
  406. //MessageManager::callAsync([cb, file]() { cb(String()); });
  407. }
  408. return "Could not open file " + f.getFullPathName();
  409. }
  410. Range<double> PaulstretchpluginAudioProcessor::getTimeSelection()
  411. {
  412. return { *getFloatParameter(5),*getFloatParameter(6) };
  413. }
  414. double PaulstretchpluginAudioProcessor::getPreBufferingPercent()
  415. {
  416. if (m_buffering_source==nullptr)
  417. return 0.0;
  418. return m_buffering_source->getPercentReady();
  419. }
  420. void PaulstretchpluginAudioProcessor::finishRecording(int lenrecording)
  421. {
  422. m_is_recording = false;
  423. m_stretch_source->setAudioBufferAsInputSource(&m_recbuffer, getSampleRate(), lenrecording);
  424. m_stretch_source->setPlayRange({ *getFloatParameter(5),*getFloatParameter(6) }, true);
  425. auto ed = dynamic_cast<PaulstretchpluginAudioProcessorEditor*>(getActiveEditor());
  426. if (ed)
  427. {
  428. //ed->setAudioBuffer(&m_recbuffer, getSampleRate(), lenrecording);
  429. }
  430. }
  431. //==============================================================================
  432. // This creates new instances of the plugin..
  433. AudioProcessor* JUCE_CALLTYPE createPluginFilter()
  434. {
  435. return new PaulstretchpluginAudioProcessor();
  436. }