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.

912 lines
33KB

  1. /*
  2. Copyright (C) 2006-2011 Nasca Octavian Paul
  3. Author: Nasca Octavian Paul
  4. Copyright (C) 2017 Xenakios
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of version 2 of the GNU General Public License
  7. as published by the Free Software Foundation.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License (version 2) for more details.
  12. You should have received a copy of the GNU General Public License (version 2)
  13. along with this program; if not, write to the Free Software Foundation,
  14. Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  15. */
  16. #include "PluginProcessor.h"
  17. #include "PluginEditor.h"
  18. #include <set>
  19. #include <thread>
  20. #ifdef WIN32
  21. #undef min
  22. #undef max
  23. #endif
  24. String g_plugintitle{ "PaulXStretch 1.2.1" };
  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. inline AudioParameterFloat* make_floatpar(String id, String name, float minv, float maxv, float defv, float step, float skew)
  48. {
  49. return new AudioParameterFloat(id, name, NormalisableRange<float>(minv, maxv, step, skew), defv);
  50. }
  51. //==============================================================================
  52. PaulstretchpluginAudioProcessor::PaulstretchpluginAudioProcessor()
  53. : m_bufferingthread("pspluginprebufferthread")
  54. {
  55. m_playposinfo.timeInSeconds = 0.0;
  56. m_free_filter_envelope = std::make_shared<breakpoint_envelope>();
  57. m_free_filter_envelope->SetName("Free filter");
  58. m_free_filter_envelope->AddNode({ 0.0,0.75 });
  59. m_free_filter_envelope->AddNode({ 1.0,0.75 });
  60. m_free_filter_envelope->set_reset_nodes(m_free_filter_envelope->get_all_nodes());
  61. m_recbuffer.setSize(2, 44100);
  62. m_recbuffer.clear();
  63. if (m_afm->getNumKnownFormats()==0)
  64. m_afm->registerBasicFormats();
  65. m_thumb = std::make_unique<AudioThumbnail>(512, *m_afm, *m_thumbcache);
  66. // The default priority of 2 is a bit too low in some cases, it seems...
  67. m_thumbcache->getTimeSliceThread().setPriority(3);
  68. m_sm_enab_pars[0] = new AudioParameterBool("enab_specmodule0", "Enable harmonics", false);
  69. m_sm_enab_pars[1] = new AudioParameterBool("enab_specmodule1", "Enable tonal vs noise", false);
  70. m_sm_enab_pars[2] = new AudioParameterBool("enab_specmodule2", "Enable frequency shift", true);
  71. m_sm_enab_pars[3] = new AudioParameterBool("enab_specmodule3", "Enable pitch shift", true);
  72. m_sm_enab_pars[4] = new AudioParameterBool("enab_specmodule4", "Enable ratios", false);
  73. m_sm_enab_pars[5] = new AudioParameterBool("enab_specmodule5", "Enable spread", false);
  74. m_sm_enab_pars[6] = new AudioParameterBool("enab_specmodule6", "Enable filter", true);
  75. m_sm_enab_pars[7] = new AudioParameterBool("enab_specmodule7", "Enable free filter", true);
  76. m_sm_enab_pars[8] = new AudioParameterBool("enab_specmodule8", "Enable compressor", false);
  77. m_stretch_source = std::make_unique<StretchAudioSource>(2, m_afm,m_sm_enab_pars);
  78. m_stretch_source->setOnsetDetection(0.0);
  79. m_stretch_source->setLoopingEnabled(true);
  80. m_stretch_source->setFFTWindowingType(1);
  81. addParameter(make_floatpar("mainvolume0", "Main volume", -24.0, 12.0, -3.0, 0.1, 1.0));
  82. addParameter(make_floatpar("stretchamount0", "Stretch amount", 0.1, 1024.0, 2.0, 0.1, 0.25));
  83. addParameter(make_floatpar("fftsize0", "FFT size", 0.0, 1.0, 0.7, 0.01, 1.0));
  84. addParameter(make_floatpar("pitchshift0", "Pitch shift", -24.0f, 24.0f, 0.0f, 0.1,1.0)); // 3
  85. addParameter(make_floatpar("freqshift0", "Frequency shift", -1000.0f, 1000.0f, 0.0f, 1.0, 1.0)); // 4
  86. addParameter(make_floatpar("playrange_start0", "Sound start", 0.0f, 1.0f, 0.0f, 0.0001,1.0)); // 5
  87. addParameter(make_floatpar("playrange_end0", "Sound end", 0.0f, 1.0f, 1.0f, 0.0001,1.0)); // 6
  88. addParameter(new AudioParameterBool("freeze0", "Freeze", false)); // 7
  89. addParameter(make_floatpar("spread0", "Frequency spread", 0.0f, 1.0f, 0.0f, 0.001,1.0)); // 8
  90. addParameter(make_floatpar("compress0", "Compress", 0.0f, 1.0f, 0.0f, 0.001,1.0)); // 9
  91. addParameter(make_floatpar("loopxfadelen0", "Loop xfade length", 0.0f, 1.0f, 0.01f, 0.001, 1.0)); // 10
  92. addParameter(new AudioParameterInt("numharmonics0", "Num harmonics", 1, 100, 10)); // 11
  93. addParameter(make_floatpar("harmonicsfreq0", "Harmonics base freq", 1.0, 5000.0, 128.0, 0.1, 0.5));
  94. addParameter(make_floatpar("harmonicsbw0", "Harmonics bandwidth", 0.1f, 200.0f, 25.0f, 0.01, 1.0)); // 13
  95. addParameter(new AudioParameterBool("harmonicsgauss0", "Gaussian harmonics", false)); // 14
  96. addParameter(make_floatpar("octavemixm2_0", "2 octaves down level", 0.0f, 1.0f, 0.0f, 0.001, 1.0)); // 15
  97. addParameter(make_floatpar("octavemixm1_0", "Octave down level", 0.0f, 1.0f, 0.0f, 0.001, 1.0)); // 16
  98. addParameter(make_floatpar("octavemix0_0", "Normal pitch level", 0.0f, 1.0f, 1.0f, 0.001, 1.0)); // 17
  99. addParameter(make_floatpar("octavemix1_0", "1 octave up level", 0.0f, 1.0f, 0.0f, 0.001, 1.0)); // 18
  100. addParameter(make_floatpar("octavemix15_0", "1 octave and fifth up level", 0.0f, 1.0f, 0.0f, 0.001, 1.0)); // 19
  101. addParameter(make_floatpar("octavemix2_0", "2 octaves up level", 0.0f, 1.0f, 0.0f, 0.001, 1.0)); // 20
  102. addParameter(make_floatpar("tonalvsnoisebw_0", "Tonal vs Noise BW", 0.74f, 1.0f, 0.74f, 0.001, 1.0)); // 21
  103. addParameter(make_floatpar("tonalvsnoisepreserve_0", "Tonal vs Noise preserve", -1.0f, 1.0f, 0.5f, 0.001, 1.0)); // 22
  104. auto filt_convertFrom0To1Func = [](float rangemin, float rangemax, float value)
  105. {
  106. if (value < 0.5f)
  107. return jmap<float>(value, 0.0f, 0.5f, 20.0f, 1000.0f);
  108. return jmap<float>(value, 0.5f, 1.0f, 1000.0f, 20000.0f);
  109. };
  110. auto filt_convertTo0To1Func = [](float rangemin, float rangemax, float value)
  111. {
  112. if (value < 1000.0f)
  113. return jmap<float>(value, 20.0f, 1000.0f, 0.0f, 0.5f);
  114. return jmap<float>(value, 1000.0f, 20000.0f, 0.5f, 1.0f);
  115. };
  116. addParameter(new AudioParameterFloat("filter_low_0", "Filter low",
  117. NormalisableRange<float>(20.0f, 20000.0f,
  118. filt_convertFrom0To1Func, filt_convertTo0To1Func), 20.0f)); // 23
  119. addParameter(new AudioParameterFloat("filter_high_0", "Filter high",
  120. NormalisableRange<float>(20.0f, 20000.0f,
  121. filt_convertFrom0To1Func,filt_convertTo0To1Func), 20000.0f));; // 24
  122. addParameter(make_floatpar("onsetdetect_0", "Onset detection", 0.0f, 1.0f, 0.0f, 0.01, 1.0)); // 25
  123. addParameter(new AudioParameterBool("capture_enabled0", "Capture", false)); // 26
  124. m_outchansparam = new AudioParameterInt("numoutchans0", "Num outs", 2, 8, 2); // 27
  125. addParameter(m_outchansparam); // 27
  126. addParameter(new AudioParameterBool("pause_enabled0", "Pause", false)); // 28
  127. addParameter(new AudioParameterFloat("maxcapturelen_0", "Max capture length", 1.0f, 120.0f, 10.0f)); // 29
  128. addParameter(new AudioParameterBool("passthrough0", "Pass input through", false)); // 30
  129. addParameter(new AudioParameterBool("markdirty0", "Internal (don't use)", false)); // 31
  130. m_inchansparam = new AudioParameterInt("numinchans0", "Num ins", 2, 8, 2); // 32
  131. addParameter(m_inchansparam); // 32
  132. addParameter(new AudioParameterBool("bypass_stretch0", "Bypass stretch", false)); // 33
  133. addParameter(new AudioParameterFloat("freefilter_shiftx_0", "Free filter shift X", -1.0f, 1.0f, 0.0f)); // 34
  134. addParameter(new AudioParameterFloat("freefilter_shifty_0", "Free filter shift Y", -1.0f, 1.0f, 0.0f)); // 35
  135. addParameter(new AudioParameterFloat("freefilter_scaley_0", "Free filter scale Y", -1.0f, 1.0f, 1.0f)); // 36
  136. addParameter(new AudioParameterFloat("freefilter_tilty_0", "Free filter tilt Y", -1.0f, 1.0f, 0.0f)); // 37
  137. addParameter(new AudioParameterInt("freefilter_randomybands0", "Random bands", 2, 128, 16)); // 38
  138. addParameter(new AudioParameterInt("freefilter_randomyrate0", "Random rate", 1, 32, 2)); // 39
  139. addParameter(new AudioParameterFloat("freefilter_randomyamount0", "Random amount", 0.0, 1.0, 0.0)); // 40
  140. for (int i = 0; i < 9; ++i) // 41-49
  141. {
  142. addParameter(m_sm_enab_pars[i]);
  143. m_sm_enab_pars[i]->addListener(this);
  144. }
  145. addParameter(make_floatpar("octavemix_extra0_0", "Ratio mix 7 level", 0.0f, 1.0f, 0.0f, 0.001, 1.0)); // 50
  146. addParameter(make_floatpar("octavemix_extra1_0", "Ratio mix 8 level", 0.0f, 1.0f, 0.0f, 0.001, 1.0)); // 51
  147. std::array<double,8> initialratios{ 0.25,0.5,1.0,2.0,3.0,4.0,1.5,1.0 / 1.5 };
  148. // 52-59
  149. for (int i = 0; i < 8; ++i)
  150. {
  151. addParameter(make_floatpar("ratiomix_ratio_"+String(i)+"_0", "Ratio mix ratio "+String(i+1), 0.125f, 8.0f,
  152. initialratios[i],
  153. 0.001,
  154. 1.0));
  155. }
  156. addParameter(new AudioParameterBool("loop_enabled0", "Loop", true)); // 60
  157. auto& pars = getParameters();
  158. for (const auto& p : pars)
  159. m_reset_pars.push_back(p->getValue());
  160. setPreBufferAmount(2);
  161. startTimer(1, 50);
  162. m_show_technical_info = m_propsfile->m_props_file->getBoolValue("showtechnicalinfo", false);
  163. }
  164. PaulstretchpluginAudioProcessor::~PaulstretchpluginAudioProcessor()
  165. {
  166. m_thumb->removeAllChangeListeners();
  167. m_thumb = nullptr;
  168. m_bufferingthread.stopThread(1000);
  169. }
  170. void PaulstretchpluginAudioProcessor::resetParameters()
  171. {
  172. ScopedLock locker(m_cs);
  173. for (int i = 0; i < m_reset_pars.size(); ++i)
  174. {
  175. if (i!=cpi_main_volume && i!=cpi_passthrough)
  176. setParameter(i, m_reset_pars[i]);
  177. }
  178. }
  179. void PaulstretchpluginAudioProcessor::setPreBufferAmount(int x)
  180. {
  181. int temp = jlimit(0, 5, x);
  182. if (temp != m_prebuffer_amount || m_use_backgroundbuffering == false)
  183. {
  184. m_use_backgroundbuffering = true;
  185. m_prebuffer_amount = temp;
  186. m_recreate_buffering_source = true;
  187. ScopedLock locker(m_cs);
  188. m_prebuffering_inited = false;
  189. m_cur_num_out_chans = *m_outchansparam;
  190. //Logger::writeToLog("Switching to use " + String(m_cur_num_out_chans) + " out channels");
  191. String err;
  192. startplay({ *getFloatParameter(cpi_soundstart),*getFloatParameter(cpi_soundend) },
  193. m_cur_num_out_chans, m_curmaxblocksize, err);
  194. m_prebuffering_inited = true;
  195. }
  196. }
  197. int PaulstretchpluginAudioProcessor::getPreBufferAmount()
  198. {
  199. if (m_use_backgroundbuffering == false)
  200. return -1;
  201. return m_prebuffer_amount;
  202. }
  203. ValueTree PaulstretchpluginAudioProcessor::getStateTree(bool ignoreoptions, bool ignorefile)
  204. {
  205. ValueTree paramtree("paulstretch3pluginstate");
  206. storeToTreeProperties(paramtree, nullptr, getParameters());
  207. if (m_current_file != File() && ignorefile == false)
  208. {
  209. paramtree.setProperty("importedfile", m_current_file.getFullPathName(), nullptr);
  210. }
  211. auto specorder = m_stretch_source->getSpectrumProcessOrder();
  212. paramtree.setProperty("numspectralstagesb", (int)specorder.size(), nullptr);
  213. for (int i = 0; i < specorder.size(); ++i)
  214. {
  215. paramtree.setProperty("specorderb" + String(i), specorder[i].m_index, nullptr);
  216. }
  217. if (ignoreoptions == false)
  218. {
  219. if (m_use_backgroundbuffering)
  220. paramtree.setProperty("prebufamount", m_prebuffer_amount, nullptr);
  221. else
  222. paramtree.setProperty("prebufamount", -1, nullptr);
  223. paramtree.setProperty("loadfilewithstate", m_load_file_with_state, nullptr);
  224. storeToTreeProperties(paramtree, nullptr, "playwhenhostrunning", m_play_when_host_plays, "capturewhenhostrunning", m_capture_when_host_plays);
  225. }
  226. storeToTreeProperties(paramtree, nullptr, "waveviewrange", m_wave_view_range);
  227. ValueTree freefilterstate = m_free_filter_envelope->saveState(Identifier("freefilter_envelope"));
  228. paramtree.addChild(freefilterstate, -1, nullptr);
  229. return paramtree;
  230. }
  231. void PaulstretchpluginAudioProcessor::setStateFromTree(ValueTree tree)
  232. {
  233. if (tree.isValid())
  234. {
  235. {
  236. ScopedLock locker(m_cs);
  237. ValueTree freefilterstate = tree.getChildWithName("freefilter_envelope");
  238. m_free_filter_envelope->restoreState(freefilterstate);
  239. m_load_file_with_state = tree.getProperty("loadfilewithstate", true);
  240. getFromTreeProperties(tree, "playwhenhostrunning", m_play_when_host_plays, "capturewhenhostrunning", m_capture_when_host_plays);
  241. if (tree.hasProperty("numspectralstagesb"))
  242. {
  243. std::vector<SpectrumProcess> old_order = m_stretch_source->getSpectrumProcessOrder();
  244. std::vector<SpectrumProcess> new_order;
  245. int ordersize = tree.getProperty("numspectralstagesb");
  246. if (ordersize == old_order.size())
  247. {
  248. for (int i = 0; i < ordersize; ++i)
  249. {
  250. int index = tree.getProperty("specorderb" + String(i));
  251. new_order.push_back({ index, old_order[index].m_enabled });
  252. }
  253. m_stretch_source->setSpectrumProcessOrder(new_order);
  254. }
  255. }
  256. getFromTreeProperties(tree, "waveviewrange", m_wave_view_range);
  257. getFromTreeProperties(tree, getParameters());
  258. }
  259. int prebufamt = tree.getProperty("prebufamount", 2);
  260. if (prebufamt == -1)
  261. m_use_backgroundbuffering = false;
  262. else
  263. setPreBufferAmount(prebufamt);
  264. if (m_load_file_with_state == true)
  265. {
  266. String fn = tree.getProperty("importedfile");
  267. if (fn.isEmpty() == false)
  268. {
  269. File f(fn);
  270. setAudioFile(f);
  271. }
  272. }
  273. m_state_dirty = true;
  274. }
  275. }
  276. //==============================================================================
  277. const String PaulstretchpluginAudioProcessor::getName() const
  278. {
  279. return JucePlugin_Name;
  280. }
  281. bool PaulstretchpluginAudioProcessor::acceptsMidi() const
  282. {
  283. #if JucePlugin_WantsMidiInput
  284. return true;
  285. #else
  286. return false;
  287. #endif
  288. }
  289. bool PaulstretchpluginAudioProcessor::producesMidi() const
  290. {
  291. #if JucePlugin_ProducesMidiOutput
  292. return true;
  293. #else
  294. return false;
  295. #endif
  296. }
  297. bool PaulstretchpluginAudioProcessor::isMidiEffect() const
  298. {
  299. #if JucePlugin_IsMidiEffect
  300. return true;
  301. #else
  302. return false;
  303. #endif
  304. }
  305. double PaulstretchpluginAudioProcessor::getTailLengthSeconds() const
  306. {
  307. return 0.0;
  308. //return (double)m_bufamounts[m_prebuffer_amount]/getSampleRate();
  309. }
  310. int PaulstretchpluginAudioProcessor::getNumPrograms()
  311. {
  312. return 1;
  313. }
  314. int PaulstretchpluginAudioProcessor::getCurrentProgram()
  315. {
  316. return 0;
  317. }
  318. void PaulstretchpluginAudioProcessor::setCurrentProgram (int index)
  319. {
  320. }
  321. const String PaulstretchpluginAudioProcessor::getProgramName (int index)
  322. {
  323. return String();
  324. }
  325. void PaulstretchpluginAudioProcessor::changeProgramName (int index, const String& newName)
  326. {
  327. }
  328. void PaulstretchpluginAudioProcessor::parameterValueChanged(int parameterIndex, float newValue)
  329. {
  330. if (parameterIndex >= cpi_enable_spec_module0 && parameterIndex <= cpi_enable_spec_module8)
  331. {
  332. m_stretch_source->setSpectralModuleEnabled(parameterIndex - cpi_enable_spec_module0, newValue >= 0.5);
  333. }
  334. }
  335. void PaulstretchpluginAudioProcessor::parameterGestureChanged(int parameterIndex, bool gestureIsStarting)
  336. {
  337. }
  338. void PaulstretchpluginAudioProcessor::setFFTSize(double size)
  339. {
  340. if (m_prebuffer_amount == 5)
  341. m_fft_size_to_use = pow(2, 7.0 + size * 14.5);
  342. else m_fft_size_to_use = pow(2, 7.0 + size * 10.0); // chicken out from allowing huge FFT sizes if not enough prebuffering
  343. int optim = optimizebufsize(m_fft_size_to_use);
  344. m_fft_size_to_use = optim;
  345. m_stretch_source->setFFTSize(optim);
  346. //Logger::writeToLog(String(m_fft_size_to_use));
  347. }
  348. void PaulstretchpluginAudioProcessor::startplay(Range<double> playrange, int numoutchans, int maxBlockSize, String& err)
  349. {
  350. m_stretch_source->setPlayRange(playrange, true);
  351. m_stretch_source->setFreeFilterEnvelope(m_free_filter_envelope);
  352. int bufamt = m_bufamounts[m_prebuffer_amount];
  353. if (m_buffering_source != nullptr && numoutchans != m_buffering_source->getNumberOfChannels())
  354. m_recreate_buffering_source = true;
  355. if (m_recreate_buffering_source == true)
  356. {
  357. m_buffering_source = std::make_unique<MyBufferingAudioSource>(m_stretch_source.get(),
  358. m_bufferingthread, false, bufamt, numoutchans, false);
  359. m_recreate_buffering_source = false;
  360. }
  361. if (m_bufferingthread.isThreadRunning() == false)
  362. m_bufferingthread.startThread();
  363. m_stretch_source->setNumOutChannels(numoutchans);
  364. m_stretch_source->setFFTSize(m_fft_size_to_use);
  365. m_stretch_source->setProcessParameters(&m_ppar);
  366. m_last_outpos_pos = 0.0;
  367. m_last_in_pos = playrange.getStart()*m_stretch_source->getInfileLengthSeconds();
  368. m_buffering_source->prepareToPlay(maxBlockSize, getSampleRateChecked());
  369. }
  370. void PaulstretchpluginAudioProcessor::setParameters(const std::vector<double>& pars)
  371. {
  372. ScopedLock locker(m_cs);
  373. for (int i = 0; i < getNumParameters(); ++i)
  374. {
  375. if (i<pars.size())
  376. setParameter(i, pars[i]);
  377. }
  378. }
  379. void PaulstretchpluginAudioProcessor::updateStretchParametersFromPluginParameters(ProcessParameters & pars)
  380. {
  381. pars.pitch_shift.cents = *getFloatParameter(cpi_pitchshift) * 100.0;
  382. pars.freq_shift.Hz = *getFloatParameter(cpi_frequencyshift);
  383. pars.spread.bandwidth = *getFloatParameter(cpi_spreadamount);
  384. pars.compressor.power = *getFloatParameter(cpi_compress);
  385. pars.harmonics.nharmonics = *getIntParameter(cpi_numharmonics);
  386. pars.harmonics.freq = *getFloatParameter(cpi_harmonicsfreq);
  387. pars.harmonics.bandwidth = *getFloatParameter(cpi_harmonicsbw);
  388. pars.harmonics.gauss = getParameter(cpi_harmonicsgauss);
  389. pars.octave.om2 = *getFloatParameter(cpi_octavesm2);
  390. pars.octave.om1 = *getFloatParameter(cpi_octavesm1);
  391. pars.octave.o0 = *getFloatParameter(cpi_octaves0);
  392. pars.octave.o1 = *getFloatParameter(cpi_octaves1);
  393. pars.octave.o15 = *getFloatParameter(cpi_octaves15);
  394. pars.octave.o2 = *getFloatParameter(cpi_octaves2);
  395. pars.ratiomix.ratiolevels[0]= *getFloatParameter(cpi_octavesm2);
  396. pars.ratiomix.ratiolevels[1] = *getFloatParameter(cpi_octavesm1);
  397. pars.ratiomix.ratiolevels[2] = *getFloatParameter(cpi_octaves0);
  398. pars.ratiomix.ratiolevels[3] = *getFloatParameter(cpi_octaves1);
  399. pars.ratiomix.ratiolevels[4] = *getFloatParameter(cpi_octaves15);
  400. pars.ratiomix.ratiolevels[5] = *getFloatParameter(cpi_octaves2);
  401. pars.ratiomix.ratiolevels[6] = *getFloatParameter(cpi_octaves_extra1);
  402. pars.ratiomix.ratiolevels[7] = *getFloatParameter(cpi_octaves_extra2);
  403. for (int i = 0; i < 8; ++i)
  404. pars.ratiomix.ratios[i] = *getFloatParameter((int)cpi_octaves_ratio0 + i);
  405. pars.filter.low = *getFloatParameter(cpi_filter_low);
  406. pars.filter.high = *getFloatParameter(cpi_filter_high);
  407. pars.tonal_vs_noise.bandwidth = *getFloatParameter(cpi_tonalvsnoisebw);
  408. pars.tonal_vs_noise.preserve = *getFloatParameter(cpi_tonalvsnoisepreserve);
  409. }
  410. String PaulstretchpluginAudioProcessor::offlineRender(File outputfile)
  411. {
  412. File outputfiletouse = outputfile.getNonexistentSibling();
  413. int numoutchans = *getIntParameter(cpi_num_outchans);
  414. auto ss = std::make_shared<StretchAudioSource>(numoutchans,m_afm,m_sm_enab_pars);
  415. int blocksize = 2048;
  416. ss->setAudioFile(m_current_file);
  417. ProcessParameters renderpars;
  418. updateStretchParametersFromPluginParameters(renderpars);
  419. ss->setProcessParameters(&renderpars);
  420. double t0 = *getFloatParameter(cpi_soundstart);
  421. double t1 = *getFloatParameter(cpi_soundend);
  422. sanitizeTimeRange(t0, t1);
  423. ss->setRate(*getFloatParameter(cpi_stretchamount));
  424. ss->setPlayRange({ t0,t1 }, true);
  425. ss->setLoopingEnabled(true);
  426. ss->setNumOutChannels(numoutchans);
  427. ss->setFFTWindowingType(1);
  428. //ss->setPreviewDry(true);
  429. ss->setOnsetDetection(*getFloatParameter(cpi_onsetdetection));
  430. ss->setLoopXFadeLength(*getFloatParameter(cpi_loopxfadelen));
  431. ss->setFreezing(getParameter(cpi_freeze));
  432. ss->setPaused(getParameter(cpi_pause_enabled));
  433. ss->setSpectrumProcessOrder(m_stretch_source->getSpectrumProcessOrder());
  434. ss->setFFTSize(m_fft_size_to_use);
  435. ss->setMainVolume(*getFloatParameter(cpi_main_volume));
  436. double outsr = getSampleRateChecked();
  437. ss->prepareToPlay(blocksize, outsr);
  438. WavAudioFormat wavformat;
  439. FileOutputStream* outstream = outputfiletouse.createOutputStream();
  440. if (outstream == nullptr)
  441. return "Could not create output file";
  442. auto writer = wavformat.createWriterFor(outstream, getSampleRateChecked(), numoutchans, 32, StringPairArray(), 0);
  443. if (writer == nullptr)
  444. {
  445. delete outstream;
  446. return "Could not create WAV writer";
  447. }
  448. auto rendertask = [ss,writer,blocksize,numoutchans, outsr, this]()
  449. {
  450. AudioBuffer<float> renderbuffer(numoutchans, blocksize);
  451. int64_t outlen = 250 * outsr;
  452. int64_t outcounter = 0;
  453. AudioSourceChannelInfo asci(renderbuffer);
  454. m_offline_render_state = 0;
  455. m_offline_render_cancel_requested = false;
  456. while (outcounter < outlen)
  457. {
  458. if (m_offline_render_cancel_requested == true)
  459. break;
  460. ss->getNextAudioBlock(asci);
  461. writer->writeFromAudioSampleBuffer(renderbuffer, 0, blocksize);
  462. outcounter += blocksize;
  463. m_offline_render_state = 100.0 / outlen * outcounter;
  464. }
  465. m_offline_render_state = 200;
  466. delete writer;
  467. };
  468. std::thread th(rendertask);
  469. th.detach();
  470. return "Rendered OK";
  471. }
  472. double PaulstretchpluginAudioProcessor::getSampleRateChecked()
  473. {
  474. if (m_cur_sr < 1.0 || m_cur_sr>1000000.0)
  475. return 44100.0;
  476. return m_cur_sr;
  477. }
  478. void PaulstretchpluginAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)
  479. {
  480. ++m_prepare_count;
  481. ScopedLock locker(m_cs);
  482. m_cur_sr = sampleRate;
  483. m_curmaxblocksize = samplesPerBlock;
  484. m_input_buffer.setSize(getMainBusNumInputChannels(), samplesPerBlock);
  485. int numoutchans = *m_outchansparam;
  486. if (numoutchans != m_cur_num_out_chans)
  487. m_prebuffering_inited = false;
  488. if (m_using_memory_buffer == true)
  489. {
  490. int len = jlimit(100,m_recbuffer.getNumSamples(),
  491. int(getSampleRateChecked()*(*getFloatParameter(cpi_max_capture_len))));
  492. m_stretch_source->setAudioBufferAsInputSource(&m_recbuffer,
  493. getSampleRateChecked(),
  494. len);
  495. //m_thumb->reset(m_recbuffer.getNumChannels(), sampleRate, len);
  496. }
  497. if (m_prebuffering_inited == false)
  498. {
  499. setFFTSize(*getFloatParameter(cpi_fftsize));
  500. m_stretch_source->setProcessParameters(&m_ppar);
  501. m_stretch_source->setFFTWindowingType(1);
  502. String err;
  503. startplay({ *getFloatParameter(cpi_soundstart),*getFloatParameter(cpi_soundend) },
  504. numoutchans, samplesPerBlock, err);
  505. m_cur_num_out_chans = numoutchans;
  506. m_prebuffering_inited = true;
  507. }
  508. else
  509. {
  510. m_buffering_source->prepareToPlay(samplesPerBlock, getSampleRateChecked());
  511. }
  512. }
  513. void PaulstretchpluginAudioProcessor::releaseResources()
  514. {
  515. //m_control->stopplay();
  516. //m_ready_to_play = false;
  517. }
  518. #ifndef JucePlugin_PreferredChannelConfigurations
  519. bool PaulstretchpluginAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const
  520. {
  521. #if JucePlugin_IsMidiEffect
  522. ignoreUnused (layouts);
  523. return true;
  524. #else
  525. // This is the place where you check if the layout is supported.
  526. // In this template code we only support mono or stereo.
  527. if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono()
  528. && layouts.getMainOutputChannelSet() != AudioChannelSet::stereo())
  529. return false;
  530. // This checks if the input layout matches the output layout
  531. #if ! JucePlugin_IsSynth
  532. if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
  533. return false;
  534. #endif
  535. return true;
  536. #endif
  537. }
  538. #endif
  539. void copyAudioBufferWrappingPosition(const AudioBuffer<float>& src, AudioBuffer<float>& dest, int destbufpos, int maxdestpos)
  540. {
  541. for (int i = 0; i < dest.getNumChannels(); ++i)
  542. {
  543. int channel_to_copy = i % src.getNumChannels();
  544. if (destbufpos + src.getNumSamples() > maxdestpos)
  545. {
  546. int wrappos = (destbufpos + src.getNumSamples()) % maxdestpos;
  547. int partial_len = src.getNumSamples() - wrappos;
  548. dest.copyFrom(channel_to_copy, destbufpos, src, channel_to_copy, 0, partial_len);
  549. dest.copyFrom(channel_to_copy, partial_len, src, channel_to_copy, 0, wrappos);
  550. }
  551. else
  552. {
  553. dest.copyFrom(channel_to_copy, destbufpos, src, channel_to_copy, 0, src.getNumSamples());
  554. }
  555. }
  556. }
  557. /*
  558. void PaulstretchpluginAudioProcessor::processBlock (AudioBuffer<double>& buffer, MidiBuffer&)
  559. {
  560. jassert(false);
  561. }
  562. */
  563. void PaulstretchpluginAudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  564. {
  565. ScopedLock locker(m_cs);
  566. AudioPlayHead* phead = getPlayHead();
  567. if (phead != nullptr)
  568. {
  569. phead->getCurrentPosition(m_playposinfo);
  570. }
  571. else
  572. m_playposinfo.isPlaying = false;
  573. ScopedNoDenormals noDenormals;
  574. double srtemp = getSampleRate();
  575. if (srtemp != m_cur_sr)
  576. m_cur_sr = srtemp;
  577. m_prebufsmoother.setSlope(0.9, srtemp / buffer.getNumSamples());
  578. m_smoothed_prebuffer_ready = m_prebufsmoother.process(m_buffering_source->getPercentReady());
  579. const int totalNumInputChannels = getTotalNumInputChannels();
  580. const int totalNumOutputChannels = getTotalNumOutputChannels();
  581. for (int i = 0; i < totalNumInputChannels; ++i)
  582. m_input_buffer.copyFrom(i, 0, buffer, i, 0, buffer.getNumSamples());
  583. for (int i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
  584. buffer.clear (i, 0, buffer.getNumSamples());
  585. if (m_prebuffering_inited == false)
  586. return;
  587. if (m_is_recording == true)
  588. {
  589. if (m_playposinfo.isPlaying == false && m_capture_when_host_plays == true)
  590. return;
  591. int recbuflenframes = m_max_reclen * getSampleRate();
  592. copyAudioBufferWrappingPosition(buffer, m_recbuffer, m_rec_pos, recbuflenframes);
  593. m_thumb->addBlock(m_rec_pos, buffer, 0, buffer.getNumSamples());
  594. m_rec_pos = (m_rec_pos + buffer.getNumSamples()) % recbuflenframes;
  595. return;
  596. }
  597. jassert(m_buffering_source != nullptr);
  598. jassert(m_bufferingthread.isThreadRunning());
  599. if (m_last_host_playing == false && m_playposinfo.isPlaying)
  600. {
  601. m_stretch_source->seekPercent(*getFloatParameter(cpi_soundstart));
  602. m_last_host_playing = true;
  603. }
  604. else if (m_last_host_playing == true && m_playposinfo.isPlaying == false)
  605. {
  606. m_last_host_playing = false;
  607. }
  608. if (m_play_when_host_plays == true && m_playposinfo.isPlaying == false)
  609. return;
  610. m_free_filter_envelope->m_transform_x_shift = *getFloatParameter(cpi_freefilter_shiftx);
  611. m_free_filter_envelope->m_transform_y_shift = *getFloatParameter(cpi_freefilter_shifty);
  612. m_free_filter_envelope->m_transform_y_scale = *getFloatParameter(cpi_freefilter_scaley);
  613. m_free_filter_envelope->m_transform_y_tilt = *getFloatParameter(cpi_freefilter_tilty);
  614. m_free_filter_envelope->m_transform_y_random_bands = *getIntParameter(cpi_freefilter_randomy_numbands);
  615. m_free_filter_envelope->m_transform_y_random_rate = *getIntParameter(cpi_freefilter_randomy_rate);
  616. m_free_filter_envelope->m_transform_y_random_amount = *getFloatParameter(cpi_freefilter_randomy_amount);
  617. //m_stretch_source->setSpectralModulesEnabled(m_sm_enab_pars);
  618. if (m_stretch_source->isLoopEnabled() != *getBoolParameter(cpi_looping_enabled))
  619. m_stretch_source->setLoopingEnabled(*getBoolParameter(cpi_looping_enabled));
  620. m_stretch_source->setMainVolume(*getFloatParameter(cpi_main_volume));
  621. m_stretch_source->setRate(*getFloatParameter(cpi_stretchamount));
  622. m_stretch_source->setPreviewDry(*getBoolParameter(cpi_bypass_stretch));
  623. setFFTSize(*getFloatParameter(cpi_fftsize));
  624. updateStretchParametersFromPluginParameters(m_ppar);
  625. m_stretch_source->setOnsetDetection(*getFloatParameter(cpi_onsetdetection));
  626. m_stretch_source->setLoopXFadeLength(*getFloatParameter(cpi_loopxfadelen));
  627. double t0 = *getFloatParameter(cpi_soundstart);
  628. double t1 = *getFloatParameter(cpi_soundend);
  629. sanitizeTimeRange(t0, t1);
  630. m_stretch_source->setPlayRange({ t0,t1 }, true);
  631. m_stretch_source->setFreezing(getParameter(cpi_freeze));
  632. m_stretch_source->setPaused(getParameter(cpi_pause_enabled));
  633. m_stretch_source->setProcessParameters(&m_ppar);
  634. AudioSourceChannelInfo aif(buffer);
  635. if (isNonRealtime() || m_use_backgroundbuffering == false)
  636. {
  637. m_stretch_source->getNextAudioBlock(aif);
  638. }
  639. else
  640. {
  641. m_buffering_source->getNextAudioBlock(aif);
  642. }
  643. if (getParameter(cpi_passthrough) > 0.5f)
  644. {
  645. for (int i = 0; i < totalNumInputChannels; ++i)
  646. {
  647. buffer.addFrom(i, 0, m_input_buffer, i, 0, buffer.getNumSamples());
  648. }
  649. }
  650. for (int i = 0; i < buffer.getNumChannels(); ++i)
  651. {
  652. for (int j = 0; j < buffer.getNumSamples(); ++j)
  653. {
  654. float sample = buffer.getSample(i,j);
  655. if (std::isnan(sample) || std::isinf(sample))
  656. ++m_abnormal_output_samples;
  657. }
  658. }
  659. }
  660. //==============================================================================
  661. bool PaulstretchpluginAudioProcessor::hasEditor() const
  662. {
  663. return true; // (change this to false if you choose to not supply an editor)
  664. }
  665. AudioProcessorEditor* PaulstretchpluginAudioProcessor::createEditor()
  666. {
  667. return new PaulstretchpluginAudioProcessorEditor (*this);
  668. }
  669. //==============================================================================
  670. void PaulstretchpluginAudioProcessor::getStateInformation (MemoryBlock& destData)
  671. {
  672. ValueTree paramtree = getStateTree(false,false);
  673. MemoryOutputStream stream(destData,true);
  674. paramtree.writeToStream(stream);
  675. }
  676. void PaulstretchpluginAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
  677. {
  678. ValueTree tree = ValueTree::readFromData(data, sizeInBytes);
  679. setStateFromTree(tree);
  680. }
  681. void PaulstretchpluginAudioProcessor::setDirty()
  682. {
  683. toggleBool(getBoolParameter(cpi_markdirty));
  684. }
  685. void PaulstretchpluginAudioProcessor::setRecordingEnabled(bool b)
  686. {
  687. ScopedLock locker(m_cs);
  688. int lenbufframes = getSampleRateChecked()*m_max_reclen;
  689. if (b == true)
  690. {
  691. m_using_memory_buffer = true;
  692. m_current_file = File();
  693. int numchans = *m_inchansparam;
  694. m_recbuffer.setSize(numchans, m_max_reclen*getSampleRateChecked()+4096,false,false,true);
  695. m_recbuffer.clear();
  696. m_rec_pos = 0;
  697. m_thumb->reset(m_recbuffer.getNumChannels(), getSampleRateChecked(), lenbufframes);
  698. m_is_recording = true;
  699. }
  700. else
  701. {
  702. if (m_is_recording == true)
  703. {
  704. finishRecording(lenbufframes);
  705. }
  706. }
  707. }
  708. double PaulstretchpluginAudioProcessor::getRecordingPositionPercent()
  709. {
  710. if (m_is_recording==false)
  711. return 0.0;
  712. return 1.0 / m_recbuffer.getNumSamples()*m_rec_pos;
  713. }
  714. String PaulstretchpluginAudioProcessor::setAudioFile(File f)
  715. {
  716. auto ai = unique_from_raw(m_afm->createReaderFor(f));
  717. if (ai != nullptr)
  718. {
  719. if (ai->numChannels > 8)
  720. {
  721. return "Too many channels in file "+f.getFullPathName();
  722. }
  723. if (ai->bitsPerSample>32)
  724. {
  725. return "Too high bit depth in file " + f.getFullPathName();
  726. }
  727. m_thumb->setSource(new FileInputSource(f));
  728. ScopedLock locker(m_cs);
  729. m_stretch_source->setAudioFile(f);
  730. //Range<double> currange{ *getFloatParameter(cpi_soundstart),*getFloatParameter(cpi_soundend) };
  731. //if (currange.contains(m_stretch_source->getInfilePositionPercent())==false)
  732. m_stretch_source->seekPercent(*getFloatParameter(cpi_soundstart));
  733. m_current_file = f;
  734. m_current_file_date = m_current_file.getLastModificationTime();
  735. m_using_memory_buffer = false;
  736. setDirty();
  737. return String();
  738. }
  739. return "Could not open file " + f.getFullPathName();
  740. }
  741. Range<double> PaulstretchpluginAudioProcessor::getTimeSelection()
  742. {
  743. return { *getFloatParameter(cpi_soundstart),*getFloatParameter(cpi_soundend) };
  744. }
  745. double PaulstretchpluginAudioProcessor::getPreBufferingPercent()
  746. {
  747. if (m_buffering_source==nullptr)
  748. return 0.0;
  749. return m_smoothed_prebuffer_ready;
  750. }
  751. void PaulstretchpluginAudioProcessor::timerCallback(int id)
  752. {
  753. if (id == 1)
  754. {
  755. bool capture = getParameter(cpi_capture_enabled);
  756. if (capture == false && m_max_reclen != *getFloatParameter(cpi_max_capture_len))
  757. {
  758. m_max_reclen = *getFloatParameter(cpi_max_capture_len);
  759. //Logger::writeToLog("Changing max capture len to " + String(m_max_reclen));
  760. }
  761. if (capture == true && m_is_recording == false)
  762. {
  763. setRecordingEnabled(true);
  764. return;
  765. }
  766. if (capture == false && m_is_recording == true)
  767. {
  768. setRecordingEnabled(false);
  769. return;
  770. }
  771. if (m_cur_num_out_chans != *m_outchansparam)
  772. {
  773. jassert(m_curmaxblocksize > 0);
  774. ScopedLock locker(m_cs);
  775. m_prebuffering_inited = false;
  776. m_cur_num_out_chans = *m_outchansparam;
  777. //Logger::writeToLog("Switching to use " + String(m_cur_num_out_chans) + " out channels");
  778. String err;
  779. startplay({ *getFloatParameter(cpi_soundstart),*getFloatParameter(cpi_soundend) },
  780. m_cur_num_out_chans, m_curmaxblocksize, err);
  781. m_prebuffering_inited = true;
  782. }
  783. }
  784. }
  785. pointer_sized_int PaulstretchpluginAudioProcessor::handleVstPluginCanDo(int32 index, pointer_sized_int value, void * ptr, float opt)
  786. {
  787. if (strcmp((char*)ptr, "xenakios") == 0)
  788. {
  789. if (index == 0 && (void*)value!=nullptr)
  790. {
  791. double t0 = *getFloatParameter(cpi_soundstart);
  792. double t1 = *getFloatParameter(cpi_soundend);
  793. double outlen = (t1-t0)*m_stretch_source->getInfileLengthSeconds()*(*getFloatParameter(cpi_stretchamount));
  794. //std::cout << "host requested output length, result " << outlen << "\n";
  795. *((double*)value) = outlen;
  796. }
  797. if (index == 1 && (void*)value!=nullptr)
  798. {
  799. String fn(CharPointer_UTF8((char*)value));
  800. //std::cout << "host requested to set audio file " << fn << "\n";
  801. auto err = setAudioFile(File(fn));
  802. if (err.isEmpty()==false)
  803. std::cout << err << "\n";
  804. }
  805. return 1;
  806. }
  807. return pointer_sized_int();
  808. }
  809. pointer_sized_int PaulstretchpluginAudioProcessor::handleVstManufacturerSpecific(int32 index, pointer_sized_int value, void * ptr, float opt)
  810. {
  811. return pointer_sized_int();
  812. }
  813. void PaulstretchpluginAudioProcessor::finishRecording(int lenrecording)
  814. {
  815. m_is_recording = false;
  816. m_stretch_source->setAudioBufferAsInputSource(&m_recbuffer, getSampleRateChecked(), lenrecording);
  817. m_stretch_source->setPlayRange({ *getFloatParameter(cpi_soundstart),*getFloatParameter(cpi_soundend) }, true);
  818. }
  819. AudioProcessor* JUCE_CALLTYPE createPluginFilter()
  820. {
  821. return new PaulstretchpluginAudioProcessor();
  822. }