djio 0.0.23

DJ Hardware Control(ler) Support
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
// SPDX-FileCopyrightText: The djio authors
// SPDX-License-Identifier: MPL-2.0

//! Receiving and processing sensor data from devices
//! .

use std::{
    borrow::Borrow,
    cmp::Ordering,
    ops::{Add, Mul, RangeInclusive, Sub},
};

use float_cmp::approx_eq;
use strum::FromRepr;

use crate::{Control, ControlValue, TimeStamp};

/// Time-stamped input event
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InputEvent<T> {
    pub ts: TimeStamp,
    pub input: T,
}

pub fn input_events_ordered_chronologically<I, T>(events: I) -> bool
where
    I: IntoIterator,
    I::Item: Borrow<InputEvent<T>>,
{
    events.into_iter().is_sorted_by_key(|item| item.borrow().ts)
}

/// A simple two-state button.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u8)]
pub enum ButtonInput {
    Released = 0,
    Pressed = 1,
}

impl From<ControlValue> for ButtonInput {
    fn from(from: ControlValue) -> Self {
        match from.to_bits() {
            0 => Self::Released,
            _ => Self::Pressed,
        }
    }
}

impl From<ButtonInput> for ControlValue {
    fn from(value: ButtonInput) -> Self {
        Self::from_bits(value as _)
    }
}

/// A pad button with pressure information.
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(transparent)]
pub struct PadButtonInput {
    /// Pressure in the interval [0, 1]
    pub pressure: f32,
}

impl PadButtonInput {
    pub const MIN_PRESSURE: f32 = 0.0;
    pub const MAX_PRESSURE: f32 = 1.0;
    pub const PRESSURE_RANGE: RangeInclusive<f32> = Self::MIN_PRESSURE..=Self::MAX_PRESSURE;

    #[must_use]
    pub fn as_button(self) -> ButtonInput {
        debug_assert!(Self::PRESSURE_RANGE.contains(&self.pressure));
        if self.pressure > Self::MIN_PRESSURE {
            ButtonInput::Pressed
        } else {
            ButtonInput::Released
        }
    }

    #[must_use]
    pub fn from_u7(input: u8) -> Self {
        debug_assert!(input <= 127);
        let pressure = f32::from(input) / 127.0;
        debug_assert!(Self::PRESSURE_RANGE.contains(&pressure));
        Self { pressure }
    }

    #[must_use]
    pub fn from_u14(input: u16) -> Self {
        debug_assert!(input <= 16383);
        let pressure = f32::from(input) / 16383.0;
        debug_assert!(Self::PRESSURE_RANGE.contains(&pressure));
        Self { pressure }
    }
}

impl From<ControlValue> for PadButtonInput {
    fn from(from: ControlValue) -> Self {
        let pressure = f32::from_bits(from.to_bits());
        debug_assert!(Self::PRESSURE_RANGE.contains(&pressure));
        Self { pressure }
    }
}

impl From<PadButtonInput> for ControlValue {
    fn from(from: PadButtonInput) -> Self {
        let PadButtonInput { pressure } = from;
        Self::from_bits(pressure.to_bits())
    }
}

/// A continuous fader or knob.
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(transparent)]
pub struct SliderInput {
    /// Position in the interval [0, 1]
    pub position: f32,
}

impl SliderInput {
    pub const MIN_POSITION: f32 = 0.0;
    pub const MAX_POSITION: f32 = 1.0;
    pub const POSITION_RANGE: RangeInclusive<f32> = Self::MIN_POSITION..=Self::MAX_POSITION;

    #[must_use]
    pub const fn clamp_position(position: f32) -> f32 {
        position.clamp(Self::MIN_POSITION, Self::MAX_POSITION)
    }

    #[must_use]
    pub fn from_u7(input: u8) -> Self {
        debug_assert!(input <= 127);
        let position = f32::from(input) / 127.0;
        debug_assert!(Self::POSITION_RANGE.contains(&position));
        Self { position }
    }

    #[must_use]
    pub fn from_u14(input: u16) -> Self {
        debug_assert!(input <= 16383);
        let position = f32::from(input) / 16383.0;
        debug_assert!(Self::POSITION_RANGE.contains(&position));
        Self { position }
    }

    #[must_use]
    pub fn inverse(self) -> Self {
        let Self { position } = self;
        Self {
            position: Self::MAX_POSITION - position,
        }
    }

