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.

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