fluidlite 0.2.1

Safe bindings to fluidlite library
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
use crate::{ffi, result_from_ptr, Result};
use bitflags::bitflags;
use std::{
    ffi::{CStr, CString},
    marker::PhantomData,
    mem::{transmute, MaybeUninit},
    ops::{Bound, RangeBounds},
    os::raw,
};

/**
The generic settings object
 */
#[repr(transparent)]
pub struct Settings {
    handle: *mut ffi::fluid_settings_t,
}

unsafe impl Send for Settings {}

/**
The settings reference
*/
#[repr(transparent)]
pub struct SettingsRef<'a> {
    handle: *mut ffi::fluid_settings_t,
    phantom: PhantomData<&'a ()>,
}

impl Drop for Settings {
    fn drop(&mut self) {
        unsafe { ffi::delete_fluid_settings(self.handle) }
    }
}

impl Settings {
    pub fn new() -> Result<Self> {
        result_from_ptr(unsafe { ffi::new_fluid_settings() }).map(|handle| Self { handle })
    }

    pub(crate) fn into_ptr(self) -> *mut ffi::fluid_settings_t {
        unsafe { transmute(self) }
    }

    pub(crate) fn from_ptr(handle: *mut ffi::fluid_settings_t) -> Self {
        Self { handle }
    }
}

impl<'a> SettingsRef<'a> {
    pub(crate) fn from_ptr(handle: *mut ffi::fluid_settings_t) -> Self {
        Self {
            handle,
            phantom: PhantomData,
        }
    }
}

/**
The settings interface
 */
pub trait IsSettings {
    fn pick<S, T>(&self, name: S) -> Option<Setting<'_, T>>
    where
        S: Into<Vec<u8>>,
        T: IsSetting + ?Sized;

    fn str_<S>(&self, name: S) -> Option<Setting<'_, str>>
    where
        S: Into<Vec<u8>>;

    fn num<S>(&self, name: S) -> Option<Setting<'_, f64>>
    where
        S: Into<Vec<u8>>;

    fn int<S>(&self, name: S) -> Option<Setting<'_, i32>>
    where
        S: Into<Vec<u8>>;
}

mod private {
    use crate::{ffi, private::HasHandle, IsSetting, IsSettings, Setting, Settings, SettingsRef};
    use std::{ffi::CString, marker::PhantomData};

    impl<X> IsSettings for X
    where
        X: HasHandle<Handle = ffi::fluid_settings_t>,
    {
        fn pick<S, T>(&self, name: S) -> Option<Setting<'_, T>>
        where
            S: Into<Vec<u8>>,
            T: IsSetting + ?Sized,
        {
            let handle = self.get_handle();
            let name = CString::new(name).ok()?;

            if T::TYPE == unsafe { ffi::fluid_settings_get_type(handle, name.as_ptr() as *const _) }
            {
                Some(Setting {
                    handle,
                    name,
                    phantom: PhantomData,
                })
            } else {
                None
            }
        }

        fn str_<S>(&self, name: S) -> Option<Setting<'_, str>>
        where
            S: Into<Vec<u8>>,
        {
            self.pick(name)
        }

        fn num<S>(&self, name: S) -> Option<Setting<'_, f64>>
        where
            S: Into<Vec<u8>>,
        {
            self.pick(name)
        }

        fn int<S>(&self, name: S) -> Option<Setting<'_, i32>>
        where
            S: Into<Vec<u8>>,
        {
            self.pick(name)
        }
    }

    impl HasHandle for Settings {
        type Handle = ffi::fluid_settings_t;

        fn get_handle(&self) -> *mut Self::Handle {
            self.handle
        }
    }

    impl<'a> HasHandle for SettingsRef<'a> {
        type Handle = ffi::fluid_settings_t;

        fn get_handle(&self) -> *mut Self::Handle {
            self.handle
        }
    }
}

/**
The single setting object interface
 */
pub trait IsSetting {
    const TYPE: ffi::fluid_types_enum;
}