    #[must_use]
    pub fn map_position_linear<T>(self, min_value: T, max_value: T) -> T
    where
        T: From<f32> + Sub<Output = T> + Mul<Output = T> + Add<Output = T> + Copy,
    {
        let Self { position } = self;
        min_value + T::from(position) * (max_value - min_value)
    }

    /// Interpret the position as a ratio for adjusting the volume of a signal.
    ///
    /// The position is interpreted as a volume level between the silence level
    /// (< 0 dB) and 0 dB.
    ///
    /// Multiply the signal with the returned value to adjust the volume.
    #[must_use]
    #[inline]
    pub fn map_position_to_gain_ratio(self, silence_db: f32) -> f32 {
        debug_assert!(silence_db < 0.0);
        let Self { position } = self;
        let gain_ratio = db_to_ratio((1.0 - position) * silence_db);
        // Still in range after transformation
        debug_assert!(Self::POSITION_RANGE.contains(&gain_ratio));
        gain_ratio
    }
}

impl From<ControlValue> for SliderInput {
    fn from(from: ControlValue) -> Self {
        let position = f32::from_bits(from.to_bits());
        debug_assert!(Self::POSITION_RANGE.contains(&position));
        Self { position }
    }
}

impl From<SliderInput> for ControlValue {
    fn from(from: SliderInput) -> Self {
        let SliderInput { position } = from;
        Self::from_bits(position.to_bits())
    }
}

/// A continuous fader or knob with a symmetric center position.
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(transparent)]
pub struct CenterSliderInput {
    /// Position in the interval [-1, 1]
    pub position: f32,
}

impl CenterSliderInput {
    pub const MIN_POSITION: f32 = -1.0;
    pub const MAX_POSITION: f32 = 1.0;
    pub const POSITION_RANGE: RangeInclusive<f32> = Self::MIN_POSITION..=Self::MAX_POSITION;
    pub const CENTER_POSITION: f32 = 0.0;

    #[must_use]
    pub const fn clamp_position(position: f32) -> f32 {
        position.clamp(Self::MIN_POSITION, Self::MAX_POSITION)
    }

    #[must_use]
    #[expect(clippy::cast_possible_wrap)]
    pub fn from_u7(input: u8) -> Self {
        debug_assert!(input < 128);
        let position = if input < 64 {
            f32::from(input as i8 - 64) / 64.0
        } else {
            f32::from(input - 64) / 63.0
        };
        debug_assert!(Self::POSITION_RANGE.contains(&position));
        Self { position }
    }

    #[must_use]
    #[expect(clippy::cast_possible_wrap)]
    pub fn from_u14(input: u16) -> Self {
        debug_assert!(input < 16384);
        let position = if input < 8192 {
            f32::from(input as i16 - 8192) / 8192.0
        } else {
            f32::from(input - 8192) / 8191.0
        };
        debug_assert!(Self::POSITION_RANGE.contains(&position));
        Self { position }
    }

    #[must_use]
    pub fn inverse(self) -> Self {
        let Self { position } = self;
        if self.position == Self::CENTER_POSITION {
            // Prevent the value -0.0
            Self { position }
        } else {
            Self {
                position: -position,
            }
        }
    }

    #[must_use]
    #[inline]
    pub fn map_position_linear<T>(self, min_value: T, center_value: T, max_value: T) -> T
    where
        T: From<f32> + Sub<Output = T> + Mul<Output = T> + Add<Output = T> + Copy + PartialOrd,
    {
        debug_assert!(
            (min_value <= center_value && center_value <= max_value)
                || (min_value >= center_value && center_value >= max_value)
        );
        let Self { position } = self;
        match position
            .partial_cmp(&Self::CENTER_POSITION)
            .unwrap_or(Ordering::Equal)
        {
            Ordering::Equal => center_value,
            Ordering::Less => T::from(position) * (center_value - min_value) + center_value,
            Ordering::Greater => T::from(position) * (max_value - center_value) + center_value,
        }
    }

    /// Interpret the position as a ratio for tuning the volume of a signal.
    ///
    /// The position is interpreted as a volume level between the `min_db`
    /// (< 0 dB) and `max_db` (> 0 dB), e.g. -26 dB and +6 dB (Pioneer DJM).
    ///
    /// Multiply the signal with the returned value to tune the volume.
    #[must_use]
    #[inline]
    pub fn map_position_to_gain_ratio(self, min_db: f32, max_db: f32) -> f32 {
        debug_assert!(min_db < 0.0);
        debug_assert!(max_db > 0.0);
        debug_assert!(min_db < max_db);
        let Self { position } = self;
        match position
            .partial_cmp(&Self::CENTER_POSITION)
            .unwrap_or(Ordering::Equal)
        {
            Ordering::Equal => 1.0,
            Ordering::Less => db_to_ratio(-position * min_db),
            Ordering::Greater => db_to_ratio(position * max_db),
        }
    }
}

