nidhi 1.1.0

nidhi — Sample playback engine: key/velocity zones, loop modes, time-stretching, SFZ/SF2 import
Documentation
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Sample storage — loaded audio waveforms and a sample bank.

use alloc::string::String;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};

/// Unique identifier for a sample in a [`SampleBank`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[must_use]
pub struct SampleId(pub u32);

/// A loaded audio sample — mono or stereo f32 data at a known sample rate.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[must_use]
pub struct Sample {
    /// Sample data (interleaved if stereo).
    pub(crate) data: Vec<f32>,
    /// Number of channels (1 = mono, 2 = stereo).
    pub(crate) channels: u32,
    /// Sample rate in Hz.
    pub(crate) sample_rate: u32,
    /// Number of frames (samples per channel).
    pub(crate) frames: usize,
    /// Optional name/label.
    pub(crate) name: String,
    /// REX-style slice points (frame indices).
    pub(crate) slices: Vec<usize>,
}

impl Sample {
    /// Create a mono sample from raw f32 data.
    pub fn from_mono(data: Vec<f32>, sample_rate: u32) -> Self {
        let frames = data.len();
        Self {
            data,
            channels: 1,
            sample_rate,
            frames,
            name: String::new(),
            slices: Vec::new(),
        }
    }

    /// Create a stereo sample from interleaved f32 data.
    pub fn from_stereo(data: Vec<f32>, sample_rate: u32) -> Self {
        let frames = data.len() / 2;
        Self {
            data,
            channels: 2,
            sample_rate,
            frames,
            name: String::new(),
            slices: Vec::new(),
        }
    }

    /// Set the sample name.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Set slice points manually.
    pub fn with_slices(mut self, slices: Vec<usize>) -> Self {
        self.slices = slices;
        self
    }

    /// Get slice points.
    #[inline]
    pub fn slices(&self) -> &[usize] {
        &self.slices
    }

    /// Auto-detect slice points via onset detection (energy-based transient detection).
    ///
    /// `threshold` controls sensitivity (0.0–1.0, lower = more slices).
    /// `min_slice_frames` is the minimum distance between slices.
    pub fn detect_onsets(&mut self, threshold: f32, min_slice_frames: usize) {
        self.slices.clear();
        if self.frames < 2 {
            return;
        }

        let window = 512.min(self.frames / 2).max(1);
        let hop = (window / 2).max(1);
        let threshold = threshold.clamp(0.01, 1.0);

        // Compute energy per window
        let mut energies = Vec::new();
        let mut pos = 0;
        while pos + window <= self.frames {
            let mut energy = 0.0f32;
            for i in pos..pos + window {
                let s = if self.channels == 1 {
                    self.data[i]
                } else {
                    (self.data[i * 2] + self.data[i * 2 + 1]) * 0.5
                };
                energy += s * s;
            }
            energies.push((pos, energy / window as f32));
            pos += hop;
        }

        if energies.len() < 2 {
            return;
        }

        // Find peak energy for normalization
        let max_energy = energies.iter().map(|(_, e)| *e).fold(0.0f32, f32::max);

        if max_energy < 1e-10 {
            return;
        }

        // Detect onsets: significant energy increase between consecutive windows
        let mut last_slice = 0usize;
        for i in 1..energies.len() {
            let (frame, energy) = energies[i];
            let prev_energy = energies[i - 1].1;
            let diff = (energy - prev_energy) / max_energy;

            if diff > threshold && frame.saturating_sub(last_slice) >= min_slice_frames {
                self.slices.push(frame);
                last_slice = frame;
            }
        }
    }

    /// Sample data.
    #[inline]
    #[must_use]
    pub fn data(&self) -> &[f32] {
        &self.data
    }

    /// Number of channels.
    #[inline]
    #[must_use]
    pub fn channels(&self) -> u32 {
        self.channels
    }

    /// Sample rate in Hz.
    #[inline]
    #[must_use]
    pub fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    /// Number of frames.
    #[inline]
    #[must_use]
    pub fn frames(&self) -> usize {
        self.frames
    }

