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.

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