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.

1403 lines
44KB

  1. // Copyright 2013 Olivier Gillet.
  2. //
  3. // Author: Olivier Gillet (ol.gillet@gmail.com)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. // See http://creativecommons.org/licenses/MIT/ for more information.
  24. //
  25. // -----------------------------------------------------------------------------
  26. //
  27. // Tidal generator.
  28. #include "tides/generator.h"
  29. #include <algorithm>
  30. #include "stmlib/utils/dsp.h"
  31. #include "stmlib/utils/random.h"
  32. #include "tides/resources.h"
  33. // #define CORE_ONLY
  34. namespace tides {
  35. using namespace stmlib;
  36. const int16_t kOctave = 12 * 128;
  37. const uint16_t kSlopeBits = 12;
  38. const uint32_t kSyncCounterMaxTime = 8 * 48000;
  39. const int32_t kDownsampleCoefficient[4] = { 17162, 19069, 17162, 12140 };
  40. /* static */
  41. const FrequencyRatio Generator::frequency_ratios_[] = {
  42. { 1, 1 },
  43. { 5, 4 },
  44. { 4, 3 },
  45. { 3, 2 },
  46. { 5, 3 },
  47. { 2, 1 },
  48. { 3, 1 },
  49. { 4, 1 },
  50. { 6, 1 },
  51. { 8, 1 },
  52. { 12, 1 },
  53. { 16, 1 },
  54. };
  55. /* static */
  56. const int16_t Generator::num_frequency_ratios_ = \
  57. sizeof(Generator::frequency_ratios_) / sizeof(FrequencyRatio);
  58. void Generator::Init() {
  59. mode_ = GENERATOR_MODE_LOOPING;
  60. range_ = GENERATOR_RANGE_HIGH;
  61. clock_divider_ = 1;
  62. phase_ = 0;
  63. final_gain_ = 0;
  64. set_pitch(60 << 7, 0);
  65. output_buffer_.Init();
  66. input_buffer_.Init();
  67. pattern_predictor_.Init();
  68. for (uint16_t i = 0; i < kBlockSize; ++i) {
  69. GeneratorSample s;
  70. s.flags = 0;
  71. s.unipolar = 0;
  72. s.bipolar = 0;
  73. output_buffer_.Overwrite(s);
  74. input_buffer_.Overwrite(0);
  75. }
  76. antialiasing_ = true;
  77. shape_ = 0;
  78. slope_ = 0;
  79. smoothed_slope_ = 0;
  80. smoothness_ = 0;
  81. previous_sample_.unipolar = previous_sample_.bipolar = 0;
  82. running_ = wrap_ = false;
  83. previous_freeze_ = false;
  84. pulse_width_ = UINT16_MAX / 2;
  85. divided_phase_ = 0;
  86. divider_ = 1;
  87. divider_counter_ = 0;
  88. delayed_phase_ = 0;
  89. delayed_threshold_ = 0;
  90. delay_ = 0;
  91. ClearFilterState();
  92. sync_counter_ = kSyncCounterMaxTime;
  93. frequency_ratio_.p = 1;
  94. frequency_ratio_.q = 1;
  95. sync_ = false;
  96. phase_increment_ = 9448928;
  97. delayed_phase_increment_ = phase_increment_;
  98. local_osc_phase_increment_ = phase_increment_;
  99. target_phase_increment_ = phase_increment_;
  100. RandomizeHarmonicDistribution();
  101. }
  102. void Generator::ComputeFrequencyRatio(int16_t pitch) {
  103. int16_t delta = previous_pitch_ - pitch;
  104. // Hysteresis for preventing glitchy transitions.
  105. if (delta < 96 && delta > -96) {
  106. return;
  107. }
  108. previous_pitch_ = pitch;
  109. // Corresponds to a 0V CV after calibration
  110. pitch -= (36 << 7);
  111. // The range of the control panel knob is 4 octaves.
  112. pitch = pitch * 12 / (48 << 7);
  113. bool swap = false;
  114. if (pitch < 0) {
  115. pitch = -pitch;
  116. swap = true;
  117. }
  118. if (pitch >= num_frequency_ratios_) {
  119. pitch = num_frequency_ratios_ - 1;
  120. }
  121. frequency_ratio_ = frequency_ratios_[pitch];
  122. if (swap) {
  123. frequency_ratio_.q = frequency_ratio_.p;
  124. frequency_ratio_.p = frequency_ratios_[pitch].q;
  125. }
  126. }
  127. int32_t Generator::ComputePhaseIncrement(int16_t pitch) {
  128. int16_t num_shifts = 0;
  129. while (pitch < 0) {
  130. pitch += kOctave;
  131. --num_shifts;
  132. }
  133. while (pitch >= kOctave) {
  134. pitch -= kOctave;
  135. ++num_shifts;
  136. }
  137. // Lookup phase increment
  138. int32_t a = lut_increments[pitch >> 4];
  139. int32_t b = lut_increments[(pitch >> 4) + 1];
  140. int32_t phase_increment = a + ((b - a) * (pitch & 0xf) >> 4);
  141. // Compensate for downsampling
  142. phase_increment *= clock_divider_;
  143. phase_increment = num_shifts >= 0
  144. ? phase_increment << num_shifts
  145. : phase_increment >> -num_shifts;
  146. return phase_increment;
  147. }
  148. int16_t Generator::ComputePitch(int32_t phase_increment) {
  149. int32_t first = lut_increments[0];
  150. int32_t last = lut_increments[LUT_INCREMENTS_SIZE - 2];
  151. int16_t pitch = 0;
  152. if (phase_increment == 0) {
  153. phase_increment = 1;
  154. }
  155. phase_increment /= clock_divider_;
  156. while (phase_increment > last) {
  157. phase_increment >>= 1;
  158. pitch += kOctave;
  159. }
  160. while (phase_increment < first) {
  161. phase_increment <<= 1;
  162. pitch -= kOctave;
  163. }
  164. pitch += (std::lower_bound(
  165. lut_increments,
  166. lut_increments + LUT_INCREMENTS_SIZE,
  167. phase_increment) - lut_increments) << 4;
  168. return pitch;
  169. }
  170. int32_t Generator::ComputeCutoffFrequency(int16_t pitch, int16_t smoothness) {
  171. uint8_t shifts = clock_divider_;
  172. while (shifts > 1) {
  173. shifts >>= 1;
  174. pitch += kOctave;
  175. }
  176. int32_t frequency;
  177. if (smoothness > 0) {
  178. frequency = 256 << 7;
  179. } else if (smoothness > -16384) {
  180. int32_t start = pitch + (36 << 7);
  181. int32_t end = 256 << 7;
  182. frequency = start + ((end - start) * (smoothness + 16384) >> 14);
  183. } else {
  184. int32_t start = pitch - (36 << 7);
  185. int32_t end = pitch + (36 << 7);
  186. frequency = start + ((end - start) * (smoothness + 32768) >> 14);
  187. }
  188. frequency += 32768;
  189. if (frequency < 0) {
  190. frequency = 0;
  191. }
  192. return frequency;
  193. }
  194. int32_t Generator::ComputeAntialiasAttenuation(
  195. int16_t pitch,
  196. int16_t slope,
  197. int16_t shape,
  198. int16_t smoothness) {
  199. pitch += 128;
  200. if (pitch < 0) pitch = 0;
  201. if (slope < 0) slope = -slope;
  202. if (shape < 0) shape = -shape;
  203. if (smoothness < 0) smoothness = 0;
  204. int32_t p = 252059;
  205. p += -76 * smoothness >> 5;
  206. p += -30 * shape >> 5;
  207. p += -102 * slope >> 5;
  208. p += -664 * pitch >> 5;
  209. p += 31 * (smoothness * shape >> 16) >> 5;
  210. p += 12 * (smoothness * slope >> 16) >> 5;
  211. p += 14 * (shape * slope >> 16) >> 5;
  212. p += 219 * (pitch * smoothness >> 16) >> 5;
  213. p += 50 * (pitch * shape >> 16) >> 5;
  214. p += 425 * (pitch * slope >> 16) >> 5;
  215. p += 13 * (smoothness * smoothness >> 16) >> 5;
  216. p += 1 * (shape * shape >> 16) >> 5;
  217. p += -11 * (slope * slope >> 16) >> 5;
  218. p += 776 * (pitch * pitch >> 16) >> 5;
  219. if (p < 0) p = 0;
  220. if (p > 32767) p = 32767;
  221. return p;
  222. }
  223. void Generator::FillBuffer() {
  224. if (feature_mode_ == FEAT_MODE_FUNCTION) {
  225. #ifndef WAVETABLE_HACK
  226. if (range_ == GENERATOR_RANGE_HIGH) {
  227. FillBufferAudioRate();
  228. } else {
  229. FillBufferControlRate();
  230. }
  231. #else
  232. FillBufferWavetable();
  233. #endif
  234. } else if (feature_mode_ == FEAT_MODE_HARMONIC) {
  235. if (mode_ == GENERATOR_MODE_LOOPING)
  236. FillBufferHarmonic<GENERATOR_MODE_LOOPING>();
  237. else if (mode_ == GENERATOR_MODE_AR)
  238. FillBufferHarmonic<GENERATOR_MODE_AR>();
  239. else if (mode_ == GENERATOR_MODE_AD)
  240. FillBufferHarmonic<GENERATOR_MODE_AD>();
  241. } else if (feature_mode_ == FEAT_MODE_RANDOM) {
  242. FillBufferRandom();
  243. }
  244. }
  245. // There are to our knowledge three ways of generating an "asymmetric" ramp:
  246. //
  247. // 1. Use the difference between two parabolic waves.
  248. //
  249. // + Anti-aliasing is easy with wavetables of band-limited parabolic waves.
  250. // + Slope modulation does not cause discontinuities.
  251. // - Does not allow a different waveshape to be used for the A and D segments.
  252. // - Needs gain compensation at the extreme settings of the slope parameter.
  253. // - Does not traverse the full 0 .. 65535 range due to inaccuracies in gain
  254. // factor.
  255. //
  256. // 2. Use different phase increments for the A and D segments.
  257. //
  258. // + Slope modulation does not cause discontinuities.
  259. // + Traverses the full 0 .. 65535 range.
  260. // - Due to rounding errors, the duration of the A+D segment is not preserved
  261. // exactly when the slope is modulated.
  262. // - No anti-aliasing.
  263. //
  264. // 3. Generate a ramp and waveshape it (phase distortion).
  265. //
  266. // + Duration of A+D segment is preserved.
  267. // + Traverses the full 0 .. 65535 range.
  268. // - No anti-aliasing.
  269. // - Slope modulations causes waveform discontinuities.
  270. //
  271. //
  272. // We use 1. for the highest range (audio rates); and 3 for the two other ranges
  273. // (control rates extending into audio territory). To compensate for the slope
  274. // modulation discontinuities, we low-pass filter digitally the slope value.
  275. // 2. has a terrible behaviour in the audio range, because it causes audible FM
  276. // when the slope parameter is modulated by a LFO.
  277. void Generator::FillBufferAudioRate() {
  278. uint8_t size = kBlockSize;
  279. GeneratorSample sample = previous_sample_;
  280. int32_t phase_increment_end;
  281. if (sync_) {
  282. pitch_ = ComputePitch(phase_increment_);
  283. phase_increment_end = phase_increment_;
  284. } else {
  285. phase_increment_end = ComputePhaseIncrement(pitch_);
  286. local_osc_phase_increment_ = phase_increment_end;
  287. target_phase_increment_ = phase_increment_end;
  288. }
  289. if (pitch_ < 0) {
  290. pitch_ = 0;
  291. }
  292. #ifndef CORE_ONLY
  293. // Load wavetable pointers for bandlimiting - they depend on pitch value.
  294. uint16_t xfade = pitch_ << 6;
  295. uint16_t index = pitch_ >> 10;
  296. if (pitch_ < 0) {
  297. index = 0;
  298. xfade = 0;
  299. }
  300. const int16_t* wave_1 = waveform_table[WAV_BANDLIMITED_PARABOLA_0 + index];
  301. const int16_t* wave_2 = waveform_table[WAV_BANDLIMITED_PARABOLA_0 + index + 1];
  302. // we split the slope button into two: original slope on the first
  303. // half, compression on the second
  304. int16_t compress = -slope_;
  305. int16_t slope = slope_;
  306. CONSTRAIN(slope, 0, 32767);
  307. CONSTRAIN(compress, 0, 32767);
  308. // adjust knob response for Slope
  309. int32_t s = 32768 - slope;
  310. slope = 32768 - ((s * s) >> 15);
  311. CONSTRAIN(slope, 0, 32600); // that is a bit weird
  312. int32_t gain = slope;
  313. gain = (32768 - (gain * gain >> 15)) * 3 >> 1;
  314. gain = 32768 * 1024 / gain;
  315. uint32_t phase_offset_a_bi = (slope - (slope >> 1)) << 16;
  316. uint32_t phase_offset_b_bi = (32768 - (slope >> 1)) << 16;
  317. uint32_t phase_offset_a_uni = 49152 << 16;
  318. uint32_t phase_offset_b_uni = (32768 + 49152 - slope) << 16;
  319. int32_t attenuation = 32767;
  320. if (antialiasing_) {
  321. attenuation = ComputeAntialiasAttenuation(
  322. pitch_,
  323. slope,
  324. shape_,
  325. smoothness_);
  326. }
  327. uint16_t shape = static_cast<uint16_t>((shape_ * attenuation >> 15) + 32768);
  328. uint16_t wave_index = WAV_INVERSE_TAN_AUDIO + (shape >> 14);
  329. const int16_t* shape_1 = waveform_table[wave_index];
  330. const int16_t* shape_2 = waveform_table[wave_index + 1];
  331. uint16_t shape_xfade = shape << 2;
  332. int32_t frequency = ComputeCutoffFrequency(pitch_, smoothness_);
  333. int32_t f_a = lut_cutoff[frequency >> 7] >> 16;
  334. int32_t f_b = lut_cutoff[(frequency >> 7) + 1] >> 16;
  335. int32_t f = f_a + ((f_b - f_a) * (frequency & 0x7f) >> 7);
  336. int32_t wf_gain = 2048;
  337. int32_t wf_balance = 0;
  338. if (smoothness_ > 0) {
  339. int16_t attenuated_smoothness = smoothness_ * attenuation >> 15;
  340. wf_gain += attenuated_smoothness * (32767 - 1024) >> 14;
  341. wf_balance = attenuated_smoothness;
  342. }
  343. #endif // CORE_ONLY
  344. uint32_t end_of_attack = (static_cast<uint32_t>(slope + 32768) << 16);
  345. // Load state into registers - saves some memory load/store inside the
  346. // rendering loop.
  347. uint32_t phase = phase_;
  348. int32_t phase_increment = phase_increment_;
  349. int32_t phase_increment_increment = (phase_increment_end - phase_increment_) / size;
  350. bool wrap = wrap_;
  351. int32_t uni_lp_state_0 = uni_lp_state_[0];
  352. int32_t uni_lp_state_1 = uni_lp_state_[1];
  353. int32_t bi_lp_state_0 = bi_lp_state_[0];
  354. int32_t bi_lp_state_1 = bi_lp_state_[1];
  355. // Enforce that the EOA pulse is at least 1 sample wide.
  356. if (end_of_attack >= abs(phase_increment)) {
  357. end_of_attack -= phase_increment;
  358. }
  359. if (end_of_attack < abs(phase_increment)) {
  360. end_of_attack = phase_increment;
  361. }
  362. // cut out the output completely when smoothness is fully off.
  363. uint16_t final_gain_end = smoothness_ + 32768;
  364. CONSTRAIN(final_gain_end, 200, (UINT16_MAX >> 3) + 200);
  365. final_gain_end -= 200;
  366. final_gain_end <<= 3;
  367. uint16_t final_gain_increment = (final_gain_end - final_gain_) / size;
  368. while (size--) {
  369. ++sync_counter_;
  370. uint8_t control = input_buffer_.ImmediateRead();
  371. // When freeze is high, discard any start/reset command.
  372. if (!(control & CONTROL_FREEZE)) {
  373. if (control & CONTROL_GATE_RISING) {
  374. phase = 0;
  375. running_ = true;
  376. } else if (mode_ != GENERATOR_MODE_LOOPING && wrap) {
  377. phase = 0;
  378. running_ = false;
  379. }
  380. // on clock falling edge
  381. if (!(control & CONTROL_CLOCK) &&
  382. previous_clock_) {
  383. sub_phase_ = 0;
  384. }
  385. previous_clock_ = control & CONTROL_CLOCK;
  386. }
  387. if (sync_) {
  388. if (control & CONTROL_CLOCK_RISING) {
  389. ++sync_edges_counter_;
  390. if (sync_edges_counter_ >= frequency_ratio_.q) {
  391. sync_edges_counter_ = 0;
  392. if (sync_counter_ < kSyncCounterMaxTime && sync_counter_) {
  393. uint64_t increment = frequency_ratio_.p * static_cast<uint64_t>(
  394. 0xffffffff / sync_counter_);
  395. if (increment > 0x80000000) {
  396. increment = 0x80000000;
  397. }
  398. target_phase_increment_ = static_cast<uint32_t>(increment);
  399. local_osc_phase_ = 0;
  400. }
  401. sync_counter_ = 0;
  402. }
  403. }
  404. // Fast tracking of the local oscillator to the external oscillator.
  405. local_osc_phase_increment_ += static_cast<int32_t>(
  406. target_phase_increment_ - local_osc_phase_increment_) >> 8;
  407. local_osc_phase_ += local_osc_phase_increment_;
  408. // Slow phase realignment between the master oscillator and the local
  409. // oscillator.
  410. int32_t phase_error = local_osc_phase_ - phase;
  411. phase_increment = local_osc_phase_increment_ + (phase_error >> 13);
  412. }
  413. if (control & CONTROL_FREEZE) {
  414. output_buffer_.Overwrite(sample);
  415. continue;
  416. }
  417. bool sustained = mode_ == GENERATOR_MODE_AR
  418. && phase >= (1UL << 31)
  419. && control & CONTROL_GATE;
  420. if (sustained) {
  421. phase = 1L << 31;
  422. }
  423. #ifndef CORE_ONLY
  424. // Clip the phase for compression
  425. uint32_t compress_index = compress << 1;
  426. compress_index = 65535 - compress_index;
  427. compress_index = (compress_index * compress_index) >> 16;
  428. compress_index = 65535 - compress_index;
  429. compress_index = compress_index * 29 / 30; // knob range
  430. compress_index = 65535 - compress_index;
  431. uint32_t compressed_phase =
  432. (phase >> 16) > compress_index ? 0 :
  433. phase / compress_index * UINT16_MAX;
  434. // Bipolar version ---------------------------------------------------------
  435. int32_t ramp_a, ramp_b, saw;
  436. int32_t original, folded;
  437. ramp_a = Crossfade1022(wave_1, wave_2, compressed_phase + phase_offset_a_bi, xfade);
  438. ramp_b = Crossfade1022(wave_1, wave_2, compressed_phase + phase_offset_b_bi, xfade);
  439. saw = (ramp_b - ramp_a) * gain >> 10;
  440. CLIP(saw);
  441. // Appy shape waveshaper.
  442. saw = Crossfade115(shape_1, shape_2, saw + 32768, shape_xfade);
  443. if (!running_ && !sustained) {
  444. saw = 0;
  445. }
  446. // Run through LPF.
  447. bi_lp_state_0 += f * (saw - bi_lp_state_0) >> 15;
  448. bi_lp_state_1 += f * (bi_lp_state_0 - bi_lp_state_1) >> 15;
  449. // Fold.
  450. original = bi_lp_state_1;
  451. folded = Interpolate1022(wav_bipolar_fold, original * wf_gain + (1UL << 31));
  452. sample.bipolar = original + ((folded - original) * wf_balance >> 15);
  453. sample.bipolar = (sample.bipolar * final_gain_) >> 16;
  454. // Unipolar version --------------------------------------------------------
  455. ramp_a = Crossfade1022(wave_1, wave_2, compressed_phase + phase_offset_a_uni, xfade);
  456. ramp_b = Crossfade1022(wave_1, wave_2, compressed_phase + phase_offset_b_uni, xfade);
  457. saw = (ramp_b - ramp_a) * gain >> 10;
  458. CLIP(saw)
  459. // Appy shape waveshaper.
  460. saw = Crossfade115(shape_1, shape_2, (saw >> 1) + 32768 + 16384,
  461. shape_xfade);
  462. if (!running_ && !sustained) {
  463. saw = 0;
  464. }
  465. // Run through LPF.
  466. uni_lp_state_0 += f * (saw - uni_lp_state_0) >> 15;
  467. uni_lp_state_1 += f * (uni_lp_state_0 - uni_lp_state_1) >> 15;
  468. // Fold.
  469. original = uni_lp_state_1 << 1;
  470. folded = Interpolate1022(wav_unipolar_fold, original * wf_gain) << 1;
  471. sample.unipolar = original + ((folded - original) * wf_balance >> 15);
  472. sample.unipolar = (sample.unipolar * final_gain_) >> 16;
  473. #else
  474. sample.bipolar = (phase >> 16) - 32768;
  475. sample.unipolar = phase >> 16;
  476. #endif // CORE_ONLY
  477. sample.flags = 0;
  478. if (compressed_phase >= end_of_attack || !running_) {
  479. sample.flags |= FLAG_END_OF_ATTACK;
  480. }
  481. if (!(control & CONTROL_CLOCK) &&
  482. sub_phase_ & 0x80000000) {
  483. sample.flags |= FLAG_END_OF_RELEASE;
  484. }
  485. output_buffer_.Overwrite(sample);
  486. if (running_ && !sustained) {
  487. phase += phase_increment;
  488. sub_phase_ += phase_increment >> 1;
  489. wrap = phase < abs(phase_increment);
  490. }
  491. final_gain_ += final_gain_increment;
  492. phase_increment += phase_increment_increment;
  493. }
  494. uni_lp_state_[0] = uni_lp_state_0;
  495. uni_lp_state_[1] = uni_lp_state_1;
  496. bi_lp_state_[0] = bi_lp_state_0;
  497. bi_lp_state_[1] = bi_lp_state_1;
  498. previous_sample_ = sample;
  499. phase_ = phase;
  500. phase_increment_ = phase_increment;
  501. wrap_ = wrap;
  502. }
  503. void Generator::FillBufferControlRate() {
  504. uint8_t size = kBlockSize;
  505. if (sync_) {
  506. pitch_ = ComputePitch(phase_increment_);
  507. } else {
  508. phase_increment_ = ComputePhaseIncrement(pitch_);
  509. local_osc_phase_increment_ = phase_increment_;
  510. target_phase_increment_ = phase_increment_;
  511. }
  512. GeneratorSample sample = previous_sample_;
  513. #ifndef CORE_ONLY
  514. uint16_t shape = static_cast<uint16_t>(shape_ + 32768);
  515. shape = (shape >> 2) * 3;
  516. uint16_t wave_index = WAV_REVERSED_CONTROL + (shape >> 13);
  517. const int16_t* shape_1 = waveform_table[wave_index];
  518. const int16_t* shape_2 = waveform_table[wave_index + 1];
  519. uint16_t shape_xfade = shape << 3;
  520. int64_t frequency = ComputeCutoffFrequency(pitch_, smoothness_);
  521. int64_t f_a = lut_cutoff[frequency >> 7];
  522. int64_t f_b = lut_cutoff[(frequency >> 7) + 1];
  523. int64_t f = f_a + ((f_b - f_a) * (frequency & 0x7f) >> 7);
  524. int32_t wf_gain = 2048;
  525. int32_t wf_balance = 0;
  526. if (smoothness_ > 0) {
  527. wf_gain += smoothness_ * (32767 - 1024) >> 14;
  528. wf_balance = smoothness_;
  529. }
  530. #endif // CORE_ONLY
  531. // Load state into registers - saves some memory load/store inside the
  532. // rendering loop.
  533. uint32_t phase = phase_;
  534. uint32_t phase_increment = phase_increment_;
  535. bool wrap = wrap_;
  536. int32_t smoothed_slope = smoothed_slope_;
  537. int64_t uni_lp_state_0 = uni_lp_state_[0];
  538. int64_t uni_lp_state_1 = uni_lp_state_[1];
  539. int64_t bi_lp_state_0 = bi_lp_state_[0];
  540. int64_t bi_lp_state_1 = bi_lp_state_[1];
  541. int32_t previous_smoothed_slope = 0x7fffffff;
  542. uint32_t end_of_attack = 1UL << 31;
  543. uint32_t attack_factor = 1 << kSlopeBits;
  544. uint32_t decay_factor = 1 << kSlopeBits;
  545. while (size--) {
  546. sync_counter_++;
  547. // Low-pass filter the slope parameter.
  548. smoothed_slope += (slope_ - smoothed_slope) >> 4;
  549. uint8_t control = input_buffer_.ImmediateRead();
  550. // When freeze is high, discard any start/reset command.
  551. if (!(control & CONTROL_FREEZE)) {
  552. if (control & CONTROL_GATE_RISING) {
  553. phase = 0;
  554. running_ = true;
  555. } else if (mode_ != GENERATOR_MODE_LOOPING && wrap) {
  556. running_ = false;
  557. phase = 0;
  558. }
  559. }
  560. if ((control & CONTROL_CLOCK_RISING) && sync_ && sync_counter_) {
  561. if (sync_counter_ >= kSyncCounterMaxTime) {
  562. phase = 0;
  563. } else {
  564. uint32_t predicted_period = pattern_predictor_.Predict(sync_counter_);
  565. uint64_t increment = frequency_ratio_.p * static_cast<uint64_t>(
  566. 0xffffffff / (predicted_period * frequency_ratio_.q));
  567. if (increment > 0x80000000) {
  568. increment = 0x80000000;
  569. }
  570. phase_increment = static_cast<uint32_t>(increment);
  571. }
  572. sync_counter_ = 0;
  573. }
  574. if (control & CONTROL_FREEZE) {
  575. output_buffer_.Overwrite(sample);
  576. continue;
  577. }
  578. // Recompute the waveshaping parameters only when the slope has changed.
  579. if (smoothed_slope != previous_smoothed_slope) {
  580. uint32_t slope_offset = Interpolate88(
  581. lut_slope_compression, smoothed_slope + 32768);
  582. if (slope_offset <= 1) {
  583. decay_factor = 32768 << kSlopeBits;
  584. attack_factor = 1 << (kSlopeBits - 1);
  585. } else {
  586. decay_factor = (32768 << kSlopeBits) / slope_offset;
  587. attack_factor = (32768 << kSlopeBits) / (65536 - slope_offset);
  588. }
  589. previous_smoothed_slope = smoothed_slope;
  590. end_of_attack = slope_offset << 16;
  591. }
  592. uint32_t skewed_phase = phase;
  593. if (phase <= end_of_attack) {
  594. skewed_phase = (phase >> kSlopeBits) * decay_factor;
  595. } else {
  596. skewed_phase = ((phase - end_of_attack) >> kSlopeBits) * attack_factor;
  597. skewed_phase += 1L << 31;
  598. }
  599. bool sustained = mode_ == GENERATOR_MODE_AR
  600. && phase >= end_of_attack
  601. && control & CONTROL_GATE;
  602. if (sustained) {
  603. skewed_phase = 1L << 31;
  604. phase = end_of_attack + 1;
  605. }
  606. #ifndef CORE_ONLY
  607. int32_t original, folded;
  608. int32_t unipolar = Crossfade106(
  609. shape_1,
  610. shape_2,
  611. skewed_phase >> 16, shape_xfade);
  612. uni_lp_state_0 += f * ((unipolar << 16) - uni_lp_state_0) >> 31;
  613. uni_lp_state_1 += f * (uni_lp_state_0 - uni_lp_state_1) >> 31;
  614. original = uni_lp_state_1 >> 15;
  615. folded = Interpolate1022(wav_unipolar_fold, original * wf_gain) << 1;
  616. sample.unipolar = original + ((folded - original) * wf_balance >> 15);
  617. int32_t bipolar = Crossfade106(
  618. shape_1,
  619. shape_2,
  620. skewed_phase >> 15, shape_xfade);
  621. if (skewed_phase >= (1UL << 31)) {
  622. bipolar = -bipolar;
  623. }
  624. bi_lp_state_0 += f * ((bipolar << 16) - bi_lp_state_0) >> 31;
  625. bi_lp_state_1 += f * (bi_lp_state_0 - bi_lp_state_1) >> 31;
  626. original = bi_lp_state_1 >> 16;
  627. folded = Interpolate1022(wav_bipolar_fold, original * wf_gain + (1UL << 31));
  628. sample.bipolar = original + ((folded - original) * wf_balance >> 15);
  629. #else
  630. sample.bipolar = (skewed_phase >> 16) - 32768;
  631. sample.unipolar = skewed_phase >> 16;
  632. #endif // CORE_ONLY
  633. uint32_t adjusted_end_of_attack = end_of_attack;
  634. if (adjusted_end_of_attack >= phase_increment) {
  635. adjusted_end_of_attack -= phase_increment;
  636. }
  637. if (adjusted_end_of_attack < phase_increment) {
  638. adjusted_end_of_attack = phase_increment;
  639. }
  640. sample.flags = 0;
  641. bool looped = mode_ == GENERATOR_MODE_LOOPING && wrap;
  642. if (phase >= adjusted_end_of_attack || !running_ || sustained) {
  643. sample.flags |= FLAG_END_OF_ATTACK;
  644. }
  645. if (!running_ || looped) {
  646. eor_counter_ = phase_increment < 44739242 ? 48 : 1;
  647. }
  648. if (eor_counter_) {
  649. sample.flags |= FLAG_END_OF_RELEASE;
  650. --eor_counter_;
  651. }
  652. // Two special cases for the "pure decay" scenario:
  653. // END_OF_ATTACK is always true except at the initial trigger.
  654. if (end_of_attack == 0) {
  655. sample.flags |= FLAG_END_OF_ATTACK;
  656. }
  657. bool triggered = control & CONTROL_GATE_RISING;
  658. if ((sustained || end_of_attack == 0) && (triggered || looped)) {
  659. sample.flags &= ~FLAG_END_OF_ATTACK;
  660. }
  661. output_buffer_.Overwrite(sample);
  662. if (running_ && !sustained) {
  663. phase += phase_increment;
  664. wrap = phase < phase_increment;
  665. } else {
  666. wrap = false;
  667. }
  668. }
  669. uni_lp_state_[0] = uni_lp_state_0;
  670. uni_lp_state_[1] = uni_lp_state_1;
  671. bi_lp_state_[0] = bi_lp_state_0;
  672. bi_lp_state_[1] = bi_lp_state_1;
  673. previous_sample_ = sample;
  674. phase_ = phase;
  675. phase_increment_ = phase_increment;
  676. wrap_ = wrap;
  677. smoothed_slope_ = smoothed_slope;
  678. }
  679. void Generator::FillBufferWavetable() {
  680. uint8_t size = kBlockSize;
  681. GeneratorSample sample = previous_sample_;
  682. if (sync_) {
  683. pitch_ = ComputePitch(phase_increment_);
  684. } else {
  685. phase_increment_ = ComputePhaseIncrement(pitch_);
  686. }
  687. uint32_t phase = phase_;
  688. uint32_t sub_phase = sub_phase_;
  689. uint32_t phase_increment = phase_increment_;
  690. // The grid is only 8x8 rather than 9x9 so we need to scale by 7/8.0
  691. uint16_t target_x = static_cast<uint16_t>(slope_ + 32768);
  692. target_x = target_x * 57344 >> 16;
  693. uint16_t x = x_;
  694. uint16_t x_increment = (target_x - x) / size;
  695. uint16_t target_y = static_cast<uint16_t>(shape_ + 32768);
  696. target_y = target_y * 57344 >> 16;
  697. uint16_t y = y_;
  698. uint16_t y_increment = (target_y - y) / size;
  699. int32_t wf_gain = smoothness_ > 0 ? smoothness_ : 0;
  700. wf_gain = wf_gain * wf_gain >> 15;
  701. int32_t frequency = ComputeCutoffFrequency(pitch_, smoothness_);
  702. int32_t f_a = lut_cutoff[frequency >> 7] >> 16;
  703. int32_t f_b = lut_cutoff[(frequency >> 7) + 1] >> 16;
  704. int32_t f = f_a + ((f_b - f_a) * (frequency & 0x7f) >> 7);
  705. int32_t lp_state_0 = bi_lp_state_[0];
  706. int32_t lp_state_1 = bi_lp_state_[1];
  707. const int16_t* bank = wt_waves + mode_ * 64 * 257 - (mode_ & 2) * 4 * 257;
  708. while (size--) {
  709. ++sync_counter_;
  710. uint8_t control = input_buffer_.ImmediateRead();
  711. // When freeze is high, discard any start/reset command.
  712. if (!(control & CONTROL_FREEZE)) {
  713. if (control & CONTROL_GATE_RISING) {
  714. phase = 0;
  715. sub_phase = 0;
  716. }
  717. }
  718. if (control & CONTROL_CLOCK_RISING) {
  719. if (sync_) {
  720. if (range_ == GENERATOR_RANGE_HIGH) {
  721. ++sync_edges_counter_;
  722. if (sync_edges_counter_ >= frequency_ratio_.q) {
  723. sync_edges_counter_ = 0;
  724. if (sync_counter_ < kSyncCounterMaxTime && sync_counter_) {
  725. uint64_t increment = frequency_ratio_.p * static_cast<uint64_t>(
  726. 0xffffffff / sync_counter_);
  727. if (increment > 0x80000000) {
  728. increment = 0x80000000;
  729. }
  730. target_phase_increment_ = static_cast<uint32_t>(increment);
  731. local_osc_phase_ = 0;
  732. }
  733. sync_counter_ = 0;
  734. }
  735. } else {
  736. if (sync_counter_ >= kSyncCounterMaxTime) {
  737. phase = 0;
  738. } else if (sync_counter_) {
  739. uint32_t predicted_period = sync_counter_ < 480
  740. ? sync_counter_
  741. : pattern_predictor_.Predict(sync_counter_);
  742. uint64_t increment = frequency_ratio_.p * static_cast<uint64_t>(
  743. 0xffffffff / (predicted_period * frequency_ratio_.q));
  744. if (increment > 0x80000000) {
  745. increment = 0x80000000;
  746. }
  747. phase_increment = static_cast<uint32_t>(increment);
  748. }
  749. sync_counter_ = 0;
  750. }
  751. } else {
  752. // Normal behaviour: switch banks.
  753. uint8_t bank_index = mode_ + 1;
  754. if (bank_index > 2) {
  755. bank_index = 0;
  756. }
  757. mode_ = static_cast<GeneratorMode>(bank_index);
  758. bank = wt_waves + mode_ * 64 * 257 - (mode_ & 2) * 4 * 257;
  759. }
  760. }
  761. // PLL stuff
  762. if (sync_ && range_ == GENERATOR_RANGE_HIGH) {
  763. // Fast tracking of the local oscillator to the external oscillator.
  764. local_osc_phase_increment_ += static_cast<int32_t>(
  765. target_phase_increment_ - local_osc_phase_increment_) >> 8;
  766. local_osc_phase_ += local_osc_phase_increment_;
  767. // Slow phase realignment between the master oscillator and the local
  768. // oscillator.
  769. int32_t phase_error = local_osc_phase_ - phase;
  770. phase_increment = local_osc_phase_increment_ + (phase_error >> 13);
  771. }
  772. x += x_increment;
  773. y += y_increment;
  774. if (control & CONTROL_FREEZE) {
  775. output_buffer_.Overwrite(sample);
  776. continue;
  777. }
  778. uint16_t x_integral = x >> 13;
  779. uint16_t y_integral = y >> 13;
  780. const int16_t* wave_1 = &bank[(x_integral + y_integral * 8) * 257];
  781. const int16_t* wave_2 = wave_1 + 257 * 8;
  782. uint16_t x_fractional = x << 3;
  783. int32_t y_fractional = (y << 2) & 0x7fff;
  784. int32_t s = 0;
  785. for (int32_t subsample = 0; subsample < 4; ++subsample) {
  786. int32_t y_1 = Crossfade(wave_1, wave_1 + 257, phase, x_fractional);
  787. int32_t y_2 = Crossfade(wave_2, wave_2 + 257, phase, x_fractional);
  788. int32_t y_mix = y_1 + ((y_2 - y_1) * y_fractional >> 15);
  789. int32_t folded = Interpolate1022(
  790. ws_smooth_bipolar_fold, (y_mix + 32768) << 16);
  791. y_mix = y_mix + ((folded - y_mix) * wf_gain >> 15);
  792. s += y_mix * kDownsampleCoefficient[subsample];
  793. phase += (phase_increment >> 2);
  794. }
  795. lp_state_0 += f * ((s >> 16) - lp_state_0) >> 15;
  796. lp_state_1 += f * (lp_state_0 - lp_state_1) >> 15;
  797. sample.bipolar = lp_state_1;
  798. sample.unipolar = sample.bipolar + 32768;
  799. sample.flags = 0;
  800. if (sample.unipolar & 0x8000) {
  801. sample.flags |= FLAG_END_OF_ATTACK;
  802. }
  803. if (sub_phase & 0x80000000) {
  804. sample.flags |= FLAG_END_OF_RELEASE;
  805. }
  806. output_buffer_.Overwrite(sample);
  807. sub_phase += phase_increment >> 1;
  808. }
  809. previous_sample_ = sample;
  810. phase_ = phase;
  811. sub_phase_ = sub_phase;
  812. phase_increment_ = phase_increment;
  813. x_ = x;
  814. y_ = y;
  815. bi_lp_state_[0] = lp_state_0;
  816. bi_lp_state_[1] = lp_state_1;
  817. }
  818. uint16_t ComputePeak(uint16_t center, uint16_t width, uint16_t x) {
  819. uint16_t peak;
  820. if (x < center - width)
  821. peak = 0;
  822. else if (x < center)
  823. peak = 32768 - ((center - x) << 15) / width;
  824. else if (x < center + width)
  825. peak = 32768 - ((x - center) << 15) / width;
  826. else
  827. peak = 0;
  828. return peak;
  829. }
  830. template<GeneratorMode mode>
  831. void Generator::FillBufferHarmonic() {
  832. uint8_t size = kBlockSize;
  833. uint16_t width = static_cast<uint16_t>(smoothness_ << 1);
  834. width = (width * width) >> 16;
  835. int32_t reverse = (-smoothness_ << 3) + 32768;
  836. CONSTRAIN(reverse, 0, UINT16_MAX);
  837. int32_t phase_increment_end;
  838. if (sync_) {
  839. pitch_ = ComputePitch(phase_increment_);
  840. phase_increment_end = phase_increment_;
  841. } else {
  842. phase_increment_end = ComputePhaseIncrement(pitch_);
  843. local_osc_phase_increment_ = phase_increment_end;
  844. target_phase_increment_ = phase_increment_end;
  845. }
  846. uint16_t center1 = shape_ + 32768;
  847. uint16_t center2 = slope_ + 32768;
  848. uint16_t envelope[kNumHarmonics];
  849. uint16_t antialias[kNumHarmonics];
  850. // pre-compute spectral envelope
  851. for (uint8_t harm=0; harm<kNumHarmonics; harm++) {
  852. uint16_t x = mode == GENERATOR_MODE_AR ?
  853. (harm << 16) / kNumHarmonicsPowers :
  854. (harm << 16) / kNumHarmonics;
  855. // first peak has half the width
  856. uint16_t peak1 = ComputePeak(center1, width >> 1, x);
  857. // second peak has half the gain
  858. uint16_t peak2 = ComputePeak(center2, width, x) >> 1;
  859. uint16_t a = peak1 > peak2 ? peak1 : peak2;
  860. uint16_t b = 32768 - a;
  861. b = (b * b) >> 16; // wider notches
  862. b = b * (kNumHarmonics - harm) / kNumHarmonics;
  863. envelope[harm] = b + (((a - b) * reverse) >> 16);
  864. // Take care of harmonics which phase increment will be > Nyquist
  865. const uint32_t kCutoffLow = UINT16_MAX / 2 - UINT16_MAX / 16;
  866. const uint32_t kCutoffHigh = UINT16_MAX / 2;
  867. uint32_t pi = abs(phase_increment_end) >> 16;
  868. pi =
  869. mode == GENERATOR_MODE_AR ? pi << harm :
  870. mode == GENERATOR_MODE_LOOPING ? pi * (harm + 1) :
  871. // mode == GENERATOR_MODE_AD ?
  872. pi * ((harm << 1) + 1);
  873. if (pi > kCutoffHigh)
  874. antialias[harm] = 0;
  875. else if (pi > kCutoffLow)
  876. antialias[harm] = UINT16_MAX * (kCutoffHigh - pi)
  877. / (kCutoffHigh - kCutoffLow);
  878. else
  879. antialias[harm] = UINT16_MAX;
  880. envelope_increment_[harm] = (envelope[harm] - envelope_[harm]) / size;
  881. }
  882. int32_t phase_increment_increment = (phase_increment_end - phase_increment_) / size;
  883. while (size--) {
  884. sync_counter_++;
  885. uint8_t control = input_buffer_.ImmediateRead();
  886. if (control & CONTROL_GATE_RISING) {
  887. phase_ = 0;
  888. sub_phase_ = 0;
  889. }
  890. if (control & CONTROL_FREEZE) {
  891. if (!previous_freeze_) {
  892. RandomizeHarmonicDistribution();
  893. previous_freeze_ = true;
  894. }
  895. } else {
  896. previous_freeze_ = false;
  897. }
  898. // clock input randomizes mode and range if not in PLL mode
  899. if (control & CONTROL_CLOCK_RISING && !sync_) {
  900. mode_ = static_cast<GeneratorMode>(Random::GetWord() % 3);
  901. range_ = static_cast<GeneratorRange>(Random::GetWord() % 3);
  902. }
  903. if (sync_) {
  904. if (control & CONTROL_CLOCK_RISING) {
  905. ++sync_edges_counter_;
  906. if (sync_edges_counter_ >= frequency_ratio_.q) {
  907. sync_edges_counter_ = 0;
  908. if (sync_counter_ < kSyncCounterMaxTime && sync_counter_) {
  909. uint64_t increment = frequency_ratio_.p * static_cast<uint64_t>(
  910. 0xffffffff / sync_counter_);
  911. if (increment > 0x80000000) {
  912. increment = 0x80000000;
  913. }
  914. target_phase_increment_ = static_cast<uint32_t>(increment);
  915. local_osc_phase_ = 0;
  916. }
  917. sync_counter_ = 0;
  918. }
  919. }
  920. // Fast tracking of the local oscillator to the external oscillator.
  921. local_osc_phase_increment_ += static_cast<int32_t>(
  922. target_phase_increment_ - local_osc_phase_increment_) >> 5;
  923. local_osc_phase_ += local_osc_phase_increment_;
  924. // Slow phase realignment between the master oscillator and the local
  925. // oscillator.
  926. int32_t phase_error = local_osc_phase_ - phase_;
  927. phase_increment_ = local_osc_phase_increment_ + (phase_error >> 13);
  928. }
  929. int32_t bipolar = 0;
  930. int32_t unipolar = 0;
  931. int32_t gain = 0;
  932. int16_t sine = range_ == GENERATOR_RANGE_HIGH ?
  933. Interpolate1022(wav_sine1024, phase_) :
  934. range_ == GENERATOR_RANGE_MEDIUM ?
  935. Interpolate626(wav_sine64, phase_) :
  936. Interpolate428(wav_sine16, phase_);
  937. int32_t tn1 = 32768;
  938. int32_t tn = sine;
  939. for (uint8_t harm=0; harm<kNumHarmonics; harm++) {
  940. envelope_[harm] += envelope_increment_[harm];
  941. gain += envelope_[harm];
  942. bipolar += (((tn * envelope_[harm]) >> 16) * antialias[harm]) >> 16;
  943. unipolar += (((tn * envelope_[harm_permut_[harm]]) >> 16) * antialias[harm]) >> 16;
  944. int32_t t = tn;
  945. if (mode == GENERATOR_MODE_AR) { // power of two harmonics
  946. if (harm == kNumHarmonicsPowers) break;
  947. if ((harm & 3) == 0)
  948. tn = Interpolate1121(wav_sine1024, phase_ << harm);
  949. else
  950. tn = 2 * ((tn * tn) >> 15) - 32768;
  951. } else if (mode == GENERATOR_MODE_AD) { // odd harmonics
  952. tn = ((sine * tn) >> 14) - tn1;
  953. tn1 = t;
  954. t = tn;
  955. tn = ((sine * tn) >> 14) - tn1;
  956. } else { // GENERATOR_MODE_LOOPING // all harmonics
  957. tn = ((sine * tn) >> 14) - tn1;
  958. }
  959. tn1 = t;
  960. }
  961. GeneratorSample s;
  962. // normalization
  963. if (gain <= 65536)
  964. gain = 65536; // avoids extreme amplifications
  965. gain += 256;
  966. s.bipolar = ((bipolar << 13) / gain) << 3;
  967. s.unipolar = (((unipolar << 13) / gain) << 3) + 32768;
  968. s.flags = 0;
  969. if (s.bipolar > 0) {
  970. s.flags |= FLAG_END_OF_ATTACK;
  971. }
  972. if (sub_phase_ & 0x80000000) {
  973. s.flags |= FLAG_END_OF_RELEASE;
  974. }
  975. output_buffer_.Overwrite(s);
  976. sub_phase_ += phase_increment_ >> 1;
  977. phase_ += phase_increment_;
  978. phase_increment_ += phase_increment_increment;
  979. }
  980. }
  981. void Generator::RandomizeHarmonicDistribution() {
  982. for(int i=0;i<kNumHarmonics;++i) {
  983. harm_permut_[i]=i;
  984. }
  985. for (int i = kNumHarmonics-1; i >= 0; --i) {
  986. //generate a random number [0, n-1]
  987. int j = rand() % (i+1);
  988. //swap the last element with element at random index
  989. int temp = harm_permut_[i];
  990. harm_permut_[i] = harm_permut_[j];
  991. harm_permut_[j] = temp;
  992. }
  993. }
  994. uint16_t fold_add(uint16_t a, int16_t b) {
  995. if (a > 0 && b > 65535 - a) {
  996. return 65535 - a - b - 1;
  997. } else if (b < 0 && a < - b) {
  998. return 65535 - a - b + 1;
  999. } else {
  1000. return a + b;
  1001. }
  1002. }
  1003. uint16_t walk_waveshaper(uint16_t shape, bool direction, uint32_t phase_) {
  1004. shape = (shape >> 2) * 3;
  1005. uint16_t idx = shape >> 13;
  1006. uint16_t shape_xfade = shape << 3;
  1007. if (idx == 0) {
  1008. int32_t a = 32767;
  1009. int32_t b = Interpolate115(direction ? wav_spiky_exp_control : wav_bump_exp_control,
  1010. phase_ >> 17);
  1011. return a + ((b - a) * static_cast<int32_t>(shape_xfade) >> 16);
  1012. } else if (idx == 1) {
  1013. return Crossfade115(direction ? wav_spiky_exp_control : wav_bump_exp_control,
  1014. wav_spiky_control,
  1015. phase_ >> 17, shape_xfade);
  1016. } else if (idx == 2) {
  1017. return Crossfade115(wav_spiky_control,
  1018. wav_linear_control,
  1019. phase_ >> 17, shape_xfade);
  1020. } else if (idx == 3) {
  1021. return Crossfade115(wav_linear_control,
  1022. wav_bump_control,
  1023. phase_ >> 17, shape_xfade);
  1024. } else if (idx == 4) {
  1025. return Crossfade115(wav_bump_control,
  1026. direction ? wav_bump_exp_control : wav_spiky_exp_control,
  1027. phase_ >> 17, shape_xfade);
  1028. } else /* if (idx == 5) */ {
  1029. int32_t a = Interpolate115(direction ? wav_bump_exp_control : wav_spiky_exp_control,
  1030. phase_ >> 17);
  1031. int32_t b = (Interpolate115(wav_bipolar_fold, phase_ >> 17) + 32768) >> 1;
  1032. return a + ((b - a) * static_cast<int32_t>(shape_xfade) >> 16);
  1033. }
  1034. }
  1035. inline void Generator::RandomizeDelay() {
  1036. uint32_t period = UINT32_MAX / phase_increment_;
  1037. uint32_t delay_ratio = slope_ + 32768;
  1038. delay_ratio = (delay_ratio * delay_ratio) >> 16; // square knob response
  1039. uint32_t max_delay = (period * delay_ratio) >> 16;
  1040. delay_ = ((Random::GetWord() >> 16) * max_delay) >> 11;
  1041. delayed_phase_increment_ = UINT32_MAX / (period + delay_);
  1042. }
  1043. void Generator::RandomizeDivider() {
  1044. uint16_t skip_prob = slope_ + 32768;
  1045. if (skip_prob > UINT16_MAX - 256)
  1046. divider_ = 1;
  1047. else
  1048. divider_ = Random::GetGeometric(skip_prob) + 1;
  1049. }
  1050. void Generator::FillBufferRandom() {
  1051. uint8_t size = kBlockSize;
  1052. if (sync_) {
  1053. pitch_ = ComputePitch(phase_increment_);
  1054. } else {
  1055. phase_increment_ = ComputePhaseIncrement(pitch_);
  1056. local_osc_phase_increment_ = phase_increment_;
  1057. target_phase_increment_ = phase_increment_;
  1058. }
  1059. while (size--) {
  1060. sync_counter_++;
  1061. uint8_t control = input_buffer_.ImmediateRead();
  1062. // on trigger
  1063. if (control & CONTROL_GATE_RISING) {
  1064. uint16_t skip_prob = slope_ + 32768;
  1065. // start divided osc. after coin toss
  1066. if ((Random::GetWord() >> 16) < skip_prob) {
  1067. running_ = true;
  1068. phase_ = 0;
  1069. divided_phase_ = 0;
  1070. }
  1071. // start delayed osc. after delay
  1072. // or ignore if ongoing delay
  1073. if (!delay_counter_)
  1074. delay_counter_ = 1 + delay_;
  1075. }
  1076. if (delay_counter_) {
  1077. if (delay_counter_ == 1) {
  1078. delayed_phase_ = 0;
  1079. wrap_ = true;
  1080. }
  1081. delay_counter_--;
  1082. }
  1083. if ((control & CONTROL_CLOCK_RISING) && !sync_) {
  1084. range_ = static_cast<GeneratorRange>(Random::GetWord() % 3);
  1085. }
  1086. // on clock in sync mode
  1087. if ((control & CONTROL_CLOCK_RISING) && sync_ && sync_counter_) {
  1088. if (sync_counter_ >= kSyncCounterMaxTime) {
  1089. phase_ = 0;
  1090. } else {
  1091. uint32_t predicted_period = pattern_predictor_.Predict(sync_counter_);
  1092. uint64_t increment = frequency_ratio_.p * static_cast<uint64_t>(
  1093. 0xffffffff / (predicted_period * frequency_ratio_.q));
  1094. if (increment > 0x80000000) {
  1095. increment = 0x80000000;
  1096. }
  1097. phase_increment_ = static_cast<uint32_t>(increment);
  1098. }
  1099. sync_counter_ = 0;
  1100. }
  1101. // on significant slope or pitch variation
  1102. if (phase_ < abs(phase_increment_) &&
  1103. (abs(slope_ - old_slope_) > 4096 ||
  1104. abs(pitch_ - old_pitch_) > 512)) {
  1105. old_slope_ = slope_;
  1106. old_pitch_ = pitch_;
  1107. // recompute delay and divider to avoid waiting for next phase
  1108. // to hear the changes
  1109. RandomizeDelay();
  1110. RandomizeDivider();
  1111. }
  1112. // on delayed phase reset
  1113. if (delayed_phase_ < abs(delayed_phase_increment_)) {
  1114. RandomizeDelay();
  1115. // compute next threshold
  1116. int32_t a = pulse_width_ - (slope_ + 32768) / 2;
  1117. CONSTRAIN(a, 0, UINT16_MAX);
  1118. int32_t b = pulse_width_ + (slope_ + 32768) / 2;
  1119. CONSTRAIN(b, 0, UINT16_MAX);
  1120. uint32_t thresh = (Random::GetWord() >> 16) * (b-a) / INT16_MAX + a;
  1121. uint32_t min_thresh = delayed_phase_increment_ / 3000;
  1122. uint32_t max_thresh = UINT16_MAX - (delayed_phase_increment_ / 3000);
  1123. CONSTRAIN(thresh, min_thresh, max_thresh);
  1124. delayed_threshold_ = thresh;
  1125. // compute next value for ch. 1
  1126. uint32_t step_max = 65536 - (smoothness_ + 32768);
  1127. current_value_[0] = value_[0];
  1128. uint16_t rnd = ((Random::GetWord() >> 16) * step_max) >> 16;
  1129. rnd *= walk_direction_[0] ? 1 : -1;
  1130. next_value_[0] = fold_add(next_value_[0], rnd);
  1131. walk_direction_[0] = !walk_direction_[0];
  1132. }
  1133. // on divided phase reset
  1134. if (divided_phase_ < phase_increment_ / divider_) {
  1135. RandomizeDivider();
  1136. // compute next value for ch. 2
  1137. uint32_t step_max = smoothness_ + 32768;
  1138. current_value_[1] = value_[1];
  1139. uint16_t rnd = ((Random::GetWord() >> 16) * step_max) >> 16;
  1140. rnd *= walk_direction_[1] ? 1 : -1;
  1141. next_value_[1] = fold_add(next_value_[1], rnd);
  1142. walk_direction_[1] = !walk_direction_[1];
  1143. }
  1144. // waveshape phase
  1145. uint16_t shape_1 = static_cast<uint16_t>(shape_ + 32768);
  1146. bool direction_1 = next_value_[0] > current_value_[0];
  1147. uint16_t shaped_phase_1 = walk_waveshaper(shape_1, direction_1, delayed_phase_);
  1148. uint16_t shape_2 = static_cast<uint16_t>(65536 - (shape_ + 32768));
  1149. bool direction_2 = next_value_[1] > current_value_[1];
  1150. uint16_t shaped_phase_2 = walk_waveshaper(shape_2, direction_2, divided_phase_);
  1151. // scale phase to random values
  1152. value_[0] = (next_value_[0] - current_value_[0]) *
  1153. shaped_phase_1 / 32768 + current_value_[0];
  1154. value_[1] = (next_value_[1] - current_value_[1]) *
  1155. shaped_phase_2 / 32768 + current_value_[1];
  1156. // compute clocks
  1157. bool clock_ch1 = (delayed_phase_ >> 16) < delayed_threshold_;
  1158. uint32_t min_pw = phase_increment_ / divider_ / 3000;
  1159. uint32_t max_pw = UINT16_MAX - (phase_increment_ / 3000);
  1160. uint32_t pw = pulse_width_;
  1161. CONSTRAIN(pw, min_pw, max_pw);
  1162. bool clock = (phase_ >> 16) < pw;
  1163. bool clock_ch2 = divider_counter_ == 0 && clock;
  1164. // emit sample
  1165. GeneratorSample s;
  1166. s.unipolar = value_[0];
  1167. s.bipolar = value_[1] - 32768;
  1168. s.flags = 0
  1169. | (clock_ch1 ? FLAG_END_OF_ATTACK : 0)
  1170. | (clock_ch2 ? FLAG_END_OF_RELEASE : 0);
  1171. output_buffer_.Overwrite(s);
  1172. /* note: we use running_ and wrap_ to store the state
  1173. * (running/stopped) of resp. the divided and the delayed
  1174. * oscillator */
  1175. // on main phase reset
  1176. if (phase_ < abs(phase_increment_)) {
  1177. }
  1178. // just before main phase reset
  1179. if (running_ && phase_ > UINT32_MAX - phase_increment_) {
  1180. divider_counter_ = (divider_counter_ + 1) % divider_;
  1181. // stop the divided oscillator on reset
  1182. if (divider_counter_ == 0 &&
  1183. ((mode_ == GENERATOR_MODE_AD) ||
  1184. (control & CONTROL_FREEZE) ||
  1185. (mode_ == GENERATOR_MODE_AR && !(control & CONTROL_GATE))))
  1186. running_ = false;
  1187. }
  1188. // just before delayed phase reset
  1189. if (wrap_ && delayed_phase_ > UINT32_MAX - delayed_phase_increment_) {
  1190. // stop the delayed oscillator
  1191. if (((mode_ == GENERATOR_MODE_AD) ||
  1192. (control & CONTROL_FREEZE) ||
  1193. (mode_ == GENERATOR_MODE_AR && !(control & CONTROL_GATE))))
  1194. wrap_ = false;
  1195. }
  1196. // restart the oscillator if needed
  1197. if (!(control & CONTROL_FREEZE) &&
  1198. ((mode_ == GENERATOR_MODE_LOOPING) ||
  1199. (mode_ == GENERATOR_MODE_AR && (control & CONTROL_GATE))))
  1200. running_ = wrap_ = true;
  1201. // increment phasors
  1202. if (wrap_) {
  1203. delayed_phase_ += delayed_phase_increment_;
  1204. }
  1205. if (running_) {
  1206. phase_ += phase_increment_;
  1207. divided_phase_ = phase_ / divider_ +
  1208. UINT32_MAX / divider_ * divider_counter_;
  1209. }
  1210. }
  1211. }
  1212. } // namespace tides