    /// Sample name.
    #[inline]
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Read a mono frame at the given index, clamping to bounds.
    ///
    /// For stereo samples, averages L+R.
    #[inline]
    fn read_mono_frame(&self, idx: isize) -> f32 {
        if idx < 0 || idx as usize >= self.frames {
            return 0.0;
        }
        let i = idx as usize;
        if self.channels == 1 {
            self.data[i]
        } else {
            let ch = self.channels as usize;
            (self.data[i * ch] + self.data[i * ch + 1]) * 0.5
        }
    }

    /// Read a stereo frame at the given index, clamping to bounds.
    ///
    /// For mono samples, returns `(sample, sample)`.
    #[inline]
    fn read_stereo_frame(&self, idx: isize) -> (f32, f32) {
        if idx < 0 || idx as usize >= self.frames {
            return (0.0, 0.0);
        }
        let i = idx as usize;
        if self.channels == 1 {
            let v = self.data[i];
            (v, v)
        } else {
            let ch = self.channels as usize;
            (self.data[i * ch], self.data[i * ch + 1])
        }
    }

    /// Cubic Hermite (Catmull-Rom) interpolation between four points.
    ///
    /// `y0..y3` are sample values at positions `idx-1, idx, idx+1, idx+2`.
    /// `t` is the fractional position between `y1` and `y2` (0.0–1.0).
    #[inline]
    #[must_use]
    pub fn cubic_hermite(y0: f32, y1: f32, y2: f32, y3: f32, t: f32) -> f32 {
        let a = -0.5 * y0 + 1.5 * y1 - 1.5 * y2 + 0.5 * y3;
        let b = y0 - 2.5 * y1 + 2.0 * y2 - 0.5 * y3;
        let c = -0.5 * y0 + 0.5 * y2;
        let d = y1;
        ((a * t + b) * t + c) * t + d
    }

    /// Read a mono value using cubic Hermite interpolation.
    ///
    /// Uses four points around the position for smooth interpolation.
    /// For stereo, averages L+R.
    #[inline]
    #[must_use]
    pub fn read_cubic(&self, position: f64) -> f32 {
        if self.frames == 0 {
            return 0.0;
        }
        let idx = position.floor() as isize;
        let frac = (position - idx as f64) as f32;

        let y0 = self.read_mono_frame(idx - 1);
        let y1 = self.read_mono_frame(idx);
        let y2 = self.read_mono_frame(idx + 1);
        let y3 = self.read_mono_frame(idx + 2);

        Self::cubic_hermite(y0, y1, y2, y3, frac)
    }

    /// Read a frame at the given position with cubic Hermite interpolation.
    ///
    /// Returns mono sample value. For stereo, averages L+R.
    #[inline]
    #[must_use]
    pub fn read_interpolated(&self, position: f64) -> f32 {
        self.read_cubic(position)
    }

    /// Read a stereo frame with cubic Hermite interpolation.
    ///
    /// Returns `(left, right)`. For mono samples, both channels are identical.
    ///
    /// When the `simd` feature is enabled on x86_64, both channels are computed
    /// in a single SIMD pass using SSE.
    #[inline]
    #[must_use]
    pub fn read_stereo_interpolated(&self, position: f64) -> (f32, f32) {
        if self.frames == 0 {
            return (0.0, 0.0);
        }
        let idx = position.floor() as isize;
        let frac = (position - idx as f64) as f32;

        let (l0, r0) = self.read_stereo_frame(idx - 1);
        let (l1, r1) = self.read_stereo_frame(idx);
        let (l2, r2) = self.read_stereo_frame(idx + 1);
        let (l3, r3) = self.read_stereo_frame(idx + 2);

        #[cfg(all(feature = "simd", target_arch = "x86_64"))]
        {
            Self::cubic_hermite_stereo_sse(l0, r0, l1, r1, l2, r2, l3, r3, frac)
        }
        #[cfg(not(all(feature = "simd", target_arch = "x86_64")))]
        {
            let left = Self::cubic_hermite(l0, l1, l2, l3, frac);
            let right = Self::cubic_hermite(r0, r1, r2, r3, frac);
            (left, right)
        }
    }