impl IsSetting for str {
    const TYPE: ffi::fluid_types_enum = ffi::fluid_types_enum_FLUID_STR_TYPE;
}

impl IsSetting for f64 {
    const TYPE: ffi::fluid_types_enum = ffi::fluid_types_enum_FLUID_NUM_TYPE;
}

impl IsSetting for i32 {
    const TYPE: ffi::fluid_types_enum = ffi::fluid_types_enum_FLUID_INT_TYPE;
}

impl IsSetting for () {
    const TYPE: ffi::fluid_types_enum = ffi::fluid_types_enum_FLUID_SET_TYPE;
}

bitflags! {
    /**
    The setting hints
     */
    pub struct Hints: i32 {
        /**
        Hint BOUNDED_BELOW indicates that the LowerBound field
        of the FLUID_PortRangeHint should be considered meaningful. The
        value in this field should be considered the (inclusive) lower
        bound of the valid range. If SAMPLE_RATE is also
        specified then the value of LowerBound should be multiplied by the
        sample rate.
         */
        const BOUNDED_BELOW = ffi::FLUID_HINT_BOUNDED_BELOW as i32;

        /**
        Hint BOUNDED_ABOVE indicates that the UpperBound field
        of the FLUID_PortRangeHint should be considered meaningful. The
        value in this field should be considered the (inclusive) upper
        bound of the valid range. If SAMPLE_RATE is also
        specified then the value of UpperBound should be multiplied by the
        sample rate.
         */
        const BOUNDED_ABOVE = ffi::FLUID_HINT_BOUNDED_ABOVE as i32;

        /**
        Hint TOGGLED indicates that the data item should be
        considered a Boolean toggle. Data less than or equal to zero should
        be considered `off' or `false,' and data above zero should be
        considered `on' or `true.' TOGGLED may not be used in
        conjunction with any other hint except DEFAULT_0 or
        DEFAULT_1.
         */
        const TOGGLED = ffi::FLUID_HINT_TOGGLED as i32;

        /**
        Hint SAMPLE_RATE indicates that any bounds specified
        should be interpreted as multiples of the sample rate. For
        instance, a frequency range from 0Hz to the Nyquist frequency (half
        the sample rate) could be requested by this hint in conjunction
        with LowerBound = 0 and UpperBound = 0.5. Hosts that support bounds
        at all must support this hint to retain meaning.
         */
        const SAMPLE_RATE = ffi::FLUID_HINT_SAMPLE_RATE as i32;

        /**
        Hint LOGARITHMIC indicates that it is likely that the
        user will find it more intuitive to view values using a logarithmic
        scale. This is particularly useful for frequencies and gains.
         */
        const LOGARITHMIC = ffi::FLUID_HINT_LOGARITHMIC as i32;

        /**
        Hint INTEGER indicates that a user interface would
        probably wish to provide a stepped control taking only integer
        values. Any bounds set should be slightly wider than the actual
        integer range required to avoid floating point rounding errors. For
        instance, the integer set {0,1,2,3} might be described as [-0.1,
        3.1].
         */
        const INTEGER = ffi::FLUID_HINT_INTEGER as i32;

        const FILENAME = ffi::FLUID_HINT_FILENAME as i32;

        const OPTIONLIST = ffi::FLUID_HINT_OPTIONLIST as i32;
    }
}

/**
The single setting of specific type
 */
pub struct Setting<'a, T: ?Sized> {
    handle: *mut ffi::fluid_settings_t,
    name: CString,
    phantom: PhantomData<(&'a (), T)>,
}

impl<'a, T> Setting<'a, T>
where
    T: ?Sized,
{
    #[inline]
    fn name_ptr(&self) -> *const raw::c_char {
        self.name.as_ptr() as *const _
    }

    pub fn hints(&self) -> Hints {
        Hints::from_bits_truncate(unsafe {
            ffi::fluid_settings_get_hints(self.handle, self.name_ptr())
        })
    }

    /** Returns whether the setting is changeable in real-time
     */
    pub fn is_realtime(&self) -> bool {
        0 < unsafe { ffi::fluid_settings_is_realtime(self.handle, self.name_ptr()) }
    }
}

