use std::fmt;
use std::time::Duration;
use crate::device::{DeviceName, DeviceNumber};
use crate::status::{
OFF_BODY_LEN, OFF_NAME, OFF_SENDER, be_u16_at, be_u32_at, byte_at, check_header,
write_shared_header,
};
use crate::{Error, MAGIC, Result};
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct BeatKind(pub u8);
impl BeatKind {
pub const BEAT: Self = Self(0x28);
pub const FADER_START: Self = Self(0x02);
pub const CHANNELS_ON_AIR: Self = Self(0x03);
pub const ABSOLUTE_POSITION: Self = Self(0x0b);
pub const SYNC_CONTROL: Self = Self(0x2a);
pub const MASTER_REQUEST: Self = Self(0x26);
pub const MASTER_RESPONSE: Self = Self(0x27);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::BEAT => "beat",
Self::FADER_START => "fader_start",
Self::CHANNELS_ON_AIR => "channels_on_air",
Self::ABSOLUTE_POSITION => "absolute_position",
Self::SYNC_CONTROL => "sync_control",
Self::MASTER_REQUEST => "master_request",
Self::MASTER_RESPONSE => "master_response",
_ => return None,
})
}
}
impl fmt::Debug for BeatKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "BeatKind({:#04x})", self.0),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Packet {
Beat(Beat),
ChannelsOnAir(ChannelsOnAir),
FaderStart(FaderStart),
MasterRequest(MasterRequest),
MasterResponse(MasterResponse),
Other {
kind: BeatKind,
raw: Vec<u8>,
},
}
impl Packet {
pub fn kind(&self) -> BeatKind {
match self {
Self::Beat(_) => BeatKind::BEAT,
Self::ChannelsOnAir(_) => BeatKind::CHANNELS_ON_AIR,
Self::FaderStart(_) => BeatKind::FADER_START,
Self::MasterRequest(_) => BeatKind::MASTER_REQUEST,
Self::MasterResponse(_) => BeatKind::MASTER_RESPONSE,
Self::Other { kind, .. } => *kind,
}
}
}
pub fn decode(data: &[u8]) -> Result<Packet> {
if data.get(..MAGIC.len()) != Some(MAGIC.as_slice()) {
let got = data.get(..MAGIC.len()).unwrap_or(data);
return Err(Error::BadMagic {
expected: MAGIC.as_slice().into(),
got: got.into(),
});
}
let Some(&raw_kind) = data.get(MAGIC.len()) else {
return Err(Error::Truncated {
need: MAGIC.len() + 1,
at: 0,
have: data.len(),
});
};
let kind = BeatKind(raw_kind);
let other = || Packet::Other {
kind,
raw: data.to_vec(),
};
Ok(match kind {
BeatKind::BEAT => Beat::parse(data).map_or_else(|_| other(), Packet::Beat),
BeatKind::CHANNELS_ON_AIR => {
ChannelsOnAir::parse(data).map_or_else(|_| other(), Packet::ChannelsOnAir)
}
BeatKind::FADER_START => {
FaderStart::parse(data).map_or_else(|_| other(), Packet::FaderStart)
}
BeatKind::MASTER_REQUEST => {
MasterRequest::parse(data).map_or_else(|_| other(), Packet::MasterRequest)
}
BeatKind::MASTER_RESPONSE => {
MasterResponse::parse(data).map_or_else(|_| other(), Packet::MasterResponse)
}
_ => other(),
})
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Pitch(pub u32);
impl Pitch {
pub const UNITY: Self = Self(0x0010_0000);
pub fn multiplier(self) -> f64 {
f64::from(self.0) / f64::from(Self::UNITY.0)
}
pub fn percent(self) -> f64 {
(self.multiplier() - 1.0) * 100.0
}
}
impl Default for Pitch {
fn default() -> Self {
Self::UNITY
}
}
impl fmt::Debug for Pitch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:+.2}%", self.percent())
}
}
impl fmt::Display for Pitch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BeatInBar(u8);
impl BeatInBar {
pub const PER_BAR: u8 = 4;
pub const DOWNBEAT: Self = Self(1);
pub const fn new(raw: u8) -> Option<Self> {
if raw >= 1 && raw <= Self::PER_BAR {
Some(Self(raw))
} else {
None
}
}
pub const fn get(self) -> u8 {
self.0
}
pub const fn index(self) -> u8 {
self.0.saturating_sub(1)
}
pub const fn beats_to_next_bar(self) -> u8 {
Self::PER_BAR.saturating_add(1).saturating_sub(self.0)
}
}
impl fmt::Debug for BeatInBar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "beat {} of {}", self.0, Self::PER_BAR)
}
}
impl fmt::Display for BeatInBar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Timings {
pub next_beat: Option<Duration>,
pub second_beat: Option<Duration>,
pub next_bar: Option<Duration>,
pub fourth_beat: Option<Duration>,
pub second_bar: Option<Duration>,
pub eighth_beat: Option<Duration>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Beat {
pub name: DeviceName,
pub device: DeviceNumber,
pub timings: Timings,
pub pitch: Pitch,
pub bpm_centi: u16,
pub beat_in_bar: Option<BeatInBar>,
pub scratching: bool,
}
const NEVER: u32 = 0xffff_ffff;
impl Beat {
pub const LEN: usize = 0x60;
const OFF_NEXT_BEAT: usize = 0x24;
const OFF_SECOND_BEAT: usize = 0x28;
const OFF_NEXT_BAR: usize = 0x2c;
const OFF_FOURTH_BEAT: usize = 0x30;
const OFF_SECOND_BAR: usize = 0x34;
const OFF_EIGHTH_BEAT: usize = 0x38;
const OFF_FILLER: usize = 0x3c;
const LEN_FILLER: usize = 24;
const OFF_PITCH: usize = 0x54;
const OFF_SCRATCH_1: usize = 0x58;
const OFF_BPM: usize = 0x5a;
const OFF_BEAT_IN_BAR: usize = 0x5c;
const OFF_SCRATCH_2: usize = 0x5d;
const OFF_DEVICE_2: usize = 0x5f;
pub fn parse(data: &[u8]) -> Result<Self> {
check_header(data, BeatKind::BEAT.0, Self::LEN)?;
let device = DeviceNumber::new(byte_at(data, OFF_SENDER).unwrap_or(0))
.ok_or_else(|| Error::malformed(OFF_SENDER, "beat packet from device 0"))?;
let interval = |offset: usize| {
be_u32_at(data, offset)
.and_then(|raw| (raw != NEVER).then(|| Duration::from_millis(u64::from(raw))))
};
Ok(Self {
name: name_at(data),
device,
timings: Timings {
next_beat: interval(Self::OFF_NEXT_BEAT),
second_beat: interval(Self::OFF_SECOND_BEAT),
next_bar: interval(Self::OFF_NEXT_BAR),
fourth_beat: interval(Self::OFF_FOURTH_BEAT),
second_bar: interval(Self::OFF_SECOND_BAR),
eighth_beat: interval(Self::OFF_EIGHTH_BEAT),
},
pitch: Pitch(be_u32_at(data, Self::OFF_PITCH).unwrap_or(Pitch::UNITY.0)),
bpm_centi: be_u16_at(data, Self::OFF_BPM).unwrap_or(0),
beat_in_bar: BeatInBar::new(byte_at(data, Self::OFF_BEAT_IN_BAR).unwrap_or(0)),
scratching: be_u16_at(data, Self::OFF_SCRATCH_1).unwrap_or(0) != 0,
})
}
pub fn encode(&self) -> [u8; Self::LEN] {
let mut raw = [0u8; Self::LEN];
write_shared_header(&mut raw, BeatKind::BEAT.0, self.name, self.device.get());
{
let mut put_u32 = |offset: usize, value: u32| {
if let Some(field) = raw.get_mut(offset..offset.saturating_add(4)) {
field.copy_from_slice(&value.to_be_bytes());
}
};
let mut put_interval = |offset: usize, value: Option<Duration>| {
let millis = value.map_or(NEVER, |duration| {
u32::try_from(duration.as_millis()).unwrap_or(NEVER)
});
put_u32(offset, millis);
};
put_interval(Self::OFF_NEXT_BEAT, self.timings.next_beat);
put_interval(Self::OFF_SECOND_BEAT, self.timings.second_beat);
put_interval(Self::OFF_NEXT_BAR, self.timings.next_bar);
put_interval(Self::OFF_FOURTH_BEAT, self.timings.fourth_beat);
put_interval(Self::OFF_SECOND_BAR, self.timings.second_bar);
put_interval(Self::OFF_EIGHTH_BEAT, self.timings.eighth_beat);
put_u32(Self::OFF_PITCH, self.pitch.0);
}
if let Some(field) = raw.get_mut(Self::OFF_FILLER..Self::OFF_FILLER + Self::LEN_FILLER) {
field.fill(0xff);
}
let scratch = if self.scratching { 0xffffu16 } else { 0 };
for offset in [Self::OFF_SCRATCH_1, Self::OFF_SCRATCH_2] {
if let Some(field) = raw.get_mut(offset..offset + 2) {
field.copy_from_slice(&scratch.to_be_bytes());
}
}
if let Some(field) = raw.get_mut(Self::OFF_BPM..Self::OFF_BPM + 2) {
field.copy_from_slice(&self.bpm_centi.to_be_bytes());
}
if let Some(slot) = raw.get_mut(Self::OFF_BEAT_IN_BAR) {
*slot = self.beat_in_bar.map_or(0, BeatInBar::get);
}
if let Some(slot) = raw.get_mut(Self::OFF_DEVICE_2) {
*slot = self.device.get();
}
raw
}
pub fn bpm(&self) -> f64 {
f64::from(self.bpm_centi) / 100.0
}
pub fn effective_bpm(&self) -> f64 {
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()
}
}
impl fmt::Debug for Beat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Beat")
.field("device", &self.device)
.field("name", &self.name)
.field("bpm", &self.bpm())
.field("pitch", &self.pitch)
.field("effective_bpm", &self.effective_bpm())
.field("beat_in_bar", &self.beat_in_bar)
.field("next_beat", &self.timings.next_beat)
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct ChannelsOnAir {
pub name: DeviceName,
pub sender: Option<DeviceNumber>,
on_air: [bool; Self::MAX_CHANNELS],
channels: usize,
}
impl ChannelsOnAir {
pub const MAX_CHANNELS: usize = 6;
pub const FOUR_CHANNEL_LEN: usize = 0x2d;
pub const SIX_CHANNEL_LEN: usize = 0x35;
const FOUR_CHANNEL_BODY: u16 = 0x0009;
const SIX_CHANNEL_BODY: u16 = 0x0011;
const OFF_FIRST: usize = 0x24;
const OFF_FIFTH: usize = 0x2d;
pub fn parse(data: &[u8]) -> Result<Self> {
check_header(data, BeatKind::CHANNELS_ON_AIR.0, Self::FOUR_CHANNEL_LEN)?;
let body = be_u16_at(data, OFF_BODY_LEN).unwrap_or(0);
let six = match body {
Self::FOUR_CHANNEL_BODY => false,
Self::SIX_CHANNEL_BODY => true,
other => {
return Err(Error::malformed(
OFF_BODY_LEN,
format!(
"on-air body length {other:#06x} is neither the four- nor the six-channel form"
),
));
}
};
if six && data.len() < Self::SIX_CHANNEL_LEN {
return Err(Error::Truncated {
need: Self::SIX_CHANNEL_LEN,
at: 0,
have: data.len(),
});
}
let mut on_air = [false; Self::MAX_CHANNELS];
for (index, slot) in on_air.iter_mut().take(4).enumerate() {
*slot = byte_at(data, Self::OFF_FIRST.saturating_add(index)).unwrap_or(0) != 0;
}
if six {
for (index, slot) in on_air.iter_mut().skip(4).enumerate() {
*slot = byte_at(data, Self::OFF_FIFTH.saturating_add(index)).unwrap_or(0) != 0;
}
}
Ok(Self {
name: name_at(data),
sender: DeviceNumber::new(byte_at(data, OFF_SENDER).unwrap_or(0)),
on_air,
channels: if six { 6 } else { 4 },
})
}
pub fn channels(&self) -> &[bool] {
self.on_air.get(..self.channels).unwrap_or(&self.on_air)
}
pub fn is_on_air(&self, number: usize) -> Option<bool> {
self.channels().get(number.checked_sub(1)?).copied()
}
}
impl fmt::Debug for ChannelsOnAir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ChannelsOnAir")
.field("sender", &self.sender)
.field("channels", &self.channels())
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FaderAction(pub u8);
impl FaderAction {
pub const START: Self = Self(0x00);
pub const STOP: Self = Self(0x01);
pub const UNCHANGED: Self = Self(0x02);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::START => "start",
Self::STOP => "stop",
Self::UNCHANGED => "unchanged",
_ => return None,
})
}
}
impl fmt::Debug for FaderAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "FaderAction({:#04x})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct FaderStart {
pub name: DeviceName,
pub sender: Option<DeviceNumber>,
pub channels: [FaderAction; Self::CHANNELS],
}
impl FaderStart {
pub const CHANNELS: usize = 4;
pub const LEN: usize = 0x28;
const OFF_FIRST: usize = 0x24;
pub fn parse(data: &[u8]) -> Result<Self> {
check_header(data, BeatKind::FADER_START.0, Self::LEN)?;
let mut channels = [FaderAction::UNCHANGED; Self::CHANNELS];
for (index, slot) in channels.iter_mut().enumerate() {
*slot = FaderAction(byte_at(data, Self::OFF_FIRST.saturating_add(index)).unwrap_or(0));
}
Ok(Self {
name: name_at(data),
sender: DeviceNumber::new(byte_at(data, OFF_SENDER).unwrap_or(0)),
channels,
})
}
}
impl fmt::Debug for FaderStart {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FaderStart")
.field("sender", &self.sender)
.field("channels", &self.channels)
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct MasterRequest {
pub name: DeviceName,
pub device: DeviceNumber,
}
impl MasterRequest {
pub const LEN: usize = 0x28;
const OFF_DEVICE_2: usize = 0x24;
pub fn parse(data: &[u8]) -> Result<Self> {
check_header(data, BeatKind::MASTER_REQUEST.0, Self::LEN)?;
let device = DeviceNumber::new(byte_at(data, OFF_SENDER).unwrap_or(0))
.ok_or_else(|| Error::malformed(OFF_SENDER, "master request from device 0"))?;
Ok(Self {
name: name_at(data),
device,
})
}
pub fn encode(&self) -> [u8; Self::LEN] {
let mut raw = [0u8; Self::LEN];
write_shared_header(
&mut raw,
BeatKind::MASTER_REQUEST.0,
self.name,
self.device.get(),
);
if let Some(field) = raw.get_mut(Self::OFF_DEVICE_2..Self::OFF_DEVICE_2 + 4) {
field.copy_from_slice(&u32::from(self.device.get()).to_be_bytes());
}
raw
}
}
impl fmt::Debug for MasterRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MasterRequest")
.field("device", &self.device)
.field("name", &self.name)
.finish()
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct MasterResponse {
pub name: DeviceName,
pub device: DeviceNumber,
pub granted: bool,
}
impl MasterResponse {
pub const LEN: usize = 0x2c;
const OFF_DEVICE_2: usize = 0x24;
const OFF_GRANTED: usize = 0x28;
pub fn parse(data: &[u8]) -> Result<Self> {
check_header(data, BeatKind::MASTER_RESPONSE.0, Self::LEN)?;
let device = DeviceNumber::new(byte_at(data, OFF_SENDER).unwrap_or(0))
.ok_or_else(|| Error::malformed(OFF_SENDER, "master response from device 0"))?;
Ok(Self {
name: name_at(data),
device,
granted: be_u32_at(data, Self::OFF_GRANTED).unwrap_or(0) != 0,
})
}
pub fn encode(&self) -> [u8; Self::LEN] {
let mut raw = [0u8; Self::LEN];
write_shared_header(
&mut raw,
BeatKind::MASTER_RESPONSE.0,
self.name,
self.device.get(),
);
if let Some(field) = raw.get_mut(Self::OFF_DEVICE_2..Self::OFF_DEVICE_2 + 4) {
field.copy_from_slice(&u32::from(self.device.get()).to_be_bytes());
}
if let Some(field) = raw.get_mut(Self::OFF_GRANTED..Self::OFF_GRANTED + 4) {
field.copy_from_slice(&u32::from(self.granted).to_be_bytes());
}
raw
}
}
impl fmt::Debug for MasterResponse {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MasterResponse")
.field("device", &self.device)
.field("granted", &self.granted)
.field("name", &self.name)
.finish()
}
}
fn name_at(raw: &[u8]) -> DeviceName {
let mut field = [0u8; DeviceName::LEN];
if let Some(bytes) = raw.get(OFF_NAME..OFF_NAME + DeviceName::LEN) {
field.copy_from_slice(bytes);
}
DeviceName(field)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::status::{OFF_CONST_ONE, OFF_SUBTYPE};
const REAL_BEAT: [u8; Beat::LEN] = [
0x51, 0x73, 0x70, 0x74, 0x31, 0x57, 0x6d, 0x4a, 0x4f, 0x4c, 0x28, 0x43, 0x44, 0x4a, 0x2d,
0x32, 0x30, 0x30, 0x30, 0x6e, 0x65, 0x78, 0x75, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x01, 0x00, 0x3c, 0x00, 0x00, 0x01, 0xc6, 0x00, 0x00, 0x03, 0x8d, 0x00,
0x00, 0x07, 0x1a, 0x00, 0x00, 0x07, 0x1a, 0x00, 0x00, 0x0e, 0x34, 0x00, 0x00, 0x0e, 0x34,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0x83, 0x12, 0x00, 0x00,
0x33, 0x91, 0x01, 0x00, 0x00, 0x01,
];
fn real() -> Beat {
Beat::parse(&REAL_BEAT).expect("a captured beat packet")
}
#[test]
fn a_captured_beat_packet_says_what_the_deck_was_playing() {
let beat = real();
assert_eq!(beat.device.get(), 1);
assert_eq!(beat.name.as_str(), "CDJ-2000nexus");
assert_eq!(beat.bpm_centi, 13201);
assert_eq!(beat.beat_in_bar, Some(BeatInBar::DOWNBEAT));
assert!(!beat.scratching);
assert_eq!(beat.timings.next_beat, Some(Duration::from_millis(454)));
assert_eq!(beat.timings.second_beat, Some(Duration::from_millis(909)));
assert_eq!(beat.timings.next_bar, Some(Duration::from_millis(1818)));
assert_eq!(beat.timings.fourth_beat, Some(Duration::from_millis(1818)));
assert_eq!(beat.timings.second_bar, Some(Duration::from_millis(3636)));
assert_eq!(beat.timings.eighth_beat, Some(Duration::from_millis(3636)));
}
#[test]
fn a_captured_beat_packet_re_encodes_byte_for_byte() {
assert_eq!(real().encode(), REAL_BEAT);
}
#[test]
fn the_effective_tempo_is_the_one_the_fader_leaves() {
let beat = real();
assert!(
(beat.bpm() - 132.01).abs() < 0.005,
"raw tempo: {}",
beat.bpm()
);
assert!(
(beat.pitch.percent() + 3.0500).abs() < 0.001,
"pitch: {}",
beat.pitch.percent()
);
assert!(
(beat.effective_bpm() - 127.9836).abs() < 0.001,
"effective tempo: {}",
beat.effective_bpm()
);
let interval = beat.beat_interval().expect("a usable tempo");
assert!(
(interval.as_secs_f64() - 0.46881).abs() < 0.0001,
"beat interval: {interval:?}"
);
}
#[test]
fn the_timing_fields_are_quoted_at_zero_pitch() {
let beat = real();
let next = beat.timings.next_beat.expect("a next beat");
let at_zero_pitch = 60_000.0 / beat.bpm();
assert!(
(next.as_secs_f64() * 1000.0 - at_zero_pitch).abs() < 1.0,
"next beat {next:?} against {at_zero_pitch} ms at 0% pitch"
);
assert!(
beat.beat_interval().expect("a tempo").as_secs_f64() * 1000.0 - at_zero_pitch > 10.0,
"and the two are far enough apart to matter"
);
}
#[test]
fn the_next_bar_is_however_many_beats_are_left_of_this_one() {
let beat = real();
let bar = beat.timings.next_bar.expect("a next bar");
let next = beat.timings.next_beat.expect("a next beat");
let second = beat.timings.second_beat.expect("a second beat");
let step = second.saturating_sub(next);
let beats_left = beat
.beat_in_bar
.expect("a bar position")
.beats_to_next_bar();
let expected = next + step * u32::from(beats_left - 1);
assert!(
bar.abs_diff(expected) <= Duration::from_millis(3),
"next bar {bar:?} against {expected:?}"
);
}
#[test]
fn a_beat_from_device_zero_is_not_a_beat() {
let mut mangled = REAL_BEAT;
mangled[OFF_SENDER] = 0;
assert!(Beat::parse(&mangled).is_err());
assert!(matches!(
decode(&mangled),
Ok(Packet::Other {
kind: BeatKind::BEAT,
..
})
));
}
#[test]
fn a_beat_in_bar_of_zero_means_no_bar_rather_than_beat_zero() {
let mut mangled = REAL_BEAT;
mangled[Beat::OFF_BEAT_IN_BAR] = 0;
let beat = Beat::parse(&mangled).expect("still a beat packet");
assert_eq!(beat.beat_in_bar, None);
assert_eq!(beat.encode(), mangled, "and zero goes back out as zero");
assert_eq!(BeatInBar::new(0), None);
assert_eq!(BeatInBar::new(5), None);
}
#[test]
fn a_track_ending_before_a_grid_point_reports_no_distance() {
let mut mangled = REAL_BEAT;
mangled[Beat::OFF_EIGHTH_BEAT..Beat::OFF_EIGHTH_BEAT + 4].fill(0xff);
let beat = Beat::parse(&mangled).expect("still a beat packet");
assert_eq!(
beat.timings.eighth_beat, None,
"0xffffffff is 'the track ends first', not a 49-day wait"
);
assert_eq!(beat.encode(), mangled);
}
#[test]
fn scratching_sets_both_flag_words_together() {
let mut beat = real();
beat.scratching = true;
let raw = beat.encode();
assert_eq!(
&raw[Beat::OFF_SCRATCH_1..Beat::OFF_SCRATCH_1 + 2],
[0xff, 0xff]
);
assert_eq!(
&raw[Beat::OFF_SCRATCH_2..Beat::OFF_SCRATCH_2 + 2],
[0xff, 0xff]
);
assert!(Beat::parse(&raw).expect("a beat").scratching);
}
#[test]
fn the_pitch_encoding_is_fixed_point_and_not_a_percentage() {
assert!((Pitch::UNITY.multiplier() - 1.0).abs() < f64::EPSILON);
assert!(Pitch::UNITY.percent().abs() < f64::EPSILON);
assert!((Pitch(0x0000_0000).percent() + 100.0).abs() < f64::EPSILON);
assert!((Pitch(0x0020_0000).percent() - 100.0).abs() < f64::EPSILON);
}
#[test]
fn beats_to_the_next_bar_counts_down_to_one() {
let expected = [(1u8, 4u8), (2, 3), (3, 2), (4, 1)];
for (beat, left) in expected {
let position = BeatInBar::new(beat).expect("a beat in 1-4");
assert_eq!(position.beats_to_next_bar(), left, "on beat {beat}");
assert_eq!(position.index(), beat - 1);
}
}
#[test]
fn a_keep_alive_is_not_a_beat() {
let keep_alive = crate::djl::Packet::new(
DeviceName::default(),
crate::DeviceKind::CDJ,
crate::djl::Body::KeepAlive {
device_number: 2,
was_first_on_network: 1,
mac: crate::MacAddress::default(),
ip: std::net::Ipv4Addr::UNSPECIFIED,
peer_count: 1,
pad_31: [0; 3],
flags: 1,
trailing: 0,
},
)
.encode();
assert!(Beat::parse(&keep_alive).is_err());
assert!(matches!(decode(&keep_alive), Ok(Packet::Other { .. })));
}
#[test]
fn something_that_is_not_pro_dj_link_is_rejected_before_anything_else() {
assert!(matches!(
decode(b"not a datagram"),
Err(Error::BadMagic { .. })
));
assert!(decode(&[]).is_err());
}
fn synthetic(kind: BeatKind, subtype: u8, len: usize) -> Vec<u8> {
let mut raw = vec![0u8; len];
write_shared_header(&mut raw, kind.0, DeviceName::new("DJM-2000nexus"), 0x21);
raw[OFF_SUBTYPE] = subtype;
raw
}
#[test]
fn the_four_channel_on_air_form_says_nothing_about_channels_five_and_six() {
let mut raw = synthetic(
BeatKind::CHANNELS_ON_AIR,
0x00,
ChannelsOnAir::FOUR_CHANNEL_LEN,
);
raw[0x24] = 1;
raw[0x26] = 1;
let Ok(Packet::ChannelsOnAir(on_air)) = decode(&raw) else {
panic!("a four-channel on-air packet");
};
assert_eq!(on_air.channels(), [true, false, true, false]);
assert_eq!(on_air.is_on_air(1), Some(true));
assert_eq!(on_air.is_on_air(2), Some(false));
assert_eq!(on_air.is_on_air(5), None);
assert_eq!(on_air.is_on_air(0), None, "channels are 1-based");
assert_eq!(on_air.sender.map(DeviceNumber::get), Some(0x21));
assert_eq!(
u16::from_be_bytes([raw[OFF_BODY_LEN], raw[OFF_BODY_LEN + 1]]),
ChannelsOnAir::FOUR_CHANNEL_BODY
);
}
#[test]
fn the_six_channel_on_air_form_carries_two_more_past_the_padding() {
let mut raw = synthetic(
BeatKind::CHANNELS_ON_AIR,
0x03,
ChannelsOnAir::SIX_CHANNEL_LEN,
);
raw[0x24] = 1;
raw[ChannelsOnAir::OFF_FIFTH + 1] = 1;
let on_air = ChannelsOnAir::parse(&raw).expect("a six-channel on-air packet");
assert_eq!(
on_air.channels(),
[true, false, false, false, false, true],
"channels 5 and 6 sit past five pad bytes"
);
}
#[test]
fn a_six_channel_on_air_packet_cut_short_is_truncated_not_four_channel() {
let mut raw = synthetic(
BeatKind::CHANNELS_ON_AIR,
0x03,
ChannelsOnAir::SIX_CHANNEL_LEN,
);
raw.truncate(ChannelsOnAir::FOUR_CHANNEL_LEN);
let error = ChannelsOnAir::parse(&raw).expect_err("a truncated packet");
assert!(error.is_truncated(), "{error}");
}
#[test]
fn fader_start_names_one_action_per_channel() {
let mut raw = synthetic(BeatKind::FADER_START, 0x00, FaderStart::LEN);
raw[0x24] = FaderAction::START.0;
raw[0x25] = FaderAction::STOP.0;
raw[0x26] = FaderAction::UNCHANGED.0;
raw[0x27] = 0x7f;
let Ok(Packet::FaderStart(fader)) = decode(&raw) else {
panic!("a fader-start packet");
};
assert_eq!(
fader.channels,
[
FaderAction::START,
FaderAction::STOP,
FaderAction::UNCHANGED,
FaderAction(0x7f),
]
);
assert_eq!(
fader.channels[3].name(),
None,
"and an unknown one stays a byte"
);
}
#[test]
fn an_unmodelled_kind_survives_as_bytes() {
let raw = synthetic(BeatKind::ABSOLUTE_POSITION, 0x02, 0x3c);
let decoded = decode(&raw).expect("a well-formed datagram");
assert_eq!(decoded.kind(), BeatKind::ABSOLUTE_POSITION);
assert!(matches!(decoded, Packet::Other { ref raw, .. } if raw.len() == 0x3c));
assert_eq!(BeatKind(0x77).name(), None);
assert_eq!(format!("{:?}", BeatKind(0x77)), "BeatKind(0x77)");
}
const REAL_MASTER_REQUEST: [u8; MasterRequest::LEN] = [
0x51, 0x73, 0x70, 0x74, 0x31, 0x57, 0x6d, 0x4a, 0x4f, 0x4c, 0x26, 0x43, 0x44, 0x4a, 0x2d,
0x32, 0x30, 0x30, 0x30, 0x6e, 0x65, 0x78, 0x75, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01,
];
const REAL_MASTER_RESPONSE: [u8; MasterResponse::LEN] = [
0x51, 0x73, 0x70, 0x74, 0x31, 0x57, 0x6d, 0x4a, 0x4f, 0x4c, 0x27, 0x43, 0x44, 0x4a, 0x2d,
0x32, 0x30, 0x30, 0x30, 0x6e, 0x65, 0x78, 0x75, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x02, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01,
];
#[test]
fn a_master_request_names_the_deck_that_wants_it() {
let Packet::MasterRequest(request) = decode(&REAL_MASTER_REQUEST).expect("a datagram")
else {
panic!("not decoded as a master request");
};
assert_eq!(request.device.get(), 1);
assert_eq!(request.name.to_string(), "CDJ-2000nexus");
assert_eq!(request.encode(), REAL_MASTER_REQUEST);
}
#[test]
fn a_master_response_names_the_deck_giving_it_up_not_the_one_asking() {
let Packet::MasterResponse(response) = decode(&REAL_MASTER_RESPONSE).expect("a datagram")
else {
panic!("not decoded as a master response");
};
assert_eq!(response.device.get(), 2);
assert!(response.granted);
assert_eq!(response.encode(), REAL_MASTER_RESPONSE);
}
#[test]
fn the_body_length_field_matches_the_two_handoff_layouts() {
let request = MasterRequest {
name: DeviceName::new("CDJ-2000nexus"),
device: DeviceNumber::new(1).expect("1 is a device number"),
};
assert_eq!(be_u16_at(&request.encode(), OFF_BODY_LEN), Some(0x0004));
assert_eq!(byte_at(&request.encode(), OFF_SUBTYPE), Some(0x00));
let response = MasterResponse {
name: DeviceName::new("CDJ-2000nexus"),
device: DeviceNumber::new(2).expect("2 is a device number"),
granted: true,
};
assert_eq!(be_u16_at(&response.encode(), OFF_BODY_LEN), Some(0x0008));
assert_eq!(byte_at(&response.encode(), OFF_CONST_ONE), Some(0x01));
}
#[test]
fn a_handoff_packet_from_device_zero_is_refused() {
let mut raw = REAL_MASTER_REQUEST;
raw[OFF_SENDER] = 0;
assert!(MasterRequest::parse(&raw).is_err());
assert!(matches!(
decode(&raw).expect("still a datagram"),
Packet::Other { kind, .. } if kind == BeatKind::MASTER_REQUEST
));
}
fn corpus_beats() -> Vec<Vec<u8>> {
let Some(corpus) = prolink_capture::Corpus::locate() else {
return Vec::new();
};
let mut found = Vec::new();
for path in corpus.captures() {
let Ok(capture) = prolink_capture::Capture::open(&path) else {
continue;
};
for packet in capture.udp_to(prolink_capture::BEAT_PORT).flatten() {
found.push(packet.payload.clone());
}
}
found
}
#[test]
fn every_beat_packet_in_the_corpus_re_encodes_byte_for_byte() {
let datagrams = corpus_beats();
if datagrams.is_empty() {
return;
}
assert!(
datagrams.len() >= 1000,
"the corpus holds 1110 datagrams addressed to 50001; found {}",
datagrams.len()
);
let mut beats = 0usize;
let mut handoff = 0usize;
for raw in &datagrams {
let encoded = match decode(raw).expect("a Pro DJ Link datagram") {
Packet::Beat(beat) => {
assert_eq!(raw.len(), Beat::LEN, "beat packets are a fixed 96 bytes");
beats += 1;
beat.encode().to_vec()
}
Packet::MasterRequest(request) => {
handoff += 1;
request.encode().to_vec()
}
Packet::MasterResponse(response) => {
handoff += 1;
response.encode().to_vec()
}
other => panic!("unexpected 50001 datagram: {:?}", other.kind()),
};
assert_eq!(
encoded.as_slice(),
raw.as_slice(),
"re-encoding a {:?} changed bytes",
decode(raw).map(|packet| packet.kind())
);
}
assert!(beats >= 4400, "only {beats} beat packets re-encoded");
assert!(
handoff >= 10,
"the corpus holds five master handoffs — ten datagrams; found {handoff}"
);
assert_eq!(
beats + handoff,
datagrams.len(),
"every datagram on 50001 is either a beat or a master handoff"
);
}
#[test]
fn every_beat_packet_in_the_corpus_is_internally_consistent() {
let datagrams = corpus_beats();
if datagrams.is_empty() {
return;
}
let mut checked = 0usize;
for raw in &datagrams {
let Ok(Packet::Beat(beat)) = decode(raw) else {
continue;
};
let next = beat.timings.next_beat.expect("a next beat");
let second = beat.timings.second_beat.expect("a second beat");
let step = second.saturating_sub(next);
let at_zero_pitch = 60_000.0 / beat.bpm();
let millis = next.as_secs_f64() * 1000.0;
assert!(
(millis - at_zero_pitch).abs() <= 1.0,
"next beat {millis} ms against {at_zero_pitch} ms at 0% pitch, in {beat:?}"
);
let position = beat.beat_in_bar.expect("a bar position");
let expect = |beats: u32| next + step * beats.saturating_sub(1);
for (label, field, beats) in [
("fourth beat", beat.timings.fourth_beat, 4),
("eighth beat", beat.timings.eighth_beat, 8),
(
"next bar",
beat.timings.next_bar,
u32::from(position.beats_to_next_bar()),
),
(
"second bar",
beat.timings.second_bar,
u32::from(position.beats_to_next_bar()) + 4,
),
] {
let actual = field.expect(label);
assert!(
actual.abs_diff(expect(beats)) <= Duration::from_millis(7),
"{label} {actual:?} against {:?} in {beat:?}",
expect(beats)
);
}
checked += 1;
}
assert!(checked >= 1000, "checked only {checked} beat packets");
}
#[test]
fn the_corpus_holds_only_shapes_this_codec_expects() {
let datagrams = corpus_beats();
if datagrams.is_empty() {
return;
}
for raw in &datagrams {
if byte_at(raw, MAGIC.len()) != Some(BeatKind::BEAT.0) {
continue;
}
assert_eq!(
byte_at(raw, OFF_SUBTYPE),
Some(0x00),
"every captured beat packet is subtype 0x00"
);
assert_eq!(
be_u16_at(raw, OFF_BODY_LEN),
Some(0x003c),
"and declares 0x3c bytes of body"
);
assert_eq!(
byte_at(raw, OFF_CONST_ONE),
Some(0x01),
"byte 0x1f is structural here too, not the last byte of the name (C14)"
);
assert_eq!(
raw.get(Beat::OFF_FILLER..Beat::OFF_FILLER + Beat::LEN_FILLER),
Some([0xffu8; Beat::LEN_FILLER].as_slice()),
"the filler is 24 bytes of 0xff, never anything else"
);
assert_eq!(
byte_at(raw, OFF_SENDER),
byte_at(raw, Beat::OFF_DEVICE_2),
"the device number is repeated at 0x5f and always agrees"
);
}
}
}