    /// SSE-accelerated stereo cubic Hermite interpolation.
    ///
    /// Computes both L and R channels simultaneously using packed f32x4:
    /// lanes 0,1 = L,R for each coefficient, evaluated via Horner's method.
    #[cfg(all(feature = "simd", target_arch = "x86_64"))]
    #[inline]
    #[allow(unsafe_code, clippy::too_many_arguments)]
    fn cubic_hermite_stereo_sse(
        l0: f32,
        r0: f32,
        l1: f32,
        r1: f32,
        l2: f32,
        r2: f32,
        l3: f32,
        r3: f32,
        t: f32,
    ) -> (f32, f32) {
        use core::arch::x86_64::*;
        // SAFETY: SSE2 is baseline on x86_64.
        unsafe {
            // Pack L,R pairs: y0 = [l0, r0, 0, 0], etc.
            let y0 = _mm_set_ps(0.0, 0.0, r0, l0);
            let y1 = _mm_set_ps(0.0, 0.0, r1, l1);
            let y2 = _mm_set_ps(0.0, 0.0, r2, l2);
            let y3 = _mm_set_ps(0.0, 0.0, r3, l3);
            let tv = _mm_set1_ps(t);

            // a = -0.5*y0 + 1.5*y1 - 1.5*y2 + 0.5*y3
            let half = _mm_set1_ps(0.5);
            let one_half = _mm_set1_ps(1.5);
            let a = _mm_add_ps(
                _mm_add_ps(_mm_mul_ps(_mm_set1_ps(-0.5), y0), _mm_mul_ps(one_half, y1)),
                _mm_add_ps(_mm_mul_ps(_mm_set1_ps(-1.5), y2), _mm_mul_ps(half, y3)),
            );
            // b = y0 - 2.5*y1 + 2.0*y2 - 0.5*y3
            let b = _mm_add_ps(
                _mm_add_ps(y0, _mm_mul_ps(_mm_set1_ps(-2.5), y1)),
                _mm_add_ps(
                    _mm_mul_ps(_mm_set1_ps(2.0), y2),
                    _mm_mul_ps(_mm_set1_ps(-0.5), y3),
                ),
            );
            // c = -0.5*y0 + 0.5*y2
            let c = _mm_add_ps(_mm_mul_ps(_mm_set1_ps(-0.5), y0), _mm_mul_ps(half, y2));
            // d = y1
            // Horner: ((a*t + b)*t + c)*t + d
            let result = _mm_add_ps(
                _mm_mul_ps(
                    _mm_add_ps(_mm_mul_ps(_mm_add_ps(_mm_mul_ps(a, tv), b), tv), c),
                    tv,
                ),
                y1,
            );

            // Extract L and R from lanes 0 and 1
            let mut out = [0.0f32; 4];
            _mm_storeu_ps(out.as_mut_ptr(), result);
            (out[0], out[1])
        }
    }
}

/// A bank of loaded samples, addressable by [`SampleId`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[must_use]
pub struct SampleBank {
    samples: Vec<Sample>,
}

impl SampleBank {
    /// Create an empty sample bank.
    pub fn new() -> Self {
        Self {
            samples: Vec::new(),
        }
    }

    /// Add a sample to the bank. Returns its [`SampleId`].
    pub fn add(&mut self, sample: Sample) -> SampleId {
        let id = SampleId(self.samples.len() as u32);
        self.samples.push(sample);
        id
    }

    /// Get a sample by ID.
    #[inline]
    pub fn get(&self, id: SampleId) -> Option<&Sample> {
        self.samples.get(id.0 as usize)
    }

