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.

478 lines
14KB

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