impl<'a> Setting<'a, str> {
    /**
    Set the value of a string setting

    Returns `true` if the value has been set, `false` otherwise
     */
    pub fn set<S: Into<String>>(&self, value: S) -> bool {
        let mut value = value.into();
        value.push('\0');
        0 < unsafe {
            ffi::fluid_settings_setstr(self.handle, self.name_ptr(), value.as_ptr() as *const _)
        }
    }

    /**
    Get the value of a string setting

    Returns `Some("value")` if the value exists, `None` otherwise
     */
    pub fn get(&self) -> Option<&str> {
        let mut value = MaybeUninit::uninit();

        if 0 < unsafe {
            ffi::fluid_settings_getstr(self.handle, self.name_ptr(), value.as_mut_ptr())
        } {
            let value = unsafe { value.assume_init() };
            let value = unsafe { CStr::from_ptr(value) };
            value.to_str().ok()
        } else {
            None
        }
    }

    /**
    Get the default value of a string setting
     */
    pub fn default(&self) -> &str {
        let value = unsafe { ffi::fluid_settings_getstr_default(self.handle, self.name_ptr()) };
        let value = unsafe { CStr::from_ptr(value) };
        value.to_str().unwrap()
    }
}

impl<'a, S> PartialEq<S> for Setting<'a, str>
where
    S: AsRef<str>,
{
    fn eq(&self, other: &S) -> bool {
        let mut other = String::from(other.as_ref());
        other.push('\0');
        0 < unsafe {
            ffi::fluid_settings_str_equal(self.handle, self.name_ptr(), other.as_ptr() as *mut _)
        }
    }
}

/**
The range of setting value
 */
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Range<T> {
    /// Below limit
    pub min: Option<T>,
    /// Above limit
    pub max: Option<T>,
}

impl<T> Range<T> {
    pub fn new(min: Option<T>, max: Option<T>) -> Self {
        Self { min, max }
    }

    fn new_unsafe(min: MaybeUninit<T>, max: MaybeUninit<T>, hints: Hints) -> Self {
        Self::new(
            if hints.contains(Hints::BOUNDED_BELOW) {
                Some(unsafe { min.assume_init() })
            } else {
                None
            },
            if hints.contains(Hints::BOUNDED_ABOVE) {
                Some(unsafe { max.assume_init() })
            } else {
                None
            },
        )
    }
}

impl<T> RangeBounds<T> for Range<T> {
    fn start_bound(&self) -> Bound<&T> {
        if let Some(value) = &self.min {
            Bound::Included(value)
        } else {
            Bound::Unbounded
        }
    }

    fn end_bound(&self) -> Bound<&T> {
        if let Some(value) = &self.max {
            Bound::Included(value)
        } else {
            Bound::Unbounded
        }
    }
}

impl<'a> Setting<'a, f64> {
    /**
    Set the value of a numeric setting

    Returns `true` if the value has been set, `false` otherwise
     */
    pub fn set(&self, value: f64) -> bool {
        0 < unsafe { ffi::fluid_settings_setnum(self.handle, self.name_ptr(), value) }
    }

    /**
    Get the value of a numeric setting

    Returns `Some(value)` if the value exists, `None` otherwise
     */
    pub fn get(&self) -> Option<f64> {
        let mut value = MaybeUninit::uninit();

        if 0 < unsafe {
            ffi::fluid_settings_getnum(self.handle, self.name_ptr(), value.as_mut_ptr())
        } {
            let value = unsafe { value.assume_init() };
            Some(value)
        } else {
            None
        }
    }

    /**
    Get the default value of a numeric setting
     */
    pub fn default(&self) -> f64 {
        unsafe { ffi::fluid_settings_getnum_default(self.handle, self.name_ptr()) }
    }

