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.

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