1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// Copyright (c) 2021-2022 Weird Constructor <weirdconstructor@gmail.com>
// This file is a part of HexoDSP. Released under GPL-3.0-or-later.
// See README.md and COPYING for details.

///! Contains various utilities for trigger signals in a modular synthesizer.
///
/// There are also clock synchronizing helpers in here like [TriggerPhaseClock]
/// or [TriggerSampleClock].

/// A-100 Eurorack states, that a trigger is usually 2-10 milliseconds.
pub const TRIG_SIGNAL_LENGTH_MS: f32 = 2.0;

/// The lower threshold for the schmidt trigger to reset.
pub const TRIG_LOW_THRES: f32 = 0.25;
/// The threshold, once reached, will cause a trigger event and signals
/// a logical '1'. Anything below this is a logical '0'.
pub const TRIG_HIGH_THRES: f32 = 0.5;

/// Gate signal generator for HexoDSP nodes.
///
/// This generator generates a gate signal when [GateSignal::trigger] is called.
/// The length is given as parameter to [GateSignal::next].
#[derive(Debug, Clone, Copy)]
pub struct GateSignal {
    ms_per_sample: f32,
    ms_count: f32,
}

impl GateSignal {
    /// Create a new gate generator
    pub fn new() -> Self {
        Self { ms_per_sample: 1000.0 / 44100.0, ms_count: 0.0 }
    }

    /// Reset the gate generator.
    pub fn reset(&mut self) {
        self.ms_count = 0.0;
    }

    /// Set the sample rate
    pub fn set_sample_rate(&mut self, srate: f32) {
        self.ms_per_sample = 1000.0 / srate;
    }

    /// Start a new gate the next time [TrigSignal::next] is called.
    #[inline]
    pub fn trigger(&mut self) {
        self.ms_count = 0.0001;
    }

    /// Gate signal output, the length is given via 'length_ms'.
    #[inline]
    pub fn next(&mut self, length_ms: f32) -> f32 {
        if self.ms_count > 0.0 {
            self.ms_count += self.ms_per_sample;
            if (self.ms_count - 0.0001) > length_ms {
                self.ms_count = 0.0;
            }
            1.0
        } else {
            0.0
        }
    }
}

impl Default for GateSignal {
    fn default() -> Self {
        Self::new()
    }
}

/// Trigger signal generator for HexoDSP nodes.
///
/// A trigger in HexoSynth and HexoDSP is commonly 2.0 milliseconds.
/// This generator generates a trigger signal when [TrigSignal::trigger] is called.
#[derive(Debug, Clone, Copy)]
pub struct TrigSignal {
    length: u32,
    scount: u32,
}

impl TrigSignal {
    /// Create a new trigger generator
    pub fn new() -> Self {
        Self { length: ((44100.0 * TRIG_SIGNAL_LENGTH_MS) / 1000.0).ceil() as u32, scount: 0 }
    }

    /// Reset the trigger generator.
    pub fn reset(&mut self) {
        self.scount = 0;
    }

    /// Set the sample rate to calculate the amount of samples for the trigger signal.
    pub fn set_sample_rate(&mut self, srate: f32) {
        self.length = ((srate * TRIG_SIGNAL_LENGTH_MS) / 1000.0).ceil() as u32;
        self.scount = 0;
    }

    /// Enable sending a trigger impulse the next time [TrigSignal::next] is called.
    #[inline]
    pub fn trigger(&mut self) {
        self.scount = self.length;
    }

    /// Trigger signal output.
    #[inline]
    pub fn next(&mut self) -> f32 {
        if self.scount > 0 {
            self.scount -= 1;
            1.0
        } else {
            0.0
        }
    }
}

impl Default for TrigSignal {
    fn default() -> Self {
        Self::new()
    }
}

/// Signal change detector that emits a trigger when the input signal changed.
///
/// This is commonly used for control signals. It has not much use for audio signals.
#[derive(Debug, Clone, Copy)]
pub struct ChangeTrig {
    ts: TrigSignal,
    last: f32,
}

impl ChangeTrig {
    /// Create a new change detector
    pub fn new() -> Self {
        Self {
            ts: TrigSignal::new(),
            last: -100.0, // some random value :-)
        }
    }

    /// Reset internal state.
    pub fn reset(&mut self) {
        self.ts.reset();
        self.last = -100.0;
    }

    /// Set the sample rate for the trigger signal generator
    pub fn set_sample_rate(&mut self, srate: f32) {
        self.ts.set_sample_rate(srate);
    }

    /// Feed a new input signal sample.
    ///
    /// The return value is the trigger signal.
    #[inline]
    pub fn next(&mut self, inp: f32) -> f32 {
        if (inp - self.last).abs() > std::f32::EPSILON {
            self.ts.trigger();
            self.last = inp;
        }

        self.ts.next()
    }
}

impl Default for ChangeTrig {
    fn default() -> Self {
        Self::new()
    }
}

