use std::collections::BTreeMap;
use std::fmt;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use prolink_proto::beat::{self, Beat, BeatInBar, Pitch};
use prolink_proto::status::{self, CdjStatus, StatusFlags};
use prolink_proto::{BEAT_PORT, DeviceName, DeviceNumber, STATUS_PORT, Slot};
use tokio::net::UdpSocket;
use tokio::sync::broadcast;
use tokio::task::JoinHandle;
use tracing::{debug, trace, warn};
use crate::Result;
use crate::interface::Interface;
use crate::socket::{self, MAX_DATAGRAM};
use crate::virtual_cdj::VirtualCdj;
const EVENT_CAPACITY: usize = 1024;
pub const BEAT_STALE_AFTER: Duration = Duration::from_secs(3);
pub const FORGET_AFTER: Duration = Duration::from_secs(30);
const REAP_INTERVAL: Duration = Duration::from_millis(250);
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct PlayState(pub u8);
impl PlayState {
pub const NO_TRACK: Self = Self(0x00);
pub const LOADING: Self = Self(0x02);
pub const PLAYING: Self = Self(0x03);
pub const LOOPING: Self = Self(0x04);
pub const PAUSED: Self = Self(0x05);
pub const CUED: Self = Self(0x06);
pub const CUE_PLAY: Self = Self(0x07);
pub const CUE_SCRATCH: Self = Self(0x08);
pub const SEARCHING: Self = Self(0x09);
pub const SPUN_DOWN: Self = Self(0x0e);
pub const END_OF_TRACK: Self = Self(0x11);
pub const EMERGENCY_LOOP: Self = Self(0x12);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::NO_TRACK => "no track",
Self::LOADING => "loading",
Self::PLAYING => "playing",
Self::LOOPING => "looping",
Self::PAUSED => "paused",
Self::CUED => "cued",
Self::CUE_PLAY => "cue play",
Self::CUE_SCRATCH => "cue scratch",
Self::SEARCHING => "searching",
Self::SPUN_DOWN => "spun down",
Self::END_OF_TRACK => "end of track",
Self::EMERGENCY_LOOP => "emergency loop",
_ => return None,
})
}
pub fn is_playing(self) -> bool {
matches!(
self,
Self::PLAYING | Self::LOOPING | Self::CUE_PLAY | Self::EMERGENCY_LOOP
)
}
}
impl fmt::Debug for PlayState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "PlayState({:#04x})", self.0),
}
}
}
impl fmt::Display for PlayState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "{:#04x}", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct TrackKind(pub u8);
impl TrackKind {
pub const NONE: Self = Self(0x00);
pub const REKORDBOX: Self = Self(0x01);
pub const UNANALYSED: Self = Self(0x02);
pub const AUDIO_CD: Self = Self(0x05);
pub const STREAMING: Self = Self(0x06);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::NONE => "none",
Self::REKORDBOX => "rekordbox",
Self::UNANALYSED => "unanalysed",
Self::AUDIO_CD => "audio cd",
Self::STREAMING => "streaming",
_ => return None,
})
}
}
impl fmt::Debug for TrackKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "TrackKind({:#04x})", self.0),
}
}
}
impl fmt::Display for TrackKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LoadedTrack {
pub source_player: DeviceNumber,
pub slot: Slot,
pub id: u32,
pub kind: TrackKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlayerStatus {
pub play_state: PlayState,
pub track: Option<LoadedTrack>,
pub bpm_centi: Option<u16>,
pub pitch: Option<Pitch>,
pub is_tempo_master: bool,
pub is_synced: bool,
pub is_playing: bool,
pub yielding_to: Option<DeviceNumber>,
pub beat: Option<u32>,
pub beat_in_bar: Option<BeatInBar>,
}
impl PlayerStatus {
pub fn bar_position(&self) -> Option<f64> {
let per_bar = BeatInBar::PER_BAR;
let index = if let Some(in_bar) = self.beat_in_bar {
in_bar.index()
} else {
let beat = self.beat?;
let per_bar = u32::from(per_bar);
u8::try_from((beat % per_bar + per_bar - 1) % per_bar).ok()?
};
Some(f64::from(index) / f64::from(per_bar))
}
fn without_position(self) -> Self {
Self {
beat: None,
beat_in_bar: None,
..self
}
}
pub fn effective_bpm(&self) -> Option<f64> {
let bpm = f64::from(self.bpm_centi?) / 100.0;
Some(bpm * self.pitch?.multiplier())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BeatObservation {
pub beat: Beat,
pub age: Duration,
}
impl BeatObservation {
pub fn is_stale(self) -> bool {
self.age > BEAT_STALE_AFTER
}
pub fn effective_bpm(self) -> f64 {
self.beat.effective_bpm()
}
pub fn beat_phase(self) -> Option<f64> {
if self.is_stale() {
return None;
}
let interval = self.beat.beat_interval()?.as_secs_f64();
if interval <= 0.0 {
return None;
}
Some((self.age.as_secs_f64() / interval).clamp(0.0, 1.0))
}
pub fn bar_phase(self) -> Option<f64> {
let position = self.beat.beat_in_bar?;
let within = self.beat_phase()?;
Some((f64::from(position.index()) + within) / f64::from(BeatInBar::PER_BAR))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StatusObservation {
pub status: PlayerStatus,
pub age: Duration,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlayerState {
pub device: DeviceNumber,
pub name: DeviceName,
pub beat: Option<BeatObservation>,
pub status: Option<StatusObservation>,
}
impl PlayerState {
pub fn effective_bpm(&self) -> Option<f64> {
self.beat.map(BeatObservation::effective_bpm)
}
pub fn beat_phase(&self) -> Option<f64> {
self.beat.and_then(BeatObservation::beat_phase)
}
pub fn bar_phase(&self) -> Option<f64> {
self.beat.and_then(BeatObservation::bar_phase)
}
pub fn bar_position(&self) -> Option<f64> {
self.status
.and_then(|observed| observed.status.bar_position())
}
pub fn beat_in_bar(&self) -> Option<BeatInBar> {
self.beat.and_then(|observed| observed.beat.beat_in_bar)
}
pub fn is_tempo_master(&self) -> Option<bool> {
self.status.map(|observed| observed.status.is_tempo_master)
}
pub fn is_synced(&self) -> Option<bool> {
self.status.map(|observed| observed.status.is_synced)
}
pub fn yielding_to(&self) -> Option<DeviceNumber> {
self.status.and_then(|observed| observed.status.yielding_to)
}
pub fn play_state(&self) -> Option<PlayState> {
self.status.map(|observed| observed.status.play_state)
}
pub fn track(&self) -> Option<LoadedTrack> {
self.status.and_then(|observed| observed.status.track)
}
pub fn is_beating(&self) -> bool {
self.beat.is_some_and(|observed| !observed.is_stale())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MonitorEvent {
Beat(Box<PlayerState>),
Status(Box<PlayerState>),
TempoMaster(Option<DeviceNumber>),
MasterRequested(DeviceNumber),
Stopped(DeviceNumber),
Gone(DeviceNumber),
}
impl MonitorEvent {
pub fn device(&self) -> Option<DeviceNumber> {
match self {
Self::Beat(state) | Self::Status(state) => Some(state.device),
Self::Stopped(device) | Self::Gone(device) | Self::MasterRequested(device) => {
Some(*device)
}
Self::TempoMaster(device) => *device,
}
}
}
#[derive(Clone, Debug)]
struct Entry {
name: DeviceName,
beat: Option<(Beat, Instant)>,
status: Option<(PlayerStatus, Instant)>,
beating: bool,
}
impl Entry {
fn last_heard(&self) -> Option<Instant> {
match (self.beat, self.status) {
(Some((_, beat)), Some((_, status))) => Some(beat.max(status)),
(Some((_, at)), None) | (None, Some((_, at))) => Some(at),
(None, None) => None,
}
}
}
#[derive(Debug, Default)]
struct PlayerTable {
players: BTreeMap<DeviceNumber, Entry>,
master: Option<DeviceNumber>,
}
impl PlayerTable {
fn entry(&mut self, device: DeviceNumber, name: DeviceName) -> &mut Entry {
let entry = self.players.entry(device).or_insert_with(|| Entry {
name,
beat: None,
status: None,
beating: false,
});
entry.name = name;
entry
}
fn observe_beat(&mut self, beat: &Beat, now: Instant) -> MonitorEvent {
let entry = self.entry(beat.device, beat.name);
entry.beat = Some((*beat, now));
entry.beating = true;
MonitorEvent::Beat(Box::new(self.state(beat.device, now).unwrap_or(
PlayerState {
device: beat.device,
name: beat.name,
beat: None,
status: None,
},
)))
}
fn observe_status(&mut self, packet: &CdjStatus, now: Instant) -> Vec<MonitorEvent> {
let Some(device) = packet.sender() else {
return Vec::new();
};
let flags = packet.flags();
let status = PlayerStatus {
play_state: PlayState(packet.play_state().unwrap_or(0)),
track: loaded_track(packet),
bpm_centi: packet.bpm_centi(),
pitch: packet.pitch(),
is_tempo_master: packet.is_tempo_master().unwrap_or(false),
is_synced: flags.is_some_and(StatusFlags::is_synced),
is_playing: flags.is_some_and(StatusFlags::is_playing),
yielding_to: packet.yielding_to(),
beat: packet.beat_number(),
beat_in_bar: packet.beat_in_bar(),
};
let entry = self.entry(device, packet.name());
let changed = entry
.status
.map(|(previous, _)| previous.without_position())
!= Some(status.without_position());
entry.status = Some((status, now));
let mut events = Vec::new();
if changed && let Some(state) = self.state(device, now) {
events.push(MonitorEvent::Status(Box::new(state)));
}
if let Some(event) = self.settle_master(device, status.is_tempo_master, status.yielding_to)
{
events.push(event);
}
events
}
fn settle_master(
&mut self,
device: DeviceNumber,
claims: bool,
yielding_to: Option<DeviceNumber>,
) -> Option<MonitorEvent> {
let was = self.master;
match yielding_to {
Some(successor) if self.players.contains_key(&successor) => {
self.master = Some(successor);
}
_ if claims => self.master = Some(device),
_ if was == Some(device) => self.master = None,
_ => {}
}
(self.master != was).then_some(MonitorEvent::TempoMaster(self.master))
}
fn state(&self, device: DeviceNumber, now: Instant) -> Option<PlayerState> {
let entry = self.players.get(&device)?;
Some(PlayerState {
device,
name: entry.name,
beat: entry.beat.map(|(beat, at)| BeatObservation {
beat,
age: now.saturating_duration_since(at),
}),
status: entry.status.map(|(status, at)| StatusObservation {
status,
age: now.saturating_duration_since(at),
}),
})
}
fn snapshot(&self, now: Instant) -> Vec<PlayerState> {
self.players
.keys()
.filter_map(|device| self.state(*device, now))
.collect()
}
fn reap(&mut self, now: Instant) -> Vec<MonitorEvent> {
let mut events = Vec::new();
let mut gone = Vec::new();
for (device, entry) in &mut self.players {
if entry.beating
&& entry
.beat
.is_none_or(|(_, at)| now.saturating_duration_since(at) > BEAT_STALE_AFTER)
{
entry.beating = false;
events.push(MonitorEvent::Stopped(*device));
}
if entry
.last_heard()
.is_none_or(|at| now.saturating_duration_since(at) > FORGET_AFTER)
{
gone.push(*device);
}
}
for device in gone {
self.players.remove(&device);
if self.master == Some(device) {
self.master = None;
events.push(MonitorEvent::TempoMaster(None));
}
events.push(MonitorEvent::Gone(device));
}
events
}
}
fn loaded_track(packet: &CdjStatus) -> Option<LoadedTrack> {
let source_player = packet.source_player()?;
let id = packet.track_id();
let kind = TrackKind(packet.track_type());
if id == 0 && kind == TrackKind::NONE {
return None;
}
Some(LoadedTrack {
source_player,
slot: packet.source_slot(),
id,
kind,
})
}
#[derive(Debug)]
pub struct Monitor {
interface: Interface,
players: Arc<Mutex<PlayerTable>>,
events: broadcast::Sender<MonitorEvent>,
watches_status: bool,
tasks: Vec<JoinHandle<()>>,
}
impl Monitor {
pub async fn start(interface: Interface) -> Result<Self> {
Self::build(interface, None).await
}
pub async fn with_status(interface: Interface, announcing: &VirtualCdj) -> Result<Self> {
match announcing.status_datagrams() {
Some(tap) => Self::build_shared(interface, announcing.number(), tap).await,
None => Self::build(interface, Some(announcing.number())).await,
}
}
#[expect(
clippy::unused_async,
reason = "spawns tasks, so it needs a tokio runtime; matches build's signature"
)]
async fn build_shared(
interface: Interface,
ours: DeviceNumber,
tap: broadcast::Receiver<Arc<Vec<u8>>>,
) -> Result<Self> {
let mut monitor = Self::empty(interface, true);
let beats = socket::bind(BEAT_PORT, Some(&monitor.interface))?;
monitor.tasks.push(monitor.spawn_beats(beats));
monitor.tasks.push(monitor.spawn_tapped_status(tap, ours));
monitor.tasks.push(monitor.spawn_reaper());
Ok(monitor)
}
#[expect(
clippy::unused_async,
reason = "spawns tasks, so it needs a tokio runtime; async is how that is documented \
at the call site, and keeps the signature stable if setup later awaits"
)]
async fn build(interface: Interface, ours: Option<DeviceNumber>) -> Result<Self> {
let mut monitor = Self::empty(interface, ours.is_some());
let beats = socket::bind(BEAT_PORT, Some(&monitor.interface))?;
monitor.tasks.push(monitor.spawn_beats(beats));
if let Some(ours) = ours {
let status = socket::bind(STATUS_PORT, Some(&monitor.interface))?;
monitor.tasks.push(monitor.spawn_status(status, ours));
}
monitor.tasks.push(monitor.spawn_reaper());
Ok(monitor)
}
fn empty(interface: Interface, watches_status: bool) -> Self {
let (events, _) = broadcast::channel(EVENT_CAPACITY);
Self {
interface,
players: Arc::new(Mutex::new(PlayerTable::default())),
events,
watches_status,
tasks: Vec::new(),
}
}
pub fn interface(&self) -> &Interface {
&self.interface
}
pub fn watches_status(&self) -> bool {
self.watches_status
}
pub fn players(&self) -> Vec<PlayerState> {
let now = Instant::now();
self.with_table(|table| table.snapshot(now))
}
pub fn player(&self, device: DeviceNumber) -> Option<PlayerState> {
let now = Instant::now();
self.with_table(|table| table.state(device, now))
}
pub fn tempo_master(&self) -> Option<DeviceNumber> {
self.with_table(|table| table.master)
}
pub fn subscribe(&self) -> broadcast::Receiver<MonitorEvent> {
self.events.subscribe()
}
fn with_table<T>(&self, read: impl FnOnce(&PlayerTable) -> T) -> T {
match self.players.lock() {
Ok(table) => read(&table),
Err(poisoned) => read(&poisoned.into_inner()),
}
}
fn spawn_beats(&self, socket: UdpSocket) -> JoinHandle<()> {
let players = Arc::clone(&self.players);
let events = self.events.clone();
tokio::spawn(async move {
let mut buffer = vec![0u8; MAX_DATAGRAM];
loop {
let Some(datagram) = receive(&socket, &mut buffer, "beat").await else {
return;
};
let decoded = match beat::decode(&datagram) {
Ok(decoded) => decoded,
Err(error) => {
trace!(%error, bytes = datagram.len(), "undecodable datagram on 50001");
continue;
}
};
let beat = match decoded {
beat::Packet::Beat(beat) => beat,
beat::Packet::MasterRequest(request) => {
let _ = events.send(MonitorEvent::MasterRequested(request.device));
continue;
}
other => {
trace!(kind = ?other.kind(), "unmodelled datagram on 50001");
continue;
}
};
let now = Instant::now();
let event = with_table_mut(&players, |table| table.observe_beat(&beat, now));
let _ = events.send(event);
}
})
}
fn spawn_status(&self, socket: UdpSocket, ours: DeviceNumber) -> JoinHandle<()> {
let players = Arc::clone(&self.players);
let events = self.events.clone();
tokio::spawn(async move {
let mut buffer = vec![0u8; MAX_DATAGRAM];
loop {
let Some(datagram) = receive(&socket, &mut buffer, "status").await else {
return;
};
observe_status_datagram(&players, &events, &datagram, ours);
}
})
}
fn spawn_tapped_status(
&self,
mut tap: broadcast::Receiver<Arc<Vec<u8>>>,
ours: DeviceNumber,
) -> JoinHandle<()> {
let players = Arc::clone(&self.players);
let events = self.events.clone();
tokio::spawn(async move {
loop {
let datagram = match tap.recv().await {
Ok(datagram) => datagram,
Err(broadcast::error::RecvError::Lagged(missed)) => {
warn!(missed, "fell behind the status tap");
continue;
}
Err(broadcast::error::RecvError::Closed) => return,
};
observe_status_datagram(&players, &events, &datagram, ours);
}
})
}
fn spawn_reaper(&self) -> JoinHandle<()> {
let players = Arc::clone(&self.players);
let events = self.events.clone();
tokio::spawn(async move {
let mut ticker = tokio::time::interval(REAP_INTERVAL);
loop {
ticker.tick().await;
let now = Instant::now();
for event in with_table_mut(&players, |table| table.reap(now)) {
debug!(?event, "player went quiet");
let _ = events.send(event);
}
}
})
}
}
impl Drop for Monitor {
fn drop(&mut self) {
for task in &self.tasks {
task.abort();
}
}
}
fn observe_status_datagram(
players: &Arc<Mutex<PlayerTable>>,
events: &broadcast::Sender<MonitorEvent>,
datagram: &[u8],
ours: DeviceNumber,
) {
let Ok(status::Packet::CdjStatus(packet)) = status::decode(datagram) else {
return;
};
if packet.sender() == Some(ours) {
return;
}
let now = Instant::now();
for event in with_table_mut(players, |table| table.observe_status(&packet, now)) {
debug!(?event, "player status changed");
let _ = events.send(event);
}
}
async fn receive(socket: &UdpSocket, buffer: &mut [u8], port: &'static str) -> Option<Vec<u8>> {
loop {
let (len, from) = match socket.recv_from(buffer).await {
Ok(received) => received,
Err(error) => {
warn!(%error, port, "socket closed");
return None;
}
};
if !matches!(from, SocketAddr::V4(_)) {
continue;
}
if let Some(datagram) = buffer.get(..len) {
return Some(datagram.to_vec());
}
}
}
fn with_table_mut<T>(table: &Mutex<PlayerTable>, write: impl FnOnce(&mut PlayerTable) -> T) -> T {
match table.lock() {
Ok(mut table) => write(&mut table),
Err(poisoned) => write(&mut poisoned.into_inner()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use prolink_proto::beat::{Pitch, Timings};
fn device(number: u8) -> DeviceNumber {
DeviceNumber::new(number).expect("a non-zero device number")
}
fn beat_at(number: u8, position: u8) -> Beat {
Beat {
name: DeviceName::new("CDJ-2000nexus"),
device: device(number),
timings: Timings {
next_beat: Some(Duration::from_millis(414)),
second_beat: Some(Duration::from_millis(828)),
next_bar: Some(Duration::from_millis(414)),
fourth_beat: Some(Duration::from_millis(1655)),
second_bar: Some(Duration::from_millis(2069)),
eighth_beat: Some(Duration::from_millis(3310)),
},
pitch: Pitch::UNITY,
bpm_centi: 14500,
beat_in_bar: BeatInBar::new(position),
scratching: false,
}
}
fn status_from(number: u8, play: u8, master: bool, track_id: u32) -> CdjStatus {
let mut raw = CdjStatus::builder()
.device_number(device(number))
.name(DeviceName::new("CDJ-2000nexus"))
.play_state(play)
.build()
.into_bytes();
raw[0x28] = number; raw[0x29] = Slot::USB.0;
raw[0x2a] = TrackKind::REKORDBOX.0;
raw[0x2c..0x30].copy_from_slice(&track_id.to_be_bytes());
raw[0x92..0x94].copy_from_slice(&14500u16.to_be_bytes());
raw[0x9e] = u8::from(master);
CdjStatus::parse(&raw).expect("a status packet")
}
#[test]
fn a_tapped_datagram_lands_in_the_table_unless_it_is_our_own() {
let players = Arc::new(Mutex::new(PlayerTable::default()));
let (events, mut heard) = broadcast::channel(16);
let ours = device(4);
let foreign = status_from(2, PlayState::PLAYING.0, true, 0x1234).into_bytes();
observe_status_datagram(&players, &events, &foreign, ours);
let now = Instant::now();
let state = with_table_mut(&players, |table| table.state(device(2), now))
.expect("the deck is in the table");
assert!(
state
.status
.as_ref()
.is_some_and(|seen| seen.status.is_tempo_master),
"device 2 said it was the tempo master"
);
assert!(heard.try_recv().is_ok(), "and that was worth an event");
let echo = status_from(ours.get(), PlayState::PLAYING.0, false, 0).into_bytes();
observe_status_datagram(&players, &events, &echo, ours);
assert!(
with_table_mut(&players, |table| table.state(ours, now)).is_none(),
"our own echo must not become a player"
);
}
#[test]
fn a_beat_packet_anchors_the_phase_at_the_beat() {
let mut table = PlayerTable::default();
let now = Instant::now();
table.observe_beat(&beat_at(2, 1), now);
let state = table.state(device(2), now).expect("a player");
let phase = state.beat_phase().expect("a phase");
assert!(phase.abs() < 1e-9, "on the beat the phase is zero: {phase}");
assert!(state.bar_phase().expect("a bar phase").abs() < 1e-9);
assert_eq!(state.beat_in_bar().map(BeatInBar::get), Some(1));
}
#[test]
fn the_phase_advances_with_the_clock_and_clamps_rather_than_wrapping() {
let mut table = PlayerTable::default();
let start = Instant::now();
table.observe_beat(&beat_at(2, 1), start);
let half = table
.state(device(2), start + Duration::from_millis(207))
.and_then(|state| state.beat_phase())
.expect("a phase");
assert!((half - 0.5).abs() < 0.005, "half a beat in: {half}");
let late = table
.state(device(2), start + Duration::from_millis(1200))
.and_then(|state| state.beat_phase())
.expect("a phase");
assert!(
(late - 1.0).abs() < 1e-9,
"clamped, not wrapped, so a stopped deck cannot look alive: {late}"
);
}
#[test]
fn the_bar_phase_walks_the_four_beats() {
let mut table = PlayerTable::default();
let now = Instant::now();
for (position, expected) in [(1u8, 0.0), (2, 0.25), (3, 0.5), (4, 0.75)] {
table.observe_beat(&beat_at(2, position), now);
let phase = table
.state(device(2), now)
.and_then(|state| state.bar_phase())
.expect("a bar phase");
assert!(
(phase - expected).abs() < 1e-9,
"beat {position} of 4 is {expected} of the bar, got {phase}"
);
}
}
#[test]
fn a_player_silent_for_three_beats_has_a_stale_phase_not_an_old_one() {
let mut table = PlayerTable::default();
let start = Instant::now();
table.observe_beat(&beat_at(2, 1), start);
let state = table
.state(
device(2),
start + BEAT_STALE_AFTER + Duration::from_millis(1),
)
.expect("a player");
assert!(state.beat_phase().is_none(), "the phase is meaningless");
assert!(state.bar_phase().is_none());
assert!(!state.is_beating());
assert!(
state
.effective_bpm()
.is_some_and(|bpm| (bpm - 145.0).abs() < 0.01)
);
}
#[test]
fn a_player_with_no_rekordbox_track_has_no_bar_to_be_in() {
let mut beat = beat_at(2, 1);
beat.beat_in_bar = None;
let mut table = PlayerTable::default();
let now = Instant::now();
table.observe_beat(&beat, now);
let state = table.state(device(2), now).expect("a player");
assert!(state.beat_phase().is_some(), "the beat is still placed");
assert!(state.bar_phase().is_none(), "but the bar is not");
}
fn status_on_beat(number: u8, play: u8, beat: Option<u32>, in_bar: u8) -> CdjStatus {
let mut raw = status_from(number, play, false, 182).into_bytes();
raw[0xa0..0xa4].copy_from_slice(&beat.unwrap_or(0xffff_ffff).to_be_bytes());
raw[0xa6] = in_bar;
CdjStatus::parse(&raw).expect("a status packet")
}
#[test]
fn a_paused_deck_is_placed_on_its_beat_and_follows_the_playhead() {
let mut table = PlayerTable::default();
let start = Instant::now();
for (step, (beat, in_bar, expected)) in
[(225, 1, 0.0), (224, 4, 0.75), (223, 3, 0.5), (222, 2, 0.25)]
.into_iter()
.enumerate()
{
let now = start + Duration::from_millis(200 * u64::try_from(step).unwrap_or(0));
let packet = status_on_beat(2, PlayState::PAUSED.0, Some(beat), in_bar);
table.observe_status(&packet, now);
let state = table.state(device(2), now).expect("a player");
assert_eq!(state.bar_position(), Some(expected), "beat {beat}");
assert!(state.bar_phase().is_none(), "no beats, so no phase");
}
}
#[test]
fn while_searching_the_bar_is_counted_from_the_beat() {
let mut table = PlayerTable::default();
let now = Instant::now();
for (beat, expected) in [(245, Some(0.0)), (6, Some(0.25)), (0, Some(0.75))] {
let packet = status_on_beat(2, PlayState::SEARCHING.0, Some(beat), 0);
table.observe_status(&packet, now);
let state = table.state(device(2), now).expect("a player");
assert_eq!(state.bar_position(), expected, "beat {beat}");
}
let off_the_grid = status_on_beat(2, PlayState::PAUSED.0, None, 0);
table.observe_status(&off_the_grid, now);
let state = table.state(device(2), now).expect("a player");
assert_eq!(state.bar_position(), None);
}
#[test]
fn a_moving_playhead_is_not_a_status_change() {
let mut table = PlayerTable::default();
let now = Instant::now();
let first = status_on_beat(3, PlayState::PLAYING.0, Some(10), 2);
let next = status_on_beat(3, PlayState::PLAYING.0, Some(11), 3);
assert_eq!(table.observe_status(&first, now).len(), 1);
let later = now + Duration::from_millis(200);
assert!(table.observe_status(&next, later).is_empty());
let state = table.state(device(3), later).expect("a player");
assert_eq!(state.bar_position(), Some(0.5));
}
#[test]
fn the_effective_tempo_follows_the_pitch_fader() {
let mut beat = beat_at(2, 1);
beat.pitch = Pitch(0x000f_8312); let mut table = PlayerTable::default();
let now = Instant::now();
table.observe_beat(&beat, now);
let state = table.state(device(2), now).expect("a player");
let bpm = state.effective_bpm().expect("a tempo");
assert!(
(bpm - 140.577).abs() < 0.01,
"145.00 at −3.05% is 140.58, not 145.00: {bpm}"
);
let phase = table
.state(device(2), now + Duration::from_millis(213))
.and_then(|state| state.beat_phase())
.expect("a phase");
assert!(
(phase - 0.5).abs() < 0.01,
"half of a 426.8 ms beat: {phase}"
);
}
#[test]
fn without_status_the_master_is_unknown_rather_than_absent() {
let mut table = PlayerTable::default();
let now = Instant::now();
table.observe_beat(&beat_at(2, 1), now);
let state = table.state(device(2), now).expect("a player");
assert_eq!(state.is_tempo_master(), None);
assert_eq!(state.play_state(), None);
assert_eq!(state.track(), None);
assert_eq!(table.master, None);
}
#[test]
fn a_status_packet_names_the_track_and_the_master() {
let mut table = PlayerTable::default();
let now = Instant::now();
let events = table.observe_status(&status_from(3, PlayState::PLAYING.0, true, 182), now);
assert!(matches!(
events.as_slice(),
[MonitorEvent::Status(_), MonitorEvent::TempoMaster(Some(_))]
));
let state = table.state(device(3), now).expect("a player");
assert_eq!(state.is_tempo_master(), Some(true));
assert_eq!(state.play_state(), Some(PlayState::PLAYING));
assert!(state.play_state().is_some_and(PlayState::is_playing));
let track = state.track().expect("a loaded track");
assert_eq!(track.id, 182);
assert_eq!(track.slot, Slot::USB);
assert_eq!(track.kind, TrackKind::REKORDBOX);
assert_eq!(track.source_player, device(3));
assert_eq!(table.master, Some(device(3)));
}
#[test]
fn an_unchanged_status_is_not_an_event() {
let mut table = PlayerTable::default();
let now = Instant::now();
let packet = status_from(3, PlayState::PLAYING.0, false, 182);
assert_eq!(table.observe_status(&packet, now).len(), 1);
assert!(
table
.observe_status(&packet, now + Duration::from_millis(200))
.is_empty()
);
}
#[test]
fn nothing_loaded_is_no_track_rather_than_track_zero() {
let mut table = PlayerTable::default();
let now = Instant::now();
let mut raw = status_from(3, PlayState::NO_TRACK.0, false, 0).into_bytes();
raw[0x28] = 0; raw[0x29] = Slot::NONE.0;
raw[0x2a] = TrackKind::NONE.0;
let packet = CdjStatus::parse(&raw).expect("a status packet");
table.observe_status(&packet, now);
assert_eq!(table.state(device(3), now).and_then(|s| s.track()), None);
}
#[test]
fn the_master_moves_when_another_deck_claims_it() {
let mut table = PlayerTable::default();
let now = Instant::now();
table.observe_status(&status_from(1, PlayState::PLAYING.0, true, 10), now);
assert_eq!(table.master, Some(device(1)));
let events = table.observe_status(&status_from(2, PlayState::PLAYING.0, true, 20), now);
assert!(events.contains(&MonitorEvent::TempoMaster(Some(device(2)))));
assert_eq!(table.master, Some(device(2)));
let events = table.observe_status(&status_from(1, PlayState::PLAYING.0, false, 10), now);
assert!(
!events
.iter()
.any(|event| matches!(event, MonitorEvent::TempoMaster(_))),
"device 1 giving up a role it no longer holds changes nothing"
);
assert_eq!(table.master, Some(device(2)));
}
#[test]
fn the_master_is_lost_when_the_holder_gives_it_up() {
let mut table = PlayerTable::default();
let now = Instant::now();
table.observe_status(&status_from(1, PlayState::PLAYING.0, true, 10), now);
let events = table.observe_status(&status_from(1, PlayState::PAUSED.0, false, 10), now);
assert!(events.contains(&MonitorEvent::TempoMaster(None)));
assert_eq!(table.master, None);
}
#[test]
fn a_deck_that_stops_beating_is_reported_once() {
let mut table = PlayerTable::default();
let start = Instant::now();
table.observe_beat(&beat_at(2, 1), start);
assert!(
table.reap(start + Duration::from_millis(500)).is_empty(),
"still beating"
);
let stale = start + BEAT_STALE_AFTER + Duration::from_millis(1);
assert_eq!(table.reap(stale), vec![MonitorEvent::Stopped(device(2))]);
assert!(
table.reap(stale + Duration::from_millis(250)).is_empty(),
"and not again at every tick"
);
}
#[test]
fn a_device_that_says_nothing_at_all_is_forgotten_and_gives_up_the_master() {
let mut table = PlayerTable::default();
let start = Instant::now();
table.observe_status(&status_from(4, PlayState::PLAYING.0, true, 7), start);
assert_eq!(table.master, Some(device(4)));
let events = table.reap(start + FORGET_AFTER + Duration::from_secs(1));
assert!(events.contains(&MonitorEvent::Gone(device(4))));
assert!(events.contains(&MonitorEvent::TempoMaster(None)));
assert!(table.snapshot(start).is_empty());
assert_eq!(table.master, None);
}
fn yielding_status(number: u8, to: u8) -> CdjStatus {
let mut raw = status_from(number, PlayState::PLAYING.0, true, 182).into_bytes();
raw[0x9f] = to;
CdjStatus::parse(&raw).expect("a status packet")
}
#[test]
fn a_master_handoff_moves_mastership_exactly_once() {
for reversed in [false, true] {
let mut table = PlayerTable::default();
let now = Instant::now();
table.observe_status(&status_from(2, PlayState::PLAYING.0, true, 182), now);
table.observe_status(&status_from(1, PlayState::PLAYING.0, false, 7), now);
assert_eq!(table.master, Some(device(2)), "device 2 starts as master");
let claiming = status_from(1, PlayState::PLAYING.0, true, 7);
let dropped = status_from(2, PlayState::PLAYING.0, false, 182);
let mut events = table.observe_status(&yielding_status(2, 1), now);
let rest = if reversed {
[dropped, claiming]
} else {
[claiming, dropped]
};
for packet in &rest {
events.extend(table.observe_status(packet, now));
}
let handovers: Vec<_> = events
.iter()
.filter_map(|event| match event {
MonitorEvent::TempoMaster(master) => Some(*master),
_ => None,
})
.collect();
assert_eq!(
handovers,
vec![Some(device(1))],
"mastership moved straight from 2 to 1 (reversed: {reversed})"
);
assert_eq!(table.master, Some(device(1)));
}
}
#[test]
fn a_deck_yielding_to_a_device_that_is_not_here_is_ignored() {
let mut table = PlayerTable::default();
let now = Instant::now();
table.observe_status(&status_from(2, PlayState::PLAYING.0, true, 182), now);
table.observe_status(&yielding_status(2, 4), now);
assert_eq!(table.master, Some(device(2)));
}
#[test]
fn the_two_ports_describe_one_player() {
let mut table = PlayerTable::default();
let now = Instant::now();
table.observe_beat(&beat_at(2, 3), now);
table.observe_status(&status_from(2, PlayState::PLAYING.0, true, 182), now);
let state = table.state(device(2), now).expect("a player");
assert_eq!(state.name.as_str(), "CDJ-2000nexus");
assert!(state.effective_bpm().is_some(), "tempo from 50001");
assert_eq!(state.is_tempo_master(), Some(true), "master from 50002");
assert_eq!(state.track().map(|track| track.id), Some(182));
assert_eq!(state.beat_in_bar().map(BeatInBar::get), Some(3));
assert_eq!(table.snapshot(now).len(), 1, "one player, not two");
}
#[test]
fn play_states_are_named_where_we_have_seen_them() {
for (state, name) in [
(PlayState::NO_TRACK, "no track"),
(PlayState::PLAYING, "playing"),
(PlayState::PAUSED, "paused"),
(PlayState::EMERGENCY_LOOP, "emergency loop"),
] {
assert_eq!(state.name(), Some(name));
}
assert_eq!(PlayState(0x7f).name(), None);
assert_eq!(format!("{}", PlayState(0x7f)), "0x7f");
assert!(!PlayState::PAUSED.is_playing());
assert!(PlayState::LOOPING.is_playing());
}
}