    /**
    Get the range of values of a numeric setting
     */
    pub fn range(&self) -> Range<f64> {
        let mut min = MaybeUninit::uninit();
        let mut max = MaybeUninit::uninit();

        unsafe {
            ffi::fluid_settings_getnum_range(
                self.handle,
                self.name_ptr(),
                min.as_mut_ptr(),
                max.as_mut_ptr(),
            );
        }

        let hints = self.hints();
        Range::new_unsafe(min, max, hints)
    }
}

impl<'a> Setting<'a, i32> {
    /**
    Set the value of a integer setting

    Returns `true` if the value has been set, `false` otherwise
     */
    pub fn set(&self, value: i32) -> bool {
        0 < unsafe { ffi::fluid_settings_setint(self.handle, self.name_ptr(), value) }
    }

    /**
    Get the value of a integer setting

    Returns `Some(value)` if the value exists, `None` otherwise
     */
    pub fn get(&self) -> Option<i32> {
        let mut value = MaybeUninit::uninit();

        if 0 < unsafe {
            ffi::fluid_settings_getint(self.handle, self.name_ptr(), value.as_mut_ptr())
        } {
            let value = unsafe { value.assume_init() };
            Some(value)
        } else {
            None
        }
    }

    /**
    Get the default value of a integer setting
     */
    pub fn default(&self) -> i32 {
        unsafe { ffi::fluid_settings_getint_default(self.handle, self.name_ptr()) }
    }

    /**
    Get the range of values of a integer setting
     */
    pub fn range(&self) -> Range<i32> {
        let mut min = MaybeUninit::uninit();
        let mut max = MaybeUninit::uninit();

        unsafe {
            ffi::fluid_settings_getint_range(
                self.handle,
                self.name_ptr(),
                min.as_mut_ptr(),
                max.as_mut_ptr(),
            );
        }

        let hints = self.hints();
        Range::new_unsafe(min, max, hints)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    macro_rules! assert_eqf {
        ($a:expr, $b:expr) => {{
            let eps = 1.0e-6;
            let (a, b) = (&$a, &$b);
            assert!(
                (*a - *b).abs() < eps,
                "assertion failed: `(left !== right)` \
                 (left: `{:?}`, right: `{:?}`, expect diff: `{:?}`, real diff: `{:?}`)",
                *a,
                *b,
                eps,
                (*a - *b).abs()
            );
        }};
    }

    #[test]
    fn settings() {
        let settings = Settings::new().unwrap();

        drop(settings);
    }

    #[test]
    fn num_setting() {
        let settings = Settings::new().unwrap();
        let gain = settings.num("synth.gain").unwrap();

        assert_eqf!(gain.default(), 0.2);
        //assert_eq!(gain.range().min, Some(0.0));
        //assert_eq!(gain.range().max, Some(10.0));

        assert_eqf!(gain.get().unwrap(), 0.2);
        assert!(gain.set(0.5));
        assert_eqf!(gain.get().unwrap(), 0.5);
    }

    #[test]
    fn int_setting() {
        let settings = Settings::new().unwrap();
        let polyphony = settings.int("synth.polyphony").unwrap();

        assert_eq!(polyphony.default(), 256);
        //assert_eq!(polyphony.range().min, Some(1));
        //assert_eq!(polyphony.range().max, Some(65535));

        assert_eq!(polyphony.get(), Some(256));
        assert!(polyphony.set(512));
        assert_eq!(polyphony.get(), Some(512));
    }

    #[test]
    fn str_setting() {
        let settings = Settings::new().unwrap();
        let active = settings.str_("synth.drums-channel.active").unwrap();

        assert_eq!(active.default(), "yes");

        assert_eq!(active.get(), Some("yes"));
        assert!(active.set("no"));
        assert_eq!(active.get(), Some("no"));
    }

    #[test]
    fn settings_ref() {
        let settings = Settings::new().unwrap();

        let settings_ref = SettingsRef::from_ptr(settings.into_ptr());

        let gain = settings_ref.num("synth.gain").unwrap();

        assert_eqf!(gain.default(), 0.2);
    }
}