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