use std::sync::Mutex;
use std::time::{Duration, Instant};
use prolink_proto::beat::{Beat, BeatInBar, Pitch, Timings};
use prolink_proto::{DeviceName, DeviceNumber};
pub const STALE_AFTER: Duration = Duration::from_millis(1500);
#[allow(
clippy::as_conversions,
clippy::cast_possible_truncation,
clippy::cast_sign_loss
)]
pub fn rounded(value: f64, max: u64) -> u64 {
if !value.is_finite() {
return 0;
}
#[allow(clippy::cast_precision_loss)]
let ceiling = max as f64;
value.round().clamp(0.0, ceiling) as u64
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BeatPosition {
pub number: u32,
pub fraction: f64,
}
impl BeatPosition {
fn as_beats(self) -> f64 {
f64::from(self.number) + self.fraction.clamp(0.0, 1.0)
}
fn from_beats(beats: f64) -> Self {
let whole = beats.floor();
let number = u32::try_from(rounded(whole, u64::from(u32::MAX)))
.unwrap_or(u32::MAX)
.max(1);
Self {
number,
fraction: (beats - whole).clamp(0.0, 1.0),
}
}
pub fn in_bar(self) -> BeatInBar {
let index = (self.number.saturating_sub(1)) % u32::from(BeatInBar::PER_BAR);
BeatInBar::new(u8::try_from(index + 1).unwrap_or(1)).unwrap_or(BeatInBar::DOWNBEAT)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Playback {
pub bpm_centi: Option<u16>,
pub pitch: Pitch,
pub playing: bool,
pub beat: Option<BeatPosition>,
pub scratching: bool,
}
impl Default for Playback {
fn default() -> Self {
Self {
bpm_centi: None,
pitch: Pitch::UNITY,
playing: false,
beat: None,
scratching: false,
}
}
}
impl Playback {
pub fn bpm(&self) -> Option<f64> {
self.bpm_centi
.filter(|¢i| centi > 0)
.map(|centi| f64::from(centi) / 100.0)
}
pub fn effective_bpm(&self) -> Option<f64> {
Some(self.bpm()? * self.pitch.multiplier())
}
pub fn beat_interval(&self) -> Option<Duration> {
let bpm = self.effective_bpm()?;
if bpm <= 0.0 {
return None;
}
Duration::try_from_secs_f64(60.0 / bpm).ok()
}
fn quoted_beat_interval(&self) -> Option<Duration> {
let bpm = self.bpm()?;
if bpm <= 0.0 {
return None;
}
Duration::try_from_secs_f64(60.0 / bpm).ok()
}
#[must_use]
pub fn projected(&self, age: Duration) -> Self {
let advanced = if let (Some(beat), Some(interval), true) =
(self.beat, self.beat_interval(), self.playing)
{
let beats = age.as_secs_f64() / interval.as_secs_f64();
Some(BeatPosition::from_beats(beat.as_beats() + beats))
} else {
self.beat
};
Self {
beat: advanced,
..*self
}
}
pub fn beat_packet(
&self,
device: DeviceNumber,
name: DeviceName,
position: BeatPosition,
) -> Option<Beat> {
let interval = self.quoted_beat_interval()?.as_secs_f64() * 1000.0;
let beats_out = |n: u32| {
Some(Duration::from_millis(rounded(
interval * f64::from(n),
u64::MAX,
)))
};
let to_next_bar = u32::from(position.in_bar().beats_to_next_bar());
Some(Beat {
name,
device,
timings: Timings {
next_beat: beats_out(1),
second_beat: beats_out(2),
next_bar: beats_out(to_next_bar),
fourth_beat: beats_out(4),
second_bar: beats_out(to_next_bar + u32::from(BeatInBar::PER_BAR)),
eighth_beat: beats_out(8),
},
pitch: self.pitch,
bpm_centi: self.bpm_centi.unwrap_or(0),
beat_in_bar: Some(position.in_bar()),
scratching: false,
})
}
}
#[derive(Debug, Default)]
pub struct PlaybackCell {
latest: Mutex<Option<(Playback, Instant)>>,
}
impl PlaybackCell {
pub fn set(&self, playback: Playback) {
let stamped = Some((playback, Instant::now()));
match self.latest.lock() {
Ok(mut latest) => *latest = stamped,
Err(poisoned) => *poisoned.into_inner() = stamped,
}
}
pub fn clear(&self) {
match self.latest.lock() {
Ok(mut latest) => *latest = None,
Err(poisoned) => *poisoned.into_inner() = None,
}
}
pub fn now(&self) -> Playback {
let sample = match self.latest.lock() {
Ok(latest) => *latest,
Err(poisoned) => *poisoned.into_inner(),
};
match sample {
Some((playback, at)) => {
let age = at.elapsed();
if age > STALE_AFTER {
Playback::default()
} else {
playback.projected(age)
}
}
None => Playback::default(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn at(number: u32, fraction: f64) -> BeatPosition {
BeatPosition { number, fraction }
}
fn playing_at(bpm_centi: u16, position: BeatPosition) -> Playback {
Playback {
bpm_centi: Some(bpm_centi),
pitch: Pitch::UNITY,
playing: true,
beat: Some(position),
scratching: false,
}
}
#[test]
fn beat_one_is_a_downbeat_and_the_bar_repeats_every_four() {
let bars: Vec<u8> = (1..=9).map(|n| at(n, 0.0).in_bar().get()).collect();
assert_eq!(bars, vec![1, 2, 3, 4, 1, 2, 3, 4, 1]);
}
#[test]
fn the_playhead_advances_by_the_clock_not_by_the_poll() {
let playback = playing_at(12_000, at(4, 0.0));
let later = playback.projected(Duration::from_millis(500));
assert_eq!(later.beat.expect("a beat").number, 5);
let much_later = playback.projected(Duration::from_millis(1750));
let beat = much_later.beat.expect("a beat");
assert_eq!(beat.number, 7);
assert!(
(beat.fraction - 0.5).abs() < 1e-9,
"1.75 s at 120 BPM is three and a half beats, not {beat:?}"
);
}
#[test]
fn a_paused_deck_stays_where_it_is() {
let paused = Playback {
playing: false,
..playing_at(12_000, at(4, 0.25))
};
assert_eq!(
paused.projected(Duration::from_secs(10)).beat,
Some(at(4, 0.25)),
"a deck that is not playing does not travel"
);
}
#[test]
fn the_pitch_fader_moves_the_playhead_but_not_the_quoted_grid() {
let fast = Playback {
pitch: Pitch(0x0020_0000), ..playing_at(12_000, at(1, 0.0))
};
assert_eq!(
fast.beat_interval(),
Some(Duration::from_millis(250)),
"240 effective BPM is a beat every quarter second"
);
assert_eq!(
fast.quoted_beat_interval(),
Some(Duration::from_millis(500)),
"but the packet quotes the track's own 120 BPM"
);
let packet = fast
.beat_packet(DeviceNumber::ONE, DeviceName::default(), at(1, 0.0))
.expect("a beat packet");
assert_eq!(packet.timings.next_beat, Some(Duration::from_millis(500)));
assert_eq!(packet.beat_interval(), Some(Duration::from_millis(250)));
}
#[test]
fn the_bar_line_is_however_many_beats_are_left_of_the_bar() {
let playback = playing_at(12_000, at(3, 0.0));
let packet = playback
.beat_packet(DeviceNumber::ONE, DeviceName::default(), at(3, 0.0))
.expect("a beat packet");
assert_eq!(packet.beat_in_bar, BeatInBar::new(3));
assert_eq!(packet.timings.next_bar, Some(Duration::from_secs(1)));
assert_eq!(packet.timings.second_bar, Some(Duration::from_secs(3)));
assert_eq!(packet.timings.next_beat, Some(Duration::from_millis(500)));
assert_eq!(packet.timings.eighth_beat, Some(Duration::from_secs(4)));
}
#[test]
fn a_beat_packet_we_emit_parses_back_as_a_beat_packet() {
let playback = playing_at(14_500, at(9, 0.0));
let packet = playback
.beat_packet(DeviceNumber::ONE, DeviceName::default(), at(9, 0.0))
.expect("a beat packet");
let raw = packet.encode();
let parsed = Beat::parse(&raw).expect("our own beat packet");
assert_eq!(parsed, packet);
assert_eq!(parsed.beat_in_bar, BeatInBar::new(1));
assert!((parsed.effective_bpm() - 145.0).abs() < 0.01);
}
#[test]
fn a_caller_that_stops_talking_stops_being_a_tempo() {
let cell = PlaybackCell::default();
assert_eq!(cell.now().bpm_centi, None, "nothing stated yet");
cell.set(playing_at(14_500, at(1, 0.0)));
assert_eq!(cell.now().bpm_centi, Some(14_500));
cell.clear();
assert_eq!(cell.now().bpm_centi, None);
assert!(!cell.now().playing);
}
#[test]
fn a_track_with_no_tempo_produces_no_beat_packet() {
let silent = Playback::default();
assert!(
silent
.beat_packet(DeviceNumber::ONE, DeviceName::default(), at(1, 0.0))
.is_none(),
"every field in a beat packet is a distance in beats"
);
assert_eq!(silent.beat_interval(), None);
}
}