impl From<ControlValue> for CenterSliderInput {
    fn from(from: ControlValue) -> Self {
        let position = f32::from_bits(from.to_bits());
        debug_assert!(Self::POSITION_RANGE.contains(&position));
        Self { position }
    }
}

impl From<CenterSliderInput> for ControlValue {
    fn from(from: CenterSliderInput) -> Self {
        let CenterSliderInput { position } = from;
        Self::from_bits(position.to_bits())
    }
}

/// An endless encoder that sends discrete delta values
///
/// Usually implemented by a hardware knob/pot that sends either
/// positive or negative delta values while rotated in clockwise (CW)
/// or counter-clockwise (CCS) direction respectively.
///
/// The number of ticks per revolution or twist is device-dependent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct StepEncoderInput {
    pub delta: i32,
}

impl StepEncoderInput {
    #[must_use]
    pub fn from_u7(input: u8) -> Self {
        debug_assert!(input < 0x80);
        let delta = if input < 0x40 {
            i32::from(input)
        } else {
            i32::from(input) - 0x80
        };
        Self { delta }
    }

    #[must_use]
    pub fn from_u14(input: u16) -> Self {
        debug_assert!(input < 0x4000);
        let delta = if input < 0x2000 {
            i32::from(input)
        } else {
            i32::from(input) - 0x4000
        };
        Self { delta }
    }
}

impl From<ControlValue> for StepEncoderInput {
    fn from(from: ControlValue) -> Self {
        #[expect(clippy::cast_possible_wrap)]
        let delta = from.to_bits() as i32;
        Self { delta }
    }
}

impl From<StepEncoderInput> for ControlValue {
    fn from(from: StepEncoderInput) -> Self {
        let StepEncoderInput { delta } = from;
        #[expect(clippy::cast_sign_loss)]
        Self::from_bits(delta as u32)
    }
}

/// An endless encoder that sends continuous delta values
///
/// Usually implemented by a hardware knob/pot that sends either
/// positive or negative delta values while rotated in clockwise (CW)
/// or counter-clockwise (CCS) direction respectively.
///
/// The scaling is device-dependent, but the following values are
/// recommended both for reference and for maximum portability:
///
///  1.0: One full CW rotation (360 degrees)
/// -1.0: One full CCW rotation (360 degrees)
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(transparent)]
pub struct SliderEncoderInput {
    pub delta: f32,
}

impl SliderEncoderInput {
    #[must_use]
    pub fn inverse(self) -> Self {
        let Self { delta } = self;
        if self.delta == 0.0 {
            // Prevent the value -0.0
            Self { delta }
        } else {
            Self { delta: -delta }
        }
    }
}

impl SliderEncoderInput {
    pub const DELTA_PER_CW_REV: f32 = 1.0;
    pub const DELTA_PER_CCW_REV: f32 = -1.0;

    #[must_use]
    #[expect(clippy::cast_possible_wrap)]
    pub fn from_u7(input: u8) -> Self {
        debug_assert!(input < 128);
        let delta = if input < 64 {
            f32::from(input) / 63.0
        } else {
            f32::from(input.wrapping_sub(128) as i8) / 64.0
        };
        Self { delta }
    }

    #[must_use]
    #[expect(clippy::cast_possible_wrap)]
    pub fn from_u14(input: u16) -> Self {
        debug_assert!(input < 16384);
        let delta = if input < 8192 {
            f32::from(input) / 8191.0
        } else {
            f32::from(input.wrapping_sub(16384) as i16) / 8192.0
        };
        Self { delta }
    }
}

impl From<ControlValue> for SliderEncoderInput {
    fn from(from: ControlValue) -> Self {
        let delta = f32::from_bits(from.to_bits());
        Self { delta }
    }
}

impl From<SliderEncoderInput> for ControlValue {
    fn from(from: SliderEncoderInput) -> Self {
        let SliderEncoderInput { delta } = from;
        Self::from_bits(delta.to_bits())
    }
}

/// Choose one out of many, discrete possible choices
///
/// Useful for configuration settings, e.g. selecting a mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelectorInput {
    pub choice: u32,
}

