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.

808 lines
28KB

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