/// Trigger signal detector for HexoDSP.
///
/// Whenever you need to detect a trigger on an input you can use this component.
/// A trigger in HexoDSP is any signal over [TRIG_HIGH_THRES]. The internal state is
/// resetted when the signal drops below [TRIG_LOW_THRES].
#[derive(Debug, Clone, Copy)]
pub struct Trigger {
    triggered: bool,
}

impl Trigger {
    /// Create a new trigger detector.
    pub fn new() -> Self {
        Self { triggered: false }
    }

    /// Reset the internal state of the trigger detector.
    #[inline]
    pub fn reset(&mut self) {
        self.triggered = false;
    }

    /// Checks the input signal for a trigger and returns true when the signal
    /// surpassed [TRIG_HIGH_THRES] and has not fallen below [TRIG_LOW_THRES] yet.
    #[inline]
    pub fn check_trigger(&mut self, input: f32) -> bool {
        if self.triggered {
            if input <= TRIG_LOW_THRES {
                self.triggered = false;
            }

            false
        } else if input > TRIG_HIGH_THRES {
            self.triggered = true;
            true
        } else {
            false
        }
    }
}

/// Trigger signal detector with custom range.
///
/// Whenever you need to detect a trigger with a custom threshold.
#[derive(Debug, Clone, Copy)]
pub struct CustomTrigger {
    triggered: bool,
    low_thres: f32,
    high_thres: f32,
}

impl CustomTrigger {
    /// Create a new trigger detector.
    pub fn new(low_thres: f32, high_thres: f32) -> Self {
        Self { triggered: false, low_thres, high_thres }
    }

    pub fn set_threshold(&mut self, low_thres: f32, high_thres: f32) {
        self.low_thres = low_thres;
        self.high_thres = high_thres;
    }

    /// Reset the internal state of the trigger detector.
    #[inline]
    pub fn reset(&mut self) {
        self.triggered = false;
    }

    /// Checks the input signal for a trigger and returns true when the signal
    /// surpassed the high threshold and has not fallen below low threshold yet.
    #[inline]
    pub fn check_trigger(&mut self, input: f32) -> bool {
        //        println!("TRIG CHECK: {} <> {}", input, self.high_thres);
        if self.triggered {
            if input <= self.low_thres {
                self.triggered = false;
            }

            false
        } else if input > self.high_thres {
            self.triggered = true;
            true
        } else {
            false
        }
    }
}

/// Generates a phase signal from a trigger/gate input signal.
///
/// This helper allows you to measure the distance between trigger or gate pulses
/// and generates a phase signal for you that increases from 0.0 to 1.0.
#[derive(Debug, Clone, Copy)]
pub struct TriggerPhaseClock {
    clock_phase: f64,
    clock_inc: f64,
    prev_trigger: bool,
    clock_samples: u32,
}

impl TriggerPhaseClock {
    /// Create a new phase clock.
    pub fn new() -> Self {
        Self { clock_phase: 0.0, clock_inc: 0.0, prev_trigger: true, clock_samples: 0 }
    }

    /// Reset the phase clock.
    #[inline]
    pub fn reset(&mut self) {
        self.clock_samples = 0;
        self.clock_inc = 0.0;
        self.prev_trigger = true;
        self.clock_samples = 0;
    }

    /// Restart the phase clock. It will count up from 0.0 again on [TriggerPhaseClock::next_phase].
    #[inline]
    pub fn sync(&mut self) {
        self.clock_phase = 0.0;
    }

    /// Generate the phase signal of this clock.
    ///
    /// * `clock_limit` - The maximum number of samples to detect two trigger signals in.
    /// * `trigger_in` - Trigger signal input.
    #[inline]
    pub fn next_phase(&mut self, clock_limit: f64, trigger_in: f32) -> f64 {
        if self.prev_trigger {
            if trigger_in <= TRIG_LOW_THRES {
                self.prev_trigger = false;
            }
        } else if trigger_in > TRIG_HIGH_THRES {
            self.prev_trigger = true;

            if self.clock_samples > 0 {
                self.clock_inc = 1.0 / (self.clock_samples as f64);
            }

            self.clock_samples = 0;
        }

        self.clock_samples += 1;

        self.clock_phase += self.clock_inc;
        self.clock_phase = self.clock_phase % clock_limit;

        self.clock_phase
    }
}

#[derive(Debug, Clone, Copy)]
pub struct TriggerSampleClock {
    prev_trigger: bool,
    clock_samples: u32,
    counter: u32,
}

impl TriggerSampleClock {
    pub fn new() -> Self {
        Self { prev_trigger: true, clock_samples: 0, counter: 0 }
    }

    #[inline]
    pub fn reset(&mut self) {
        self.clock_samples = 0;
        self.counter = 0;
    }

    #[inline]
    pub fn next(&mut self, trigger_in: f32) -> u32 {
        if self.prev_trigger {
            if trigger_in <= TRIG_LOW_THRES {
                self.prev_trigger = false;
            }
        } else if trigger_in > TRIG_HIGH_THRES {
            self.prev_trigger = true;
            self.clock_samples = self.counter;
            self.counter = 0;
        }

        self.counter += 1;

        self.clock_samples
    }
}