impl From<ControlValue> for SelectorInput {
    fn from(from: ControlValue) -> Self {
        let choice = from.to_bits();
        Self { choice }
    }
}

impl From<SelectorInput> for ControlValue {
    fn from(from: SelectorInput) -> Self {
        let SelectorInput { choice } = from;
        Self::from_bits(choice)
    }
}

pub type ControlInputEvent = InputEvent<Control>;

pub trait ControlInputEventSink {
    /// Callback for sinking control input events
    ///
    /// The caller will provide one or more events per invocation.
    /// Multiple events are ordered chronologically according to
    /// their time stamps.
    fn sink_control_input_events(&mut self, events: &[ControlInputEvent]);
}

#[must_use]
pub fn split_crossfader_input_linear(input: CenterSliderInput) -> (SliderInput, SliderInput) {
    const fn f_x(x: f32) -> f32 {
        x
    }
    let CenterSliderInput { position } = input;
    let x = position * 0.5 + 0.5; // [0, 1]
    let left_position = f_x(1.0 - x);
    let right_position = f_x(x);
    debug_assert!(SliderInput::POSITION_RANGE.contains(&left_position));
    debug_assert!(SliderInput::POSITION_RANGE.contains(&right_position));
    (
        SliderInput {
            position: left_position,
        },
        SliderInput {
            position: right_position,
        },
    )
}

#[must_use]
pub fn split_crossfader_input_amplitude_preserving_approx(
    input: CenterSliderInput,
) -> (SliderInput, SliderInput) {
    // <https://signalsmith-audio.co.uk/writing/2021/cheap-energy-crossfade/>
    #[expect(clippy::cast_possible_truncation)]
    fn f_x(x: f64) -> f32 {
        (x.powi(2) * (3.0 - 2.0 * x)) as _
    }
    let CenterSliderInput { position } = input;
    let x: f64 = f64::from(position) * 0.5 + 0.5; // [0, 1]
    let left_position = f_x(1.0 - x);
    let right_position = f_x(x);
    (
        SliderInput {
            position: SliderInput::clamp_position(left_position),
        },
        SliderInput {
            position: SliderInput::clamp_position(right_position),
        },
    )
}

#[must_use]
pub fn split_crossfader_input_energy_preserving_approx(
    input: CenterSliderInput,
) -> (SliderInput, SliderInput) {
    // <https://signalsmith-audio.co.uk/writing/2021/cheap-energy-crossfade/>
    #[expect(clippy::cast_possible_truncation)]
    fn f_x(x: f64) -> f32 {
        let y = x * (1.0 - x);
        (y * (1.0 + 1.4186 * y) + x).powi(2) as _
    }
    let CenterSliderInput { position } = input;
    let x = f64::from(position) * 0.5 + 0.5; // [0, 1]
    let left_position = f_x(1.0 - x);
    let right_position = f_x(x);
    (
        SliderInput {
            position: SliderInput::clamp_position(left_position),
        },
        SliderInput {
            position: SliderInput::clamp_position(right_position),
        },
    )
}

#[must_use]
pub fn split_crossfader_input_square(input: CenterSliderInput) -> (SliderInput, SliderInput) {
    let CenterSliderInput { position } = input;
    let left_position = if approx_eq!(f32, position, CenterSliderInput::MAX_POSITION) {
        SliderInput::MIN_POSITION
    } else {
        SliderInput::MAX_POSITION
    };
    let right_position = if approx_eq!(f32, position, CenterSliderInput::MIN_POSITION) {
        SliderInput::MIN_POSITION
    } else {
        SliderInput::MAX_POSITION
    };
    (
        SliderInput {
            position: left_position,
        },
        SliderInput {
            position: right_position,
        },
    )
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CrossfaderCurve {
    Linear,
    AmplitudePreserving,
    EnergyPreserving,
    Square,
}

impl CrossfaderCurve {
    #[must_use]
    pub fn split_input(self, input: CenterSliderInput) -> (SliderInput, SliderInput) {
        match self {
            Self::Linear => split_crossfader_input_linear(input),
            Self::AmplitudePreserving => split_crossfader_input_amplitude_preserving_approx(input),
            Self::EnergyPreserving => split_crossfader_input_energy_preserving_approx(input),
            Self::Square => split_crossfader_input_square(input),
        }
    }
}

#[inline]
fn db_to_ratio(gain: f32) -> f32 {
    10.0f32.powf(gain / 20.0)
}

#[cfg(test)]
mod tests;