    /// Number of samples in the bank.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.samples.len()
    }

    /// Whether the bank is empty.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.samples.is_empty()
    }
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;

    #[test]
    fn sample_from_mono() {
        let s = Sample::from_mono(vec![0.5; 100], 44100).with_name("test");
        assert_eq!(s.channels(), 1);
        assert_eq!(s.frames(), 100);
        assert_eq!(s.name(), "test");
    }

    #[test]
    fn sample_interpolation() {
        // Cubic Hermite with 4 points: for a linear ramp, should interpolate exactly
        let s = Sample::from_mono(vec![0.0, 0.25, 0.5, 0.75, 1.0], 44100);
        assert!((s.read_interpolated(2.0) - 0.5).abs() < 0.01);
        assert!((s.read_interpolated(2.5) - 0.625).abs() < 0.01);
        // Peak sample reads exactly
        let s2 = Sample::from_mono(vec![0.0, 0.0, 1.0, 0.0, 0.0], 44100);
        assert!((s2.read_interpolated(2.0) - 1.0).abs() < 0.01);
    }

    #[test]
    fn cubic_hermite_smooth() {
        // A ramp: 0, 1, 2, 3 — cubic should give exact linear result
        let v = Sample::cubic_hermite(0.0, 1.0, 2.0, 3.0, 0.5);
        assert!((v - 1.5).abs() < 0.01);
    }

    #[test]
    fn read_cubic_basic() {
        let s = Sample::from_mono(vec![0.0, 0.0, 1.0, 0.0, 0.0], 44100);
        let v = s.read_cubic(2.0);
        assert!((v - 1.0).abs() < 0.01);
    }

    #[test]
    fn read_stereo_interpolated_basic() {
        // Stereo: L=1.0, R=0.0 at every frame
        let data = vec![1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0];
        let s = Sample::from_stereo(data, 44100);
        let (l, r) = s.read_stereo_interpolated(1.5);
        assert!((l - 1.0).abs() < 0.01);
        assert!(r.abs() < 0.01);
    }

    #[test]
    fn read_stereo_interpolated_mono_duplicates() {
        let s = Sample::from_mono(vec![0.5, 0.5, 0.5, 0.5], 44100);
        let (l, r) = s.read_stereo_interpolated(1.0);
        assert!((l - 0.5).abs() < 0.01);
        assert!((r - 0.5).abs() < 0.01);
    }

    #[test]
    fn bank_add_get() {
        let mut bank = SampleBank::new();
        let id = bank.add(Sample::from_mono(vec![0.0; 10], 44100));
        assert!(bank.get(id).is_some());
        assert_eq!(bank.len(), 1);
    }

    #[test]
    fn detect_onsets_finds_transients() {
        // Long silence then loud burst — onset should be detected
        let mut data = vec![0.0f32; 8000];
        for s in data.iter_mut().take(4500).skip(4000) {
            *s = 0.9;
        }
        let mut s = Sample::from_mono(data, 44100);
        s.detect_onsets(0.1, 256);
        assert!(!s.slices().is_empty(), "should detect at least one onset");
        // Onset should be somewhere in the vicinity of the burst
        let first = s.slices()[0];
        assert!(
            (3500..=5000).contains(&first),
            "slice at {first} should be near burst at 4000"
        );
    }

    #[test]
    fn detect_onsets_empty_sample() {
        let mut s = Sample::from_mono(vec![], 44100);
        s.detect_onsets(0.1, 100);
        assert!(s.slices().is_empty());
    }

    #[test]
    fn detect_onsets_silence() {
        let mut s = Sample::from_mono(vec![0.0; 4000], 44100);
        s.detect_onsets(0.1, 100);
        assert!(s.slices().is_empty(), "silence should produce no onsets");
    }

    #[test]
    fn detect_onsets_very_short_sample() {
        // Regression: frames <= 3 caused hop=0 and infinite loop
        let mut s = Sample::from_mono(vec![0.5, -0.5], 44100);
        s.detect_onsets(0.1, 1);
        // Just verifying it terminates without hanging

        let mut s = Sample::from_mono(vec![0.5, -0.5, 0.3], 44100);
        s.detect_onsets(0.1, 1);
    }

    #[test]
    fn manual_slices() {
        let s = Sample::from_mono(vec![0.0; 1000], 44100).with_slices(vec![100, 500, 800]);
        assert_eq!(s.slices(), &[100, 500, 800]);
    }
}