use std::fmt;
use crate::device::{BrowsableDeviceNumber, DeviceNumber};
use crate::{Error, Result, Slot};
pub const MAGIC: u32 = 0x8723_49AE;
pub const PORT: u16 = 1051;
pub const PORT_QUERY_PORT: u16 = 12523;
pub const PORT_QUERY: [u8; 19] = [
0x00, 0x00, 0x00, 0x0f, b'R', b'e', b'm', b'o', b't', b'e', b'D', b'B', b'S', b'e', b'r', b'v',
b'e', b'r', 0x00,
];
pub const PREAMBLE: [u8; 5] = [FieldTag::U32.0, 0x00, 0x00, 0x00, 0x01];
pub const SETUP_TRANSACTION_ID: u32 = 0xFFFF_FFFE;
pub const FIRST_TRANSACTION_ID: u32 = 0x0380_0001;
pub const MAX_RENDER_BATCH: u32 = 64;
const ARG_TAG_BLOB_LEN: usize = 12;
const HEADER_LEN: usize = 5 + 5 + 3 + 2 + 5 + ARG_TAG_BLOB_LEN;
const MAX_BLOB_LEN: u32 = 16 * 1024 * 1024;
const MAX_STRING_CHARS: u32 = MAX_BLOB_LEN / 2;
pub fn skip_preamble(data: &[u8]) -> &[u8] {
match data.get(..PREAMBLE.len()) {
Some(head) if head == PREAMBLE => data.get(PREAMBLE.len()..).unwrap_or(&[]),
_ => data,
}
}
pub fn encode_port_reply(port: u16) -> [u8; 2] {
port.to_be_bytes()
}
pub fn decode_port_reply(data: &[u8]) -> Result<u16> {
let bytes: [u8; 2] = data
.get(..2)
.and_then(|slice| slice.try_into().ok())
.ok_or(Error::Truncated {
need: 2,
at: 0,
have: data.len(),
})?;
Ok(u16::from_be_bytes(bytes))
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FieldTag(pub u8);
impl FieldTag {
pub const U8: Self = Self(0x0f);
pub const U16: Self = Self(0x10);
pub const U32: Self = Self(0x11);
pub const BLOB: Self = Self(0x14);
pub const TEXT: Self = Self(0x26);
pub const fn arg_tag(self) -> Option<ArgTag> {
Some(match self {
Self::U8 => ArgTag::U8,
Self::U16 => ArgTag::U16,
Self::U32 => ArgTag::U32,
Self::BLOB => ArgTag::BLOB,
Self::TEXT => ArgTag::TEXT,
_ => return None,
})
}
}
impl fmt::Debug for FieldTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::U8 => f.write_str("u8"),
Self::U16 => f.write_str("u16"),
Self::U32 => f.write_str("u32"),
Self::BLOB => f.write_str("blob"),
Self::TEXT => f.write_str("text"),
Self(raw) => write!(f, "FieldTag({raw:#04x})"),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ArgTag(pub u8);
impl ArgTag {
pub const TEXT: Self = Self(0x02);
pub const BLOB: Self = Self(0x03);
pub const U8: Self = Self(0x04);
pub const U16: Self = Self(0x05);
pub const U32: Self = Self(0x06);
pub const fn field_tag(self) -> Option<FieldTag> {
Some(match self {
Self::U8 => FieldTag::U8,
Self::U16 => FieldTag::U16,
Self::U32 => FieldTag::U32,
Self::BLOB => FieldTag::BLOB,
Self::TEXT => FieldTag::TEXT,
_ => return None,
})
}
}
impl fmt::Debug for ArgTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::TEXT => f.write_str("text"),
Self::BLOB => f.write_str("blob"),
Self::U8 => f.write_str("u8"),
Self::U16 => f.write_str("u16"),
Self::U32 => f.write_str("u32"),
Self(raw) => write!(f, "ArgTag({raw:#04x})"),
}
}
}
pub const NUL: u16 = 0x0000;
pub fn encode_string(text: &str) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + text.len() * 2 + 2);
write_string(&mut out, text, Some(NUL));
out
}
pub fn string_characters(text: &str) -> u32 {
utf16_units(text).saturating_add(1)
}
fn utf16_units(text: &str) -> u32 {
u32::try_from(text.encode_utf16().count()).unwrap_or(u32::MAX)
}
fn write_string(out: &mut Vec<u8>, text: &str, terminator: Option<u16>) {
let count = utf16_units(text).saturating_add(u32::from(terminator.is_some()));
out.extend_from_slice(&count.to_be_bytes());
for unit in text.encode_utf16() {
out.extend_from_slice(&unit.to_be_bytes());
}
if let Some(terminator) = terminator {
out.extend_from_slice(&terminator.to_be_bytes());
}
}
pub fn label_bytes(text: &str) -> u32 {
string_characters(text).saturating_mul(2)
}
fn decode_string_body(bytes: &[u8]) -> (String, Option<u16>) {
let mut units: Vec<u16> = bytes
.chunks_exact(2)
.map(|pair| {
u16::from_be_bytes([
pair.first().copied().unwrap_or(0),
pair.get(1).copied().unwrap_or(0),
])
})
.collect();
let terminator = units.pop();
(String::from_utf16_lossy(&units), terminator)
}
#[derive(Clone, PartialEq, Eq)]
pub enum Field {
U8(u8),
U16(u16),
U32(u32),
Blob(Vec<u8>),
Text {
text: String,
terminator: Option<u16>,
},
}
impl Field {
pub const fn tag(&self) -> FieldTag {
match *self {
Self::U8(_) => FieldTag::U8,
Self::U16(_) => FieldTag::U16,
Self::U32(_) => FieldTag::U32,
Self::Blob(_) => FieldTag::BLOB,
Self::Text { .. } => FieldTag::TEXT,
}
}
pub const fn arg_tag(&self) -> ArgTag {
match *self {
Self::U8(_) => ArgTag::U8,
Self::U16(_) => ArgTag::U16,
Self::U32(_) => ArgTag::U32,
Self::Blob(_) => ArgTag::BLOB,
Self::Text { .. } => ArgTag::TEXT,
}
}
pub fn number(&self) -> Option<u32> {
Some(match *self {
Self::U8(value) => u32::from(value),
Self::U16(value) => u32::from(value),
Self::U32(value) => value,
_ => return None,
})
}
pub fn text(&self) -> Option<&str> {
match self {
Self::Text { text, .. } => Some(text),
_ => None,
}
}
pub fn blob(&self) -> Option<&[u8]> {
match self {
Self::Blob(value) => Some(value),
_ => None,
}
}
fn presence_value(&self) -> u32 {
self.number().unwrap_or(1)
}
fn write(&self, out: &mut Vec<u8>) {
out.push(self.tag().0);
match self {
Self::U8(value) => out.push(*value),
Self::U16(value) => out.extend_from_slice(&value.to_be_bytes()),
Self::U32(value) => out.extend_from_slice(&value.to_be_bytes()),
Self::Blob(value) => {
let length = u32::try_from(value.len()).unwrap_or(u32::MAX);
out.extend_from_slice(&length.to_be_bytes());
out.extend_from_slice(value);
}
Self::Text { text, terminator } => write_string(out, text, *terminator),
}
}
}
impl fmt::Debug for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::U8(value) => write!(f, "{value:#04x}"),
Self::U16(value) => write!(f, "{value:#06x}"),
Self::U32(value) => write!(f, "{value:#010x}"),
Self::Blob(value) => write!(f, "<{}B>", value.len()),
Self::Text {
text,
terminator: Some(NUL) | None,
} => write!(f, "{text:?}"),
Self::Text { text, terminator } => write!(f, "{text:?}+{terminator:04x?}"),
}
}
}
impl From<u32> for Field {
fn from(value: u32) -> Self {
Self::U32(value)
}
}
impl From<&str> for Field {
fn from(value: &str) -> Self {
Self::from(value.to_owned())
}
}
impl From<String> for Field {
fn from(text: String) -> Self {
Self::Text {
text,
terminator: Some(NUL),
}
}
}
impl From<Vec<u8>> for Field {
fn from(value: Vec<u8>) -> Self {
Self::Blob(value)
}
}
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Arguments(Vec<Field>);
impl Arguments {
pub const MAX: usize = ARG_TAG_BLOB_LEN;
pub fn new(fields: impl IntoIterator<Item = Field>) -> Option<Self> {
let fields: Vec<Field> = fields.into_iter().collect();
(fields.len() <= Self::MAX).then_some(Self(fields))
}
pub fn as_slice(&self) -> &[Field] {
&self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn get(&self, index: usize) -> Option<&Field> {
self.0.get(index)
}
pub fn number(&self, index: usize) -> Option<u32> {
self.get(index).and_then(Field::number)
}
pub fn text(&self, index: usize) -> Option<&str> {
self.get(index).and_then(Field::text)
}
pub fn blob(&self, index: usize) -> Option<&[u8]> {
self.get(index).and_then(Field::blob)
}
}
impl<const N: usize> From<[Field; N]> for Arguments {
fn from(fields: [Field; N]) -> Self {
const {
assert!(
N <= Arguments::MAX,
"a dbserver message carries at most twelve arguments"
);
}
Self(fields.into())
}
}
impl fmt::Debug for Arguments {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(&self.0).finish()
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MessageKind(pub u16);
impl MessageKind {
pub const INTRODUCE: Self = Self(0x0000);
pub const MENU_CLOSE: Self = Self(0x0001);
pub const DISCONNECT: Self = Self(0x0100);
pub const MENU_ROOT: Self = Self(0x1000);
pub const MENU_GENRE: Self = Self(0x1001);
pub const MENU_ARTIST: Self = Self(0x1002);
pub const MENU_ALBUM: Self = Self(0x1003);
pub const MENU_TRACK: Self = Self(0x1004);
pub const MENU_BPM: Self = Self(0x1006);
pub const MENU_RATING: Self = Self(0x1007);
pub const MENU_YEAR: Self = Self(0x1008);
pub const MENU_LABEL: Self = Self(0x100a);
pub const MENU_COLOR: Self = Self(0x100d);
pub const MENU_TIME: Self = Self(0x1010);
pub const MENU_BITRATE: Self = Self(0x1011);
pub const MENU_HISTORY: Self = Self(0x1012);
pub const MENU_FILENAME: Self = Self(0x1013);
pub const MENU_KEY: Self = Self(0x1014);
pub const MENU_TAG_LIST: Self = Self(0x100f);
pub const MENU_PLAYLIST: Self = Self(0x1105);
pub const MENU_SEARCH: Self = Self(0x1300);
pub const MENU_SORT: Self = Self(0x1400);
pub const MENU_FOLDER: Self = Self(0x2006);
pub const GET_METADATA: Self = Self(0x2002);
pub const GET_ARTWORK: Self = Self(0x2003);
pub const GET_WAVEFORM_PREVIEW: Self = Self(0x2004);
pub const GET_TRACK_INFO: Self = Self(0x2102);
pub const GET_CUE_POINTS: Self = Self(0x2104);
pub const GET_GENERIC_METADATA: Self = Self(0x2202);
pub const GET_BEAT_GRID: Self = Self(0x2204);
pub const GET_VBR_INDEX: Self = Self(0x2504);
pub const GET_MEDIA_INFO: Self = Self(0x3903);
pub const UNKNOWN_3001: Self = Self(0x3001);
pub const HAND_BACK_WAVEFORM_PREVIEW: Self = Self(0x2005);
pub const HAND_BACK_VBR_INDEX: Self = Self(0x2205);
pub const UNPLAYABLE: Self = Self(0x3503);
pub const GET_WAVEFORM_DETAIL: Self = Self(0x2904);
pub const GET_CUE_POINTS_EXT: Self = Self(0x2b04);
pub const GET_ANALYSIS_TAG: Self = Self(0x2c04);
pub const RENDER_MENU: Self = Self(0x3000);
pub const TAG_LIST_ADD: Self = Self(0x3002);
pub const TAG_LIST_CLEAR: Self = Self(0x3202);
pub const UNKNOWN_3402: Self = Self(0x3402);
pub const UNKNOWN_3100: Self = Self(0x3100);
pub const UNKNOWN_3D03: Self = Self(0x3d03);
pub const UNKNOWN_3E03: Self = Self(0x3e03);
pub const SUCCESS: Self = Self(0x4000);
pub const MENU_HEADER: Self = Self(0x4001);
pub const ARTWORK: Self = Self(0x4002);
pub const ERROR: Self = Self(0x4003);
pub const MENU_ITEM: Self = Self(0x4101);
pub const MENU_FOOTER: Self = Self(0x4201);
pub const WAVEFORM_PREVIEW: Self = Self(0x4402);
pub const VBR_INDEX: Self = Self(0x4502);
pub const MEDIA_INFO: Self = Self(0x4902);
pub const BEAT_GRID: Self = Self(0x4602);
pub const CUE_POINTS: Self = Self(0x4702);
pub const WAVEFORM_DETAIL: Self = Self(0x4a02);
pub const UNKNOWN_4B02: Self = Self(0x4b02);
pub const CUE_POINTS_EXT: Self = Self(0x4e02);
pub const ANALYSIS_TAG: Self = Self(0x4f02);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::INTRODUCE => "introduce",
Self::MENU_CLOSE => "menu_close",
Self::DISCONNECT => "disconnect",
Self::MENU_ROOT => "menu_root",
Self::MENU_GENRE => "menu_genre",
Self::MENU_ARTIST => "menu_artist",
Self::MENU_ALBUM => "menu_album",
Self::MENU_TRACK => "menu_track",
Self::MENU_BPM => "menu_bpm",
Self::MENU_RATING => "menu_rating",
Self::MENU_YEAR => "menu_year",
Self::MENU_LABEL => "menu_label",
Self::MENU_COLOR => "menu_color",
Self::MENU_TIME => "menu_time",
Self::MENU_BITRATE => "menu_bitrate",
Self::MENU_HISTORY => "menu_history",
Self::MENU_FILENAME => "menu_filename",
Self::MENU_KEY => "menu_key",
Self::MENU_TAG_LIST => "menu_tag_list",
Self::TAG_LIST_ADD => "tag_list_add",
Self::TAG_LIST_CLEAR => "tag_list_clear",
Self::MENU_PLAYLIST => "menu_playlist",
Self::MENU_SEARCH => "menu_search",
Self::MENU_SORT => "menu_sort",
Self::MENU_FOLDER => "menu_folder",
Self::GET_METADATA => "get_metadata",
Self::GET_ARTWORK => "get_artwork",
Self::GET_WAVEFORM_PREVIEW => "get_waveform_preview",
Self::GET_TRACK_INFO => "get_track_info",
Self::GET_CUE_POINTS => "get_cue_points",
Self::GET_GENERIC_METADATA => "get_generic_metadata",
Self::GET_BEAT_GRID => "get_beat_grid",
Self::GET_VBR_INDEX => "get_vbr_index",
Self::GET_MEDIA_INFO => "get_media_info",
Self::UNKNOWN_3001 => "unknown_3001",
Self::HAND_BACK_WAVEFORM_PREVIEW => "hand_back_waveform_preview",
Self::HAND_BACK_VBR_INDEX => "hand_back_vbr_index",
Self::UNPLAYABLE => "unplayable",
Self::MEDIA_INFO => "media_info",
Self::GET_WAVEFORM_DETAIL => "get_waveform_detail",
Self::GET_CUE_POINTS_EXT => "get_cue_points_ext",
Self::GET_ANALYSIS_TAG => "get_analysis_tag",
Self::RENDER_MENU => "render_menu",
Self::UNKNOWN_3100 => "unknown_3100",
Self::UNKNOWN_3D03 => "unknown_3d03",
Self::UNKNOWN_3E03 => "unknown_3e03",
Self::SUCCESS => "success",
Self::MENU_HEADER => "menu_header",
Self::ARTWORK => "artwork",
Self::ERROR => "error",
Self::MENU_ITEM => "menu_item",
Self::MENU_FOOTER => "menu_footer",
Self::WAVEFORM_PREVIEW => "waveform_preview",
Self::VBR_INDEX => "vbr_index",
Self::BEAT_GRID => "beat_grid",
Self::CUE_POINTS => "cue_points",
Self::WAVEFORM_DETAIL => "waveform_detail",
Self::UNKNOWN_4B02 => "unknown_4b02",
Self::CUE_POINTS_EXT => "cue_points_ext",
Self::ANALYSIS_TAG => "analysis_tag",
_ => return None,
})
}
pub fn expects_no_reply(self) -> bool {
matches!(
self,
Self::MENU_CLOSE
| Self::UNKNOWN_3001
| Self::HAND_BACK_WAVEFORM_PREVIEW
| Self::HAND_BACK_VBR_INDEX
| Self::UNPLAYABLE
)
}
}
impl fmt::Debug for MessageKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "MessageKind({:#06x})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub struct Drill {
pub depth: u8,
pub category: u8,
}
impl Drill {
pub fn kind(self) -> MessageKind {
drill_kind(self.depth, self.category)
}
pub fn parse(kind: MessageKind) -> Option<Self> {
let raw = kind.0;
if raw & 0xf000 != 0x1000 {
return None;
}
let depth = u8::try_from((raw >> 8) & 0x0f).ok()?;
if depth == 0 {
return None;
}
Some(Self {
depth,
category: u8::try_from(raw & 0xff).ok()?,
})
}
}
pub fn drill_kind(depth: u8, category: u8) -> MessageKind {
MessageKind(0x1000 | (u16::from(depth) << 8) | u16::from(category))
}
pub const FILTER_ALL: u32 = 0xFFFF_FFFF;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct MenuTarget(pub u8);
impl MenuTarget {
pub const MAIN: Self = Self(0x01);
pub const SUB: Self = Self(0x02);
pub const PREVIEW: Self = Self(0x03);
pub const BINARY: Self = Self(0x08);
}
impl fmt::Debug for MenuTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::MAIN => f.write_str("main"),
Self::SUB => f.write_str("sub"),
Self::PREVIEW => f.write_str("preview"),
Self::BINARY => f.write_str("binary"),
Self(raw) => write!(f, "MenuTarget({raw:#04x})"),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct TrackType(pub u8);
impl TrackType {
pub const REKORDBOX: Self = Self(1);
pub const UNANALYSED: Self = Self(2);
pub const CD_AUDIO: Self = Self(5);
pub const STREAMING: Self = Self(6);
}
impl fmt::Debug for TrackType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::REKORDBOX => f.write_str("rekordbox"),
Self::UNANALYSED => f.write_str("unanalysed"),
Self::CD_AUDIO => f.write_str("cd_audio"),
Self::STREAMING => f.write_str("streaming"),
Self(raw) => write!(f, "TrackType({raw:#04x})"),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub struct Descriptor {
pub device: DeviceNumber,
pub menu: MenuTarget,
pub slot: Slot,
pub track_type: TrackType,
}
impl Descriptor {
pub fn new(
device: BrowsableDeviceNumber,
slot: Slot,
menu: MenuTarget,
track_type: TrackType,
) -> Self {
Self {
device: device.number(),
menu,
slot,
track_type,
}
}
pub fn parse(raw: u32) -> Option<Self> {
let [device, menu, slot, track_type] = raw.to_be_bytes();
Some(Self {
device: DeviceNumber::new(device)?,
menu: MenuTarget(menu),
slot: Slot(slot),
track_type: TrackType(track_type),
})
}
pub fn to_raw(self) -> u32 {
u32::from_be_bytes([
self.device.get(),
self.menu.0,
self.slot.0,
self.track_type.0,
])
}
#[must_use]
pub fn with_menu(mut self, menu: MenuTarget) -> Self {
self.menu = menu;
self
}
}
impl From<Descriptor> for Field {
fn from(descriptor: Descriptor) -> Self {
Self::U32(descriptor.to_raw())
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Message {
pub transaction_id: u32,
pub kind: MessageKind,
pub args: Arguments,
}
impl Message {
pub fn new(transaction_id: u32, kind: MessageKind, args: impl Into<Arguments>) -> Self {
Self {
transaction_id,
kind,
args: args.into(),
}
}
pub fn decode(data: &[u8]) -> Result<(Self, usize)> {
let mut reader = Reader::new(data);
reader.magic()?;
let transaction_id = reader.tagged_u32("transaction id")?;
let kind = MessageKind(reader.tagged_u16("message type")?);
let count = usize::from(reader.tagged_u8("argument count")?);
let tags = reader.arg_tag_blob()?;
if count > Arguments::MAX {
return Err(Error::malformed(
14,
format!("argument count {count} exceeds the twelve the tag blob describes"),
));
}
let mut fields = Vec::with_capacity(count);
let mut previous = 1u32;
for index in 0..count {
let arg_tag = ArgTag(tags.get(index).copied().unwrap_or(0));
let field = if arg_tag == ArgTag::BLOB && previous == 0 {
Field::Blob(Vec::new())
} else {
reader.field(arg_tag, index)?
};
previous = field.presence_value();
fields.push(field);
}
let args = Arguments::new(fields).unwrap_or_default();
let consumed = reader.position();
Ok((
Self {
transaction_id,
kind,
args,
},
consumed,
))
}
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(HEADER_LEN + 8 * self.args.len());
Field::U32(MAGIC).write(&mut out);
Field::U32(self.transaction_id).write(&mut out);
Field::U16(self.kind.0).write(&mut out);
let count = u8::try_from(self.args.len()).unwrap_or(0);
Field::U8(count).write(&mut out);
let mut tags = [0u8; ARG_TAG_BLOB_LEN];
for (slot, field) in tags.iter_mut().zip(self.args.as_slice()) {
*slot = field.arg_tag().0;
}
Field::Blob(tags.to_vec()).write(&mut out);
let mut previous = 1u32;
for field in self.args.as_slice() {
let omitted = previous == 0 && matches!(field, Field::Blob(blob) if blob.is_empty());
if !omitted {
field.write(&mut out);
}
previous = field.presence_value();
}
out
}
pub fn number(&self, index: usize) -> Option<u32> {
self.args.number(index)
}
pub fn text(&self, index: usize) -> Option<&str> {
self.args.text(index)
}
pub fn blob(&self, index: usize) -> Option<&[u8]> {
self.args.blob(index)
}
pub fn descriptor(&self) -> Option<Descriptor> {
self.number(0).and_then(Descriptor::parse)
}
pub fn introduce(device: BrowsableDeviceNumber) -> Self {
Self::new(
SETUP_TRANSACTION_ID,
MessageKind::INTRODUCE,
[Field::U32(u32::from(device.get()))],
)
}
pub fn disconnect() -> Self {
Self::new(SETUP_TRANSACTION_ID, MessageKind::DISCONNECT, [])
}
pub fn render(transaction_id: u32, descriptor: Descriptor, offset: u32, limit: u32) -> Self {
Self::render_of(transaction_id, descriptor, offset, limit, limit)
}
pub fn render_of(
transaction_id: u32,
descriptor: Descriptor,
offset: u32,
limit: u32,
total: u32,
) -> Self {
Self::new(
transaction_id,
MessageKind::RENDER_MENU,
[
descriptor.into(),
Field::U32(offset),
Field::U32(limit),
Field::U32(0),
Field::U32(total),
Field::U32(0),
],
)
}
pub fn menu_request(
transaction_id: u32,
kind: MessageKind,
descriptor: Descriptor,
extra: &[u32],
) -> Option<Self> {
let args = Arguments::new(
std::iter::once(Field::from(descriptor)).chain(extra.iter().copied().map(Field::U32)),
)?;
Some(Self {
transaction_id,
kind,
args,
})
}
pub fn search(
transaction_id: u32,
descriptor: Descriptor,
sort: SortOrder,
term: &str,
) -> Self {
Self::new(
transaction_id,
MessageKind::MENU_SEARCH,
[
descriptor.into(),
Field::U32(sort.0),
Field::U32(label_bytes(term)),
Field::from(term),
Field::U32(0),
],
)
}
pub fn success(transaction_id: u32, request: MessageKind, count: u32) -> Self {
Self::new(
transaction_id,
MessageKind::SUCCESS,
[Field::U32(u32::from(request.0)), Field::U32(count)],
)
}
pub fn introduce_reply(server: DeviceNumber) -> Self {
Self::new(
SETUP_TRANSACTION_ID,
MessageKind::SUCCESS,
[
Field::U32(u32::from(MessageKind::INTRODUCE.0)),
Field::U32(u32::from(server.get())),
],
)
}
pub fn unknown_3e03_reply(transaction_id: u32, server: DeviceNumber) -> Self {
Self::new(
transaction_id,
MessageKind::UNKNOWN_4B02,
[
Field::U32(u32::from(MessageKind::UNKNOWN_3E03.0)),
Field::U32(0),
Field::U32(u32::from(server.get())),
Field::from(""),
],
)
}
pub fn menu_header(transaction_id: u32) -> Self {
Self::new(
transaction_id,
MessageKind::MENU_HEADER,
[Field::U32(1), Field::U32(0)],
)
}
pub fn menu_footer(transaction_id: u32) -> Self {
Self::new(transaction_id, MessageKind::MENU_FOOTER, [])
}
pub fn binary_reply(
transaction_id: u32,
kind: MessageKind,
request: MessageKind,
payload: Vec<u8>,
trailing: &[u32],
) -> Option<Self> {
let length = u32::try_from(payload.len()).unwrap_or(u32::MAX);
let args = Arguments::new(
[
Field::U32(u32::from(request.0)),
Field::U32(0),
Field::U32(length),
Field::Blob(payload),
]
.into_iter()
.chain(trailing.iter().copied().map(Field::U32)),
)?;
Some(Self {
transaction_id,
kind,
args,
})
}
}
impl fmt::Debug for Message {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:?}(tx={:#x}) {:?}",
self.kind, self.transaction_id, self.args
)
}
}
struct Reader<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Reader<'a> {
fn new(data: &'a [u8]) -> Self {
Self { data, pos: 0 }
}
fn position(&self) -> usize {
self.pos
}
fn take(&mut self, len: usize) -> Result<&'a [u8]> {
let end = self.pos.checked_add(len).ok_or(Error::Truncated {
need: len,
at: self.pos,
have: 0,
})?;
let slice = self.data.get(self.pos..end).ok_or(Error::Truncated {
need: len,
at: self.pos,
have: self.data.len().saturating_sub(self.pos),
})?;
self.pos = end;
Ok(slice)
}
fn u8(&mut self) -> Result<u8> {
Ok(self.take(1)?.first().copied().unwrap_or(0))
}
fn u16(&mut self) -> Result<u16> {
let bytes: [u8; 2] = self.take(2)?.try_into().unwrap_or([0; 2]);
Ok(u16::from_be_bytes(bytes))
}
fn u32(&mut self) -> Result<u32> {
let bytes: [u8; 4] = self.take(4)?.try_into().unwrap_or([0; 4]);
Ok(u32::from_be_bytes(bytes))
}
fn magic(&mut self) -> Result<()> {
let mut wanted = Vec::with_capacity(5);
Field::U32(MAGIC).write(&mut wanted);
if let Some(&first) = self.data.first()
&& first != FieldTag::U32.0
{
return Err(Error::BadMagic {
expected: wanted.as_slice().into(),
got: self.data.get(..1).unwrap_or_default().into(),
});
}
let got = self.take(wanted.len())?;
if got == wanted.as_slice() {
Ok(())
} else {
Err(Error::BadMagic {
expected: wanted.as_slice().into(),
got: got.into(),
})
}
}
fn expect_tag(&mut self, expected: FieldTag, what: &'static str) -> Result<()> {
let at = self.pos;
let tag = FieldTag(self.u8()?);
if tag == expected {
Ok(())
} else {
Err(Error::malformed(
at,
format!("{what} should be tagged {expected:?}, got {tag:?}"),
))
}
}
fn tagged_u8(&mut self, what: &'static str) -> Result<u8> {
self.expect_tag(FieldTag::U8, what)?;
self.u8()
}
fn tagged_u16(&mut self, what: &'static str) -> Result<u16> {
self.expect_tag(FieldTag::U16, what)?;
self.u16()
}
fn tagged_u32(&mut self, what: &'static str) -> Result<u32> {
self.expect_tag(FieldTag::U32, what)?;
self.u32()
}
fn arg_tag_blob(&mut self) -> Result<&'a [u8]> {
let at = self.pos;
self.expect_tag(FieldTag::BLOB, "argument tags")?;
let length = self.u32()?;
if length != u32::try_from(ARG_TAG_BLOB_LEN).unwrap_or(u32::MAX) {
return Err(Error::malformed(
at,
format!("argument-tag blob is {length} bytes, not {ARG_TAG_BLOB_LEN}"),
));
}
self.take(ARG_TAG_BLOB_LEN)
}
fn field(&mut self, arg_tag: ArgTag, index: usize) -> Result<Field> {
let at = self.pos;
let tag = FieldTag(self.u8()?);
if let Some(expected) = arg_tag.field_tag()
&& expected != tag
{
return Err(Error::malformed(
at,
format!("argument {index} is tagged {tag:?} but the header calls it {arg_tag:?}"),
));
}
match tag {
FieldTag::U8 => Ok(Field::U8(self.u8()?)),
FieldTag::U16 => Ok(Field::U16(self.u16()?)),
FieldTag::U32 => Ok(Field::U32(self.u32()?)),
FieldTag::BLOB => {
let length = self.u32()?;
if length > MAX_BLOB_LEN {
return Err(Error::ImplausibleLength {
what: "dbserver binary argument",
length: u64::from(length),
limit: u64::from(MAX_BLOB_LEN),
});
}
let bytes = self.take(usize::try_from(length).unwrap_or(usize::MAX))?;
Ok(Field::Blob(bytes.to_vec()))
}
FieldTag::TEXT => {
let characters = self.u32()?;
if characters > MAX_STRING_CHARS {
return Err(Error::ImplausibleLength {
what: "dbserver string argument",
length: u64::from(characters),
limit: u64::from(MAX_STRING_CHARS),
});
}
let bytes = self.take(usize::try_from(characters * 2).unwrap_or(usize::MAX))?;
let (text, terminator) = decode_string_body(bytes);
Ok(Field::Text { text, terminator })
}
FieldTag(raw) => Err(Error::malformed(
at,
format!("argument {index} has unknown field tag {raw:#04x}"),
)),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ItemType(pub u32);
impl ItemType {
pub const PATH: Self = Self(0x0000);
pub const FOLDER: Self = Self(0x0001);
pub const ALBUM: Self = Self(0x0002);
pub const DISC: Self = Self(0x0003);
pub const TRACK_TITLE: Self = Self(0x0004);
pub const GENRE: Self = Self(0x0006);
pub const ARTIST: Self = Self(0x0007);
pub const PLAYLIST: Self = Self(0x0008);
pub const RATING: Self = Self(0x000a);
pub const DURATION: Self = Self(0x000b);
pub const TEMPO: Self = Self(0x000d);
pub const LABEL: Self = Self(0x000e);
pub const KEY: Self = Self(0x000f);
pub const BITRATE: Self = Self(0x0010);
pub const YEAR: Self = Self(0x0011);
pub const COLOR: Self = Self(0x0013);
pub const COMMENT: Self = Self(0x0023);
pub const HISTORY_PLAYLIST: Self = Self(0x0024);
pub const ORIGINAL_ARTIST: Self = Self(0x0028);
pub const REMIXER: Self = Self(0x0029);
pub const PLAY_COUNT: Self = Self(0x002a);
pub const DATE_ADDED: Self = Self(0x002e);
pub const TRACK_INFO_UNKNOWN: Self = Self(0x002f);
pub const ALL: Self = Self(0x00a0);
pub const SORT_DEFAULT: Self = Self(0x00a1);
pub const SORT_ALPHABET: Self = Self(0x00a2);
pub const MENU_GENRE: Self = Self(0x0080);
pub const MENU_ARTIST: Self = Self(0x0081);
pub const MENU_ALBUM: Self = Self(0x0082);
pub const MENU_TRACK: Self = Self(0x0083);
pub const MENU_PLAYLIST: Self = Self(0x0084);
pub const MENU_BPM: Self = Self(0x0085);
pub const MENU_RATING: Self = Self(0x0086);
pub const MENU_LABEL: Self = Self(0x0089);
pub const MENU_KEY: Self = Self(0x008b);
pub const MENU_DATE_ADDED: Self = Self(0x008c);
pub const MENU_FOLDER: Self = Self(0x0090);
pub const MENU_SEARCH: Self = Self(0x0091);
pub const MENU_BITRATE: Self = Self(0x0093);
pub const MENU_HISTORY: Self = Self(0x0095);
pub const MENU_PLAY_COUNT: Self = Self(0x0097);
#[must_use]
pub const fn masked(self) -> Self {
Self(self.0 & 0xffff)
}
#[must_use]
pub const fn as_track_column(self) -> Self {
Self((self.0 << 8) | 0x04)
}
}
impl fmt::Debug for ItemType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ItemType({:#06x})", self.0)
}
}
pub const MENU_LABEL_PREFIX: char = '\u{fffa}';
pub const MENU_LABEL_SUFFIX: char = '\u{fffb}';
pub fn menu_label(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 6);
out.push(MENU_LABEL_PREFIX);
out.push_str(text);
out.push(MENU_LABEL_SUFFIX);
out
}
pub fn unwrap_menu_label(text: &str) -> Option<&str> {
text.strip_prefix(MENU_LABEL_PREFIX)?
.strip_suffix(MENU_LABEL_SUFFIX)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MenuItem {
pub argument0: u32,
pub id: u32,
pub label1: String,
pub label2: String,
pub item_type: ItemType,
pub flags: u32,
pub artwork_id: u32,
pub playlist_position: u32,
pub key_index: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CamelotKey {
position: u8,
minor: bool,
}
impl CamelotKey {
pub const fn new(position: u8, minor: bool) -> Option<Self> {
if position >= 1 && position <= 12 {
Some(Self { position, minor })
} else {
None
}
}
pub const fn position(self) -> u8 {
self.position
}
pub const fn is_minor(self) -> bool {
self.minor
}
#[expect(
clippy::as_conversions,
reason = "u8 to u32 is lossless, and `position` is 1..=12 by construction"
)]
pub const fn index(self) -> u32 {
let ring = if self.minor { 1 } else { 2 };
(self.position.saturating_sub(1) as u32).saturating_mul(2) + ring
}
pub fn parse(name: &str) -> Option<Self> {
let trimmed = name.trim();
if trimmed.is_empty() {
return None;
}
let digits: String = trimmed.chars().take_while(char::is_ascii_digit).collect();
if !digits.is_empty() {
let rest = trimmed[digits.len()..].trim();
let minor = match rest {
"A" | "a" => true,
"B" | "b" => false,
_ => return Self::classical(trimmed),
};
return digits
.parse()
.ok()
.and_then(|position| Self::new(position, minor));
}
Self::classical(trimmed)
}
fn classical(name: &str) -> Option<Self> {
let key = name.to_ascii_lowercase();
let (position, minor) = match key.as_str() {
"abm" | "g#m" => (1, true),
"b" => (1, false),
"ebm" | "d#m" => (2, true),
"f#" | "gb" => (2, false),
"bbm" | "a#m" => (3, true),
"db" | "c#" => (3, false),
"fm" => (4, true),
"ab" | "g#" => (4, false),
"cm" => (5, true),
"eb" | "d#" => (5, false),
"gm" => (6, true),
"bb" | "a#" => (6, false),
"dm" => (7, true),
"f" => (7, false),
"am" => (8, true),
"c" => (8, false),
"em" => (9, true),
"g" => (9, false),
"bm" => (10, true),
"d" => (10, false),
"f#m" | "gbm" => (11, true),
"a" => (11, false),
"dbm" | "c#m" => (12, true),
"e" => (12, false),
_ => return None,
};
Self::new(position, minor)
}
}
impl MenuItem {
pub const TRACK_FLAGS: u32 = 0x0100_0000;
pub const TAGGED: u32 = 0x0000_0001;
pub const LOADED: u32 = 0x0000_0100;
pub const TRACK_ARGUMENT_10: u32 = 0x0100;
pub fn track(id: u32, title: &str, column: &str, item_type: ItemType, artwork_id: u32) -> Self {
Self {
argument0: 0,
id,
label1: title.to_owned(),
label2: column.to_owned(),
item_type,
flags: Self::TRACK_FLAGS,
artwork_id,
playlist_position: 0,
key_index: 0,
}
}
#[must_use]
pub fn with_key(mut self, key: Option<CamelotKey>) -> Self {
self.key_index = key.map_or(0, CamelotKey::index);
self
}
pub fn category(id: u32, item_type: ItemType, label: &str) -> Self {
Self {
argument0: 0,
id,
label1: menu_label(label),
label2: String::new(),
item_type,
flags: 0,
artwork_id: 0,
playlist_position: 0,
key_index: 0,
}
}
pub fn all() -> Self {
Self::category(FILTER_ALL, ItemType::ALL, "ALL")
}
pub fn named(id: u32, item_type: ItemType, label: &str) -> Self {
Self {
argument0: 0,
id,
label1: label.to_owned(),
label2: String::new(),
item_type,
flags: 0,
artwork_id: 0,
playlist_position: 0,
key_index: 0,
}
}
pub fn argument10(&self) -> u32 {
if self.flags == 0 {
0
} else {
Self::TRACK_ARGUMENT_10
}
}
pub fn to_message(&self, transaction_id: u32) -> Message {
Message::new(
transaction_id,
MessageKind::MENU_ITEM,
[
Field::U32(self.argument0),
Field::U32(self.id),
Field::U32(label_bytes(&self.label1)),
Field::from(self.label1.clone()),
Field::U32(label_bytes(&self.label2)),
Field::from(self.label2.clone()),
Field::U32(self.item_type.0),
Field::U32(self.flags),
Field::U32(self.artwork_id),
Field::U32(self.playlist_position),
Field::U32(self.argument10()),
Field::U32(self.key_index),
],
)
}
pub fn from_message(message: &Message) -> Option<Self> {
if message.kind != MessageKind::MENU_ITEM {
return None;
}
Some(Self {
argument0: message.number(0)?,
id: message.number(1)?,
label1: message.text(3)?.to_owned(),
label2: message.text(5)?.to_owned(),
item_type: ItemType(message.number(6)?),
flags: message.number(7)?,
artwork_id: message.number(8).unwrap_or(0),
playlist_position: message.number(9).unwrap_or(0),
key_index: message.number(11).unwrap_or(0),
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RootCategory {
pub id: u32,
pub item_type: ItemType,
pub label: &'static str,
}
impl RootCategory {
pub fn to_item(self) -> MenuItem {
MenuItem::category(self.id, self.item_type, self.label)
}
}
pub const ROOT_CATEGORIES: [RootCategory; 12] = [
RootCategory {
id: 0x05,
item_type: ItemType::MENU_PLAYLIST,
label: "PLAYLIST",
},
RootCategory {
id: 0x03,
item_type: ItemType::MENU_ALBUM,
label: "ALBUM",
},
RootCategory {
id: 0x01,
item_type: ItemType::MENU_GENRE,
label: "GENRE",
},
RootCategory {
id: 0x0a,
item_type: ItemType::MENU_LABEL,
label: "LABEL",
},
RootCategory {
id: 0x02,
item_type: ItemType::MENU_ARTIST,
label: "ARTIST",
},
RootCategory {
id: 0x14,
item_type: ItemType::MENU_BITRATE,
label: "BITRATE",
},
RootCategory {
id: 0x1b,
item_type: ItemType::MENU_DATE_ADDED,
label: "DATE ADDED",
},
RootCategory {
id: 0x04,
item_type: ItemType::MENU_TRACK,
label: "TRACK",
},
RootCategory {
id: 0x16,
item_type: ItemType::MENU_HISTORY,
label: "HISTORY",
},
RootCategory {
id: 0x12,
item_type: ItemType::MENU_SEARCH,
label: "SEARCH",
},
RootCategory {
id: 0x11,
item_type: ItemType::MENU_FOLDER,
label: "FOLDER",
},
RootCategory {
id: 0x0c,
item_type: ItemType::MENU_KEY,
label: "KEY",
},
];
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SortOrder(pub u32);
impl SortOrder {
pub const DEFAULT: Self = Self(0x00);
pub const TITLE: Self = Self(0x01);
pub const ARTIST: Self = Self(0x02);
pub const ALBUM: Self = Self(0x03);
pub const BPM: Self = Self(0x04);
pub const RATING: Self = Self(0x05);
pub const GENRE: Self = Self(0x06);
pub const COMMENT: Self = Self(0x07);
pub const TIME: Self = Self(0x08);
pub const REMIXER: Self = Self(0x09);
pub const LABEL: Self = Self(0x0a);
pub const ORIGINAL_ARTIST: Self = Self(0x0b);
pub const KEY: Self = Self(0x0c);
pub const BITRATE: Self = Self(0x0d);
pub const PLAY_COUNT: Self = Self(0x10);
pub const DATE_ADDED: Self = Self(0x11);
pub fn column(self) -> Option<ItemType> {
Some(match self {
Self::DEFAULT | Self::TITLE | Self::ARTIST => ItemType::ARTIST,
Self::ALBUM => ItemType::ALBUM,
Self::BPM => ItemType::TEMPO,
Self::RATING => ItemType::RATING,
Self::GENRE => ItemType::GENRE,
Self::LABEL => ItemType::LABEL,
Self::KEY => ItemType::KEY,
Self::BITRATE => ItemType::BITRATE,
Self::PLAY_COUNT => ItemType::PLAY_COUNT,
Self::DATE_ADDED => ItemType::DATE_ADDED,
_ => return None,
})
}
pub fn track_item_type(self) -> ItemType {
self.column().unwrap_or(ItemType::ARTIST).as_track_column()
}
pub fn column_is_numeric(self) -> bool {
matches!(
self,
Self::BPM | Self::RATING | Self::BITRATE | Self::PLAY_COUNT
)
}
}
impl fmt::Debug for SortOrder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match SORT_MENU.iter().find(|entry| entry.sort.0 == self.0) {
Some(entry) => f.write_str(entry.label),
None => write!(f, "SortOrder({:#04x})", self.0),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SortOption {
pub sort: SortOrder,
pub item_type: ItemType,
pub label: &'static str,
}
impl SortOption {
pub fn to_item(self) -> MenuItem {
MenuItem::category(self.sort.0, self.item_type, self.label)
}
}
pub const SORT_MENU: [SortOption; 12] = [
SortOption {
sort: SortOrder::DEFAULT,
item_type: ItemType::SORT_DEFAULT,
label: "DEFAULT",
},
SortOption {
sort: SortOrder::TITLE,
item_type: ItemType::SORT_ALPHABET,
label: "ALPHABET",
},
SortOption {
sort: SortOrder::ARTIST,
item_type: ItemType::MENU_ARTIST,
label: "ARTIST",
},
SortOption {
sort: SortOrder::ALBUM,
item_type: ItemType::MENU_ALBUM,
label: "ALBUM",
},
SortOption {
sort: SortOrder::BPM,
item_type: ItemType::MENU_BPM,
label: "BPM",
},
SortOption {
sort: SortOrder::RATING,
item_type: ItemType::MENU_RATING,
label: "RATING",
},
SortOption {
sort: SortOrder::KEY,
item_type: ItemType::MENU_KEY,
label: "KEY",
},
SortOption {
sort: SortOrder::BITRATE,
item_type: ItemType::MENU_BITRATE,
label: "BITRATE",
},
SortOption {
sort: SortOrder::PLAY_COUNT,
item_type: ItemType::MENU_PLAY_COUNT,
label: "DJ PLAY COUNT",
},
SortOption {
sort: SortOrder::GENRE,
item_type: ItemType::MENU_GENRE,
label: "GENRE",
},
SortOption {
sort: SortOrder::DATE_ADDED,
item_type: ItemType::MENU_DATE_ADDED,
label: "DATE ADDED",
},
SortOption {
sort: SortOrder::LABEL,
item_type: ItemType::MENU_LABEL,
label: "LABEL",
},
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MetadataSlot {
pub item_type: ItemType,
pub argument0: u32,
}
pub const METADATA_ITEMS: [MetadataSlot; 13] = [
MetadataSlot {
item_type: ItemType::TRACK_TITLE,
argument0: 1,
},
MetadataSlot {
item_type: ItemType::ARTIST,
argument0: 1,
},
MetadataSlot {
item_type: ItemType::ALBUM,
argument0: 1,
},
MetadataSlot {
item_type: ItemType::DURATION,
argument0: 0,
},
MetadataSlot {
item_type: ItemType::TEMPO,
argument0: 0,
},
MetadataSlot {
item_type: ItemType::COMMENT,
argument0: 0,
},
MetadataSlot {
item_type: ItemType::KEY,
argument0: 1,
},
MetadataSlot {
item_type: ItemType::RATING,
argument0: 0,
},
MetadataSlot {
item_type: ItemType::COLOR,
argument0: 0,
},
MetadataSlot {
item_type: ItemType::GENRE,
argument0: 1,
},
MetadataSlot {
item_type: ItemType::DATE_ADDED,
argument0: 1,
},
MetadataSlot {
item_type: ItemType::BITRATE,
argument0: 1,
},
MetadataSlot {
item_type: ItemType::LABEL,
argument0: 1,
},
];
pub const TRACK_INFO_ITEMS: [ItemType; 6] = [
ItemType::TRACK_TITLE,
ItemType::DURATION,
ItemType::TEMPO,
ItemType::COMMENT,
ItemType::PATH,
ItemType::TRACK_INFO_UNKNOWN,
];
#[cfg(test)]
mod tests {
use super::*;
fn hex(text: &str) -> Vec<u8> {
assert!(
text.len().is_multiple_of(2),
"hex literal has an odd length"
);
(0..text.len() / 2)
.map(|i| u8::from_str_radix(&text[i * 2..i * 2 + 2], 16).expect("valid hex"))
.collect()
}
fn device(number: u8) -> DeviceNumber {
DeviceNumber::new(number).expect("a non-zero device number")
}
fn browsable(number: u8) -> BrowsableDeviceNumber {
BrowsableDeviceNumber::new(number).expect("a browsable device number")
}
const MENU_CLOSE: &str = "11872349ae11038001b71000010f00140000000c000000000000000000000000";
const INTRODUCE: &str = concat!(
"11872349ae11fffffffe1000000f01140000000c060000000000000000000000",
"1100000001",
);
const INTRODUCE_REPLY: &str = concat!(
"11872349ae11fffffffe1040000f02140000000c060600000000000000000000",
"11000000001100000002",
);
const MENU_ROOT: &str = concat!(
"11872349ae11038001a81010000f03140000000c060606000000000000000000",
"110101030111000000001100ffffff",
);
const ROOT_PLAYLIST_ITEM: &str = concat!(
"11872349ae11038001a91041010f0c140000000c060606020602060606060606",
"110000000011000000051100000016260000000bfffa0050004c00410059004c",
"004900530054fffb000011000000022600000001000011000000841100000000",
"1100000000110000000011000000001100000000",
);
const OMITTED_BLOB: &str = concat!(
"11872349ae110380036c1020040f05140000000c060606060300000000000000",
"1101080301110000000311000000c81100000000",
);
const UNKNOWN_4B02: &str = concat!(
"11872349ae1103800001104b020f04140000000c060606020000000000000000",
"1100003e031100000000110000000226000000010000",
);
const METADATA_TITLE_ITEM: &str = concat!(
"11872349ae110380036e1041010f0c140000000c060606020602060606060606",
"110000000111000000c8110000002c2600000016004c006f006e0065006c0069",
"006e0065007300730020002d0020004b006c0075006200200043007500740000",
"1100000002260000000100001100000004110100000011000000ba1100000000",
"11000001001100000000",
);
const TRACK_INFO_PATH_ITEM: &str = concat!(
"11872349ae110380036b1041010f0c140000000c060606020602060606060606",
"1100747a7b11000000c811000000862600000043002f0043006f006e00740065",
"006e00740073002f0054006f006d00630072006100660074002f004c006f006e",
"0065006c0069006e006500730073002f0054006f006d00630072006100660074",
"0020002d0020004c006f006e0065006c0069006e0065007300730020002d0020",
"004b006c007500620020004300750074002e006d007000330000110000000226",
"0000000100001100000000110000000011000000001100000000110000000011",
"00000000",
);
const BINARY_REPLY: &str = concat!(
"11872349ae11038008b11049020f04140000000c060606030000000000000000",
"1100003903110000000011000000941400000094530041004d00320000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000032003000320035002d003000",
"36002d0032003400000000003100300030003000000000000000000000000000",
"000000000000000000000000b40200000000010123000000070000000080ca28",
"0500000000c0007d",
);
const SEARCH: &str = concat!(
"11872349ae11038008171013000f05140000000c060606020600000000000000",
"1102010301110000000011000000042600000002004800001100000000",
);
const STALE_TERMINATOR: &str = concat!(
"11872349ae11038003691041010f0c140000000c060606020602060606060606",
"110000000011000000c8110000000226000000010009110000000226000000",
"0100091100000004110100000011000000001100000000110000010011000000",
"00",
);
const CAPTURED: &[(&str, &str)] = &[
("menu_close", MENU_CLOSE),
("introduce", INTRODUCE),
("introduce_reply", INTRODUCE_REPLY),
("menu_root", MENU_ROOT),
("root_playlist_item", ROOT_PLAYLIST_ITEM),
("omitted_blob", OMITTED_BLOB),
("unknown_4b02", UNKNOWN_4B02),
("metadata_title_item", METADATA_TITLE_ITEM),
("track_info_path_item", TRACK_INFO_PATH_ITEM),
("binary_reply", BINARY_REPLY),
("search", SEARCH),
("stale_terminator", STALE_TERMINATOR),
];
#[test]
fn every_captured_message_round_trips_byte_for_byte() {
assert!(CAPTURED.len() >= 12, "the fixture floor has shrunk");
for (name, text) in CAPTURED {
let raw = hex(text);
let (message, consumed) =
Message::decode(&raw).unwrap_or_else(|err| panic!("{name}: {err}"));
assert_eq!(consumed, raw.len(), "{name}: consumed the whole message");
assert_eq!(
message.encode(),
raw,
"{name} re-encoded differently:\n {message:?}"
);
}
}
#[test]
fn a_zero_length_blob_is_omitted_from_the_wire() {
let raw = hex(OMITTED_BLOB);
let (message, consumed) = Message::decode(&raw).unwrap();
assert_eq!(consumed, raw.len());
assert_eq!(message.kind, MessageKind::GET_WAVEFORM_PREVIEW);
assert_eq!(raw[14], 5);
assert_eq!(message.args.len(), 5);
assert_eq!(message.number(3), Some(0));
assert_eq!(message.blob(4), Some(&[][..]));
assert_eq!(raw.len(), 32 + 4 * 5);
assert_eq!(message.encode(), raw);
}
#[test]
fn an_empty_string_is_present_where_an_empty_blob_would_not_be() {
let raw = hex(UNKNOWN_4B02);
let (message, _) = Message::decode(&raw).unwrap();
assert_eq!(message.text(3), Some(""));
assert!(
raw.ends_with(&[0x26, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]),
"the empty string is written out in full"
);
}
#[test]
fn an_empty_blob_is_written_when_its_absence_could_not_be_inferred() {
let message = Message::new(
1,
MessageKind::ARTWORK,
[Field::U32(7), Field::Blob(Vec::new())],
);
let raw = message.encode();
let (decoded, consumed) = Message::decode(&raw).unwrap();
assert_eq!(consumed, raw.len());
assert_eq!(decoded, message);
assert!(raw.ends_with(&[FieldTag::BLOB.0, 0, 0, 0, 0]));
}
#[test]
fn an_omitted_blob_counts_as_one_for_the_argument_after_it() {
let message = Message::new(
1,
MessageKind::CUE_POINTS,
[
Field::U32(0),
Field::Blob(Vec::new()),
Field::Blob(Vec::new()),
],
);
let raw = message.encode();
let (decoded, _) = Message::decode(&raw).unwrap();
assert_eq!(decoded, message);
assert_eq!(raw.len(), 32 + 5 + 5);
}
#[test]
fn a_truncated_message_is_distinguishable_from_a_malformed_one() {
let raw = hex(ROOT_PLAYLIST_ITEM);
for cut in 1..raw.len() {
let err = Message::decode(&raw[..cut]).expect_err("must not decode");
assert!(
err.is_truncated(),
"cutting at {cut} should mean 'wait for more', got {err}"
);
}
assert!(Message::decode(&raw).is_ok());
}
#[test]
fn a_bad_magic_is_not_truncation() {
let mut raw = hex(INTRODUCE);
raw[2] = 0x00;
let err = Message::decode(&raw).expect_err("must not decode");
assert!(matches!(err, Error::BadMagic { .. }));
assert!(!err.is_truncated(), "more bytes will not help");
let err = Message::decode(b"GET / HTTP/1.1\r\n").expect_err("must not decode");
assert!(matches!(err, Error::BadMagic { .. }));
assert!(!err.is_truncated());
}
#[test]
fn an_implausible_length_is_refused_before_allocating() {
let mut raw = hex(INTRODUCE);
raw[20] = ArgTag::BLOB.0;
raw.truncate(32);
raw.extend_from_slice(&[FieldTag::BLOB.0, 0xc0, 0x00, 0x00, 0x00]);
let err = Message::decode(&raw).expect_err("must not decode");
assert!(matches!(err, Error::ImplausibleLength { .. }));
assert!(!err.is_truncated());
}
#[test]
fn the_two_numberings_must_agree() {
let mut raw = hex(INTRODUCE);
raw[20] = ArgTag::TEXT.0;
let err = Message::decode(&raw).expect_err("must not decode");
assert!(matches!(err, Error::Malformed { .. }), "got {err}");
}
#[test]
fn the_tag_blob_is_derived_from_the_arguments_not_stored() {
let message = Message::new(
1,
MessageKind::ARTWORK,
[
Field::U32(0x2003),
Field::U32(0),
Field::U32(3),
Field::Blob(vec![1, 2, 3]),
Field::from("x"),
],
);
let raw = message.encode();
assert_eq!(
&raw[20..32],
&[
ArgTag::U32.0,
ArgTag::U32.0,
ArgTag::U32.0,
ArgTag::BLOB.0,
ArgTag::TEXT.0,
0,
0,
0,
0,
0,
0,
0
],
"one tag per argument, zeroes after"
);
assert_eq!(raw[14], 5, "the count is derived too");
}
#[test]
fn more_than_twelve_arguments_cannot_be_built_or_decoded() {
assert!(Arguments::new((0..13).map(Field::U32)).is_none());
assert!(Arguments::new((0..12).map(Field::U32)).is_some());
let mut raw = hex(INTRODUCE);
raw[14] = 13;
let err = Message::decode(&raw).expect_err("must not decode");
assert!(matches!(err, Error::Malformed { .. }), "got {err}");
}
#[test]
fn a_camelot_key_indexes_the_wheel_the_way_a_real_deck_does() {
for (name, expected) in [
("1A", 1),
("1B", 2),
("2A", 3),
("2B", 4),
("3A", 5),
("3B", 6),
("4A", 7),
("4B", 8),
("5A", 9),
("5B", 10),
("6A", 11),
("6B", 12),
("7A", 13),
("7B", 14),
("8A", 15),
("8B", 16),
("9A", 17),
("9B", 18),
("10A", 19),
("11A", 21),
("11B", 22),
("12A", 23),
("12B", 24),
] {
let key = CamelotKey::parse(name).unwrap_or_else(|| panic!("{name} must parse"));
assert_eq!(key.index(), expected, "{name}");
}
}
#[test]
fn the_classical_names_rekordbox_writes_land_on_the_same_wheel() {
for (classical, camelot) in [
("Am", "8A"),
("C", "8B"),
("F#m", "11A"),
("A", "11B"),
("Abm", "1A"),
("B", "1B"),
("Dbm", "12A"),
("E", "12B"),
("G#m", "1A"),
("Gb", "2B"),
] {
assert_eq!(
CamelotKey::parse(classical).map(CamelotKey::index),
CamelotKey::parse(camelot).map(CamelotKey::index),
"{classical} should be {camelot}",
);
}
}
#[test]
fn a_track_with_no_key_gets_no_indicator_rather_than_a_wrong_one() {
assert_eq!(CamelotKey::parse(""), None);
assert_eq!(CamelotKey::parse(" "), None);
assert_eq!(CamelotKey::parse("13A"), None, "off the wheel");
assert_eq!(CamelotKey::parse("0A"), None);
assert_eq!(CamelotKey::parse("nonsense"), None);
assert_eq!(
MenuItem::track(1, "t", "", ItemType::TRACK_TITLE, 0)
.with_key(None)
.key_index,
0
);
}
#[test]
fn a_media_info_body_matches_the_one_a_real_deck_sent() {
let raw = hex(BINARY_REPLY);
let (message, _) = Message::decode(&raw).unwrap();
assert_eq!(message.kind, MessageKind::MEDIA_INFO);
let body = message.blob(3).expect("the 148-byte body");
let parsed = MediaInfo::parse(body).expect("it parses");
assert_eq!(
parsed.volume_name, "SAM2",
"UTF-16 *little*-endian, unlike every other string here"
);
assert_eq!(parsed.created, "2025-06-24");
assert_eq!(parsed.track_count, 692);
assert_eq!(parsed.playlist_count, 35);
assert_eq!(parsed.total_bytes, 0x0000_0007_28ca_8000);
assert_eq!(parsed.free_bytes, 0x0000_0005_7d00_c000);
assert_eq!(parsed.encode(), body, "we must send what a deck sends");
}
#[test]
fn a_media_info_body_says_a_small_mediums_size_with_zero_high_words() {
let info = MediaInfo {
volume_name: "PLAINMP3".to_owned(),
created: String::new(),
track_count: 0,
playlist_count: 0,
total_bytes: 64_000_000,
free_bytes: 0x1_0000_0001,
plain: true,
};
let body = info.encode();
assert_eq!(
&body[0x7c..0x80],
&[0, 0, 2, 0],
"the UDP reply's 0xa8 bytes"
);
assert!(body[0x58..0x60].iter().all(|&byte| byte == 0), "no `1000`");
assert_eq!(&body[0x84..0x8c], &[0, 0, 0, 0, 0x00, 0x90, 0xd0, 0x03]);
assert_eq!(&body[0x8c..0x94], &[1, 0, 0, 0, 1, 0, 0, 0]);
assert_eq!(MediaInfo::parse(&body), Some(info));
}
#[test]
fn an_unknown_message_type_decodes_instead_of_failing() {
let mut raw = hex(BINARY_REPLY);
raw[11] = 0x7f;
raw[12] = 0x7f;
let (message, _) = Message::decode(&raw).unwrap();
assert_eq!(message.kind, MessageKind(0x7f7f));
assert_eq!(message.kind.name(), None);
assert_eq!(message.blob(3).map(<[u8]>::len), Some(148));
assert_eq!(message.encode(), raw, "and survives a round trip");
}
#[test]
fn two_messages_decode_one_after_the_other() {
let mut stream = PREAMBLE.to_vec();
stream.extend_from_slice(&hex(INTRODUCE));
stream.extend_from_slice(&hex(MENU_ROOT));
let body = skip_preamble(&stream);
assert_eq!(body.len(), stream.len() - PREAMBLE.len());
let (first, used) = Message::decode(body).unwrap();
assert_eq!(first.kind, MessageKind::INTRODUCE);
let (second, used2) = Message::decode(&body[used..]).unwrap();
assert_eq!(second.kind, MessageKind::MENU_ROOT);
assert_eq!(used + used2, body.len(), "nothing left over");
}
#[test]
fn skipping_the_preamble_leaves_a_stream_without_one_alone() {
let raw = hex(INTRODUCE);
assert_eq!(skip_preamble(&raw), raw.as_slice());
assert_eq!(skip_preamble(&PREAMBLE), &[] as &[u8]);
}
#[test]
fn a_string_length_counts_characters_including_the_nul_not_bytes() {
let encoded = encode_string("abc");
assert_eq!(
&encoded[..4],
4u32.to_be_bytes(),
"three characters plus the NUL"
);
assert_eq!(encoded.len(), 4 + 8);
assert_eq!(string_characters("abc"), 4);
assert_eq!(label_bytes("abc"), 8);
assert_eq!(label_bytes(""), 2);
}
#[test]
fn a_string_is_utf16_big_endian_not_little() {
assert_eq!(encode_string("A"), [0, 0, 0, 2, 0x00, b'A', 0x00, 0x00]);
}
#[test]
fn a_terminator_that_is_not_a_nul_is_reproduced_rather_than_normalised() {
let raw = hex(STALE_TERMINATOR);
let (message, _) = Message::decode(&raw).unwrap();
assert_eq!(message.number(2), Some(2), "the label is empty (2 bytes)");
assert_eq!(message.text(3), Some(""), "and reads as empty");
assert_eq!(
message.args.get(3),
Some(&Field::Text {
text: String::new(),
terminator: Some(0x0009),
})
);
assert_eq!(message.encode(), raw);
assert_eq!(
Field::from(""),
Field::Text {
text: String::new(),
terminator: Some(NUL),
}
);
}
#[test]
fn a_label_length_counts_utf16_units_not_code_points() {
let wrapped = menu_label("PLAYLIST");
assert_eq!(wrapped.chars().count(), 10);
assert_eq!(label_bytes(&wrapped), 0x16);
assert_eq!("\u{1f3b5}".chars().count(), 1);
assert_eq!(string_characters("\u{1f3b5}"), 3);
assert_eq!(encode_string("\u{1f3b5}").len(), 4 + 6);
}
#[test]
fn a_non_ascii_string_survives_a_round_trip() {
for text in ["", "Blue Monday", "夜のテーマ", "\u{1f3b5} track"] {
let message = Message::new(1, MessageKind::MENU_ITEM, [Field::from(text)]);
let (decoded, _) = Message::decode(&message.encode()).unwrap();
assert_eq!(decoded.text(0), Some(text));
}
}
#[test]
fn the_captured_playlist_row_carries_the_label_wrapping() {
let raw = hex(ROOT_PLAYLIST_ITEM);
let (message, _) = Message::decode(&raw).unwrap();
let item = MenuItem::from_message(&message).expect("a menu item");
assert_eq!(item.label1, "\u{fffa}PLAYLIST\u{fffb}");
assert_eq!(unwrap_menu_label(&item.label1), Some("PLAYLIST"));
assert_eq!(item.id, 0x05);
assert_eq!(item.item_type, ItemType::MENU_PLAYLIST);
assert_eq!(item.flags, 0, "a category row carries no flags (F26)");
assert_eq!(message.number(2), Some(0x16), "label length in bytes");
assert_eq!(item.to_message(message.transaction_id).encode(), raw);
}
#[test]
fn a_descriptor_packs_device_menu_slot_and_track_type() {
let descriptor = Descriptor::new(
browsable(3),
Slot::USB,
MenuTarget::MAIN,
TrackType::REKORDBOX,
);
assert_eq!(descriptor.to_raw(), 0x0301_0301);
assert_eq!(Descriptor::parse(0x0301_0301), Some(descriptor));
assert_eq!(
Descriptor::new(
browsable(2),
Slot::SD,
MenuTarget::MAIN,
TrackType::REKORDBOX
)
.to_raw(),
0x0201_0201
);
assert_eq!(Descriptor::parse(0), None, "device 0 answers nothing");
}
#[test]
fn the_captured_root_request_names_a_usb_slot_on_device_one() {
let (message, _) = Message::decode(&hex(MENU_ROOT)).unwrap();
let descriptor = message.descriptor().expect("a descriptor");
assert_eq!(descriptor.device, device(1));
assert_eq!(descriptor.menu, MenuTarget::MAIN);
assert_eq!(descriptor.slot, Slot::USB);
assert_eq!(descriptor.track_type, TrackType::REKORDBOX);
}
#[test]
fn the_slot_byte_is_what_separates_two_media_on_one_connection() {
let sd = Descriptor::new(
browsable(2),
Slot::SD,
MenuTarget::MAIN,
TrackType::REKORDBOX,
);
let usb = Descriptor {
slot: Slot::USB,
..sd
};
assert_ne!(sd.to_raw(), usb.to_raw());
assert_eq!(sd.to_raw() ^ usb.to_raw(), 0x0000_0100);
}
#[test]
fn every_observed_drill_type_comes_from_the_one_formula() {
const OBSERVED: [(u16, u8, u8); 13] = [
(0x1101, 1, 0x01),
(0x1102, 1, 0x02),
(0x1103, 1, 0x03),
(0x110a, 1, 0x0a),
(0x1111, 1, 0x11),
(0x1112, 1, 0x12),
(0x1114, 1, 0x14),
(0x1201, 2, 0x01),
(0x1202, 2, 0x02),
(0x120a, 2, 0x0a),
(0x1214, 2, 0x14),
(0x1301, 3, 0x01),
(0x130a, 3, 0x0a),
];
for (raw, depth, category) in OBSERVED {
let drill = Drill { depth, category };
assert_eq!(drill.kind(), MessageKind(raw));
assert_eq!(Drill::parse(MessageKind(raw)), Some(drill));
}
assert_eq!(drill_kind(1, 0x01), MessageKind(0x1101)); assert_eq!(drill_kind(1, 0x02), MessageKind(0x1102)); assert_eq!(drill_kind(1, 0x03), MessageKind(0x1103)); }
#[test]
fn a_flat_menu_is_not_a_drill() {
assert_eq!(Drill::parse(MessageKind::MENU_KEY), None);
assert_eq!(Drill::parse(MessageKind::MENU_ROOT), None);
assert_eq!(Drill::parse(MessageKind::GET_METADATA), None);
assert_eq!(
Drill::parse(MessageKind::MENU_PLAYLIST),
Some(Drill {
depth: 1,
category: 0x05
})
);
}
#[test]
fn the_drill_category_and_the_root_id_are_different_numberings() {
let key_request = MessageKind::MENU_KEY.0 & 0xff;
assert_eq!(key_request, 0x14);
let key_root = ROOT_CATEGORIES
.iter()
.find(|category| category.label == "KEY")
.expect("KEY is a root category");
assert_eq!(key_root.id, 0x0c);
let bitrate_root = ROOT_CATEGORIES
.iter()
.find(|category| category.label == "BITRATE")
.expect("BITRATE is a root category");
assert_eq!(bitrate_root.id, u32::from(key_request));
}
#[test]
fn all_twelve_root_categories_are_listed_not_derived() {
assert_eq!(ROOT_CATEGORIES.len(), 12);
let exceptions: Vec<&str> = ROOT_CATEGORIES
.iter()
.filter(|category| category.item_type.0 - category.id != 0x7f)
.map(|category| category.label)
.collect();
assert_eq!(exceptions, ["DATE ADDED"]);
let date_added = ROOT_CATEGORIES
.iter()
.find(|category| category.label == "DATE ADDED")
.expect("DATE ADDED is a root category");
assert_eq!((date_added.id, date_added.item_type.0), (0x1b, 0x8c));
let ids: Vec<u32> = ROOT_CATEGORIES.iter().map(|entry| entry.id).collect();
let mut sorted = ids.clone();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(sorted.len(), ids.len(), "no two categories share an id");
}
#[test]
fn a_root_category_row_matches_a_real_player() {
let playlist = ROOT_CATEGORIES
.iter()
.find(|category| category.label == "PLAYLIST")
.expect("PLAYLIST is a root category");
let raw = hex(ROOT_PLAYLIST_ITEM);
let (captured, _) = Message::decode(&raw).unwrap();
assert_eq!(
playlist
.to_item()
.to_message(captured.transaction_id)
.encode(),
raw,
"byte-identical to the deck's own row"
);
}
#[test]
fn the_sort_menu_is_the_twelve_a_real_player_lists() {
assert_eq!(SORT_MENU.len(), 12);
let ids: Vec<u32> = SORT_MENU.iter().map(|option| option.sort.0).collect();
assert_eq!(
ids,
[0, 1, 2, 3, 4, 5, 0x0c, 0x0d, 0x10, 6, 0x11, 0x0a],
"the order a CDJ-2000NXS serves them in"
);
let types: Vec<u32> = SORT_MENU.iter().map(|option| option.item_type.0).collect();
assert_eq!(
types,
[
0xa1, 0xa2, 0x81, 0x82, 0x85, 0x86, 0x8b, 0x93, 0x97, 0x80, 0x8c, 0x89
]
);
}
#[test]
fn the_sort_order_selects_the_second_column() {
for (sort, item_type) in [
(SortOrder::DEFAULT, 0x0704),
(SortOrder::TITLE, 0x0704),
(SortOrder::ARTIST, 0x0704),
(SortOrder::ALBUM, 0x0204),
(SortOrder::BPM, 0x0d04),
(SortOrder::RATING, 0x0a04),
(SortOrder::GENRE, 0x0604),
(SortOrder::LABEL, 0x0e04),
(SortOrder::KEY, 0x0f04),
(SortOrder::BITRATE, 0x1004),
(SortOrder::PLAY_COUNT, 0x2a04),
(SortOrder::DATE_ADDED, 0x2e04),
] {
assert_eq!(
sort.track_item_type(),
ItemType(item_type),
"second column for {sort:?}"
);
}
assert!(SortOrder::BPM.column_is_numeric());
assert!(SortOrder::BITRATE.column_is_numeric());
assert!(!SortOrder::ARTIST.column_is_numeric());
assert!(!SortOrder::DATE_ADDED.column_is_numeric());
assert_eq!(SortOrder(0x7f).column(), None);
assert_eq!(SortOrder(0x7f).track_item_type(), ItemType(0x0704));
}
#[test]
fn a_metadata_reply_is_thirteen_items_in_a_fixed_order() {
assert_eq!(METADATA_ITEMS.len(), 13);
let types: Vec<u32> = METADATA_ITEMS.iter().map(|slot| slot.item_type.0).collect();
assert_eq!(
types,
[
0x04, 0x07, 0x02, 0x0b, 0x0d, 0x23, 0x0f, 0x0a, 0x13, 0x06, 0x2e, 0x10, 0x0e
],
"title, artist, album, duration, tempo, comment, key, rating, \
colour, genre, date added, bitrate, label"
);
let ones = METADATA_ITEMS
.iter()
.filter(|slot| slot.argument0 == 1)
.count();
assert_eq!(ones, 8);
assert_eq!(METADATA_ITEMS.len() - ones, 5);
}
#[test]
fn the_metadata_title_item_matches_a_real_deck() {
let raw = hex(METADATA_TITLE_ITEM);
let (message, _) = Message::decode(&raw).unwrap();
let item = MenuItem::from_message(&message).expect("a menu item");
assert_eq!(item.item_type, ItemType::TRACK_TITLE);
assert_eq!(item.label1, "Loneliness - Klub Cut");
assert_eq!(item.flags, MenuItem::TRACK_FLAGS);
assert_eq!(item.artwork_id, 0xba, "without this, INFO shows no cover");
assert_eq!(message.number(10), Some(MenuItem::TRACK_ARGUMENT_10));
assert_eq!(item.argument10(), MenuItem::TRACK_ARGUMENT_10);
assert_eq!(item.argument0, METADATA_ITEMS[0].argument0);
let mut rebuilt = MenuItem::track(
item.id,
&item.label1,
&item.label2,
ItemType::TRACK_TITLE,
0xba,
);
rebuilt.argument0 = 1;
assert_eq!(
rebuilt.to_message(message.transaction_id).encode(),
raw,
"a rebuilt row is byte-identical"
);
}
#[test]
fn argument_ten_is_zero_exactly_when_the_flags_are() {
let mut item = MenuItem::named(1, ItemType::ARTIST, "Tomcraft");
assert_eq!(item.flags, 0);
assert_eq!(item.argument10(), 0);
item.flags = MenuItem::TRACK_FLAGS;
assert_eq!(item.argument10(), MenuItem::TRACK_ARGUMENT_10);
}
#[test]
fn a_track_info_reply_is_six_items_and_argument_zero_is_the_file_size() {
assert_eq!(TRACK_INFO_ITEMS.len(), 6);
let types: Vec<u32> = TRACK_INFO_ITEMS.iter().map(|item| item.0).collect();
assert_eq!(types, [0x04, 0x0b, 0x0d, 0x23, 0x00, 0x2f]);
let raw = hex(TRACK_INFO_PATH_ITEM);
let (message, _) = Message::decode(&raw).unwrap();
let item = MenuItem::from_message(&message).expect("a menu item");
assert_eq!(item.item_type, ItemType::PATH);
assert_eq!(
item.argument0, 0x0074_7a7b,
"argument 0 is the file size, not padding (F31)"
);
assert_eq!(item.argument0, 7_633_531);
assert!(item.label1.ends_with("Klub Cut.mp3"));
assert_eq!(item.flags, 0, "track-info rows carry no flags");
assert_eq!(item.to_message(message.transaction_id).encode(), raw);
}
#[test]
fn the_same_item_type_means_different_things_in_different_replies() {
assert_eq!(METADATA_ITEMS[0].item_type, ItemType::TRACK_TITLE);
assert_eq!(TRACK_INFO_ITEMS[0], ItemType::TRACK_TITLE);
}
#[test]
fn a_cdj_3000_item_type_masks_down_to_a_known_one() {
assert_eq!(ItemType(0x0100_0004).masked(), ItemType::TRACK_TITLE);
}
#[test]
fn a_built_introduce_matches_a_real_one() {
assert_eq!(Message::introduce(browsable(1)).encode(), hex(INTRODUCE));
assert_eq!(
Message::introduce_reply(device(2)).encode(),
hex(INTRODUCE_REPLY)
);
}
#[test]
fn a_built_menu_close_matches_a_real_one() {
let message = Message::new(0x0380_01b7, MessageKind::MENU_CLOSE, []);
assert_eq!(message.encode(), hex(MENU_CLOSE));
assert!(message.kind.expects_no_reply());
assert!(!MessageKind::MENU_ROOT.expects_no_reply());
}
#[test]
fn a_built_unknown_3e03_reply_matches_a_real_one() {
assert_eq!(
Message::unknown_3e03_reply(0x0380_0001, device(2)).encode(),
hex(UNKNOWN_4B02)
);
}
#[test]
fn a_binary_reply_with_no_payload_is_the_same_shape_as_one_with() {
let request = MessageKind::GET_ARTWORK;
let empty =
Message::binary_reply(1, MessageKind::ARTWORK, request, Vec::new(), &[]).unwrap();
assert_eq!(empty.args.len(), 4);
assert_eq!(empty.number(2), Some(0));
assert_eq!(empty.encode().len(), 32 + 3 * 5);
let full =
Message::binary_reply(1, MessageKind::ARTWORK, request, vec![9; 10], &[]).unwrap();
assert_eq!(full.number(2), Some(10));
assert_eq!(full.encode().len(), 32 + 3 * 5 + 5 + 10);
for message in [empty, full] {
let (decoded, _) = Message::decode(&message.encode()).unwrap();
assert_eq!(decoded, message);
}
}
#[test]
fn a_render_names_the_result_set_by_descriptor_and_total() {
let descriptor = Descriptor::new(
browsable(2),
Slot::USB,
MenuTarget::SUB,
TrackType::REKORDBOX,
);
let render = Message::render_of(0x0380_0003, descriptor, 20, 6, 692);
assert_eq!(render.args.len(), 6);
assert_eq!(render.descriptor(), Some(descriptor));
assert_eq!(render.number(1), Some(20));
assert_eq!(render.number(2), Some(6));
assert_eq!(render.number(4), Some(692));
let (decoded, _) = Message::decode(&render.encode()).unwrap();
assert_eq!(decoded, render);
let simple = Message::render(1, descriptor, 0, 10);
assert_eq!(simple.number(2), simple.number(4));
}
#[test]
fn a_search_puts_the_term_in_argument_three() {
let raw = hex(SEARCH);
let (captured, _) = Message::decode(&raw).unwrap();
let descriptor = captured.descriptor().expect("a descriptor");
let search = Message::search(captured.transaction_id, descriptor, SortOrder::DEFAULT, "H");
assert_eq!(search.number(2), Some(4));
assert_eq!(search.text(3), Some("H"));
assert_eq!(search.number(4), Some(0));
assert_eq!(search.encode(), raw, "byte for byte a real deck's request");
}
#[test]
fn a_menu_request_refuses_to_overflow_the_tag_blob() {
let descriptor = Descriptor::new(
browsable(1),
Slot::SD,
MenuTarget::MAIN,
TrackType::REKORDBOX,
);
assert!(Message::menu_request(1, MessageKind::MENU_TRACK, descriptor, &[0; 11]).is_some());
assert!(Message::menu_request(1, MessageKind::MENU_TRACK, descriptor, &[0; 12]).is_none());
}
#[test]
fn the_all_row_heads_a_filtered_list() {
let item = MenuItem::all();
assert_eq!(item.id, FILTER_ALL);
assert_eq!(item.item_type, ItemType::ALL);
assert_eq!(item.label1, "\u{fffa}ALL\u{fffb}");
assert_eq!(item.flags, 0);
}
#[test]
fn the_header_footer_and_success_replies_have_the_shapes_a_deck_sends() {
let header = Message::menu_header(1);
assert_eq!(header.number(0), Some(1));
assert_eq!(header.number(1), Some(0));
assert!(Message::menu_footer(1).args.is_empty());
let success = Message::success(1, MessageKind::MENU_ROOT, 12);
assert_eq!(success.number(0), Some(0x1000));
assert_eq!(success.number(1), Some(12));
assert_eq!(
Message::disconnect().transaction_id,
SETUP_TRANSACTION_ID,
"introduce and disconnect share the reserved id"
);
}
#[test]
fn the_port_query_is_the_documented_nineteen_bytes() {
assert_eq!(PORT_QUERY.len(), 19);
assert_eq!(&PORT_QUERY[..4], 15u32.to_be_bytes());
assert_eq!(&PORT_QUERY[4..18], b"RemoteDBServer");
assert_eq!(PORT_QUERY[18], 0);
assert_eq!(decode_port_reply(&encode_port_reply(PORT)).unwrap(), 1051);
assert!(decode_port_reply(&[0x04]).unwrap_err().is_truncated());
}
#[test]
fn the_preamble_is_a_uint32_field_holding_one() {
assert_eq!(PREAMBLE, [0x11, 0x00, 0x00, 0x00, 0x01]);
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MediaInfo {
pub volume_name: String,
pub created: String,
pub track_count: u32,
pub playlist_count: u32,
pub total_bytes: u64,
pub free_bytes: u64,
pub plain: bool,
}
impl MediaInfo {
pub const LEN: usize = 148;
const OFF_VOLUME: usize = 0x00;
const LEN_VOLUME: usize = 0x40;
const OFF_CREATED: usize = 0x40;
const LEN_CREATED: usize = 0x18;
const OFF_UNKNOWN_TEXT: usize = 0x58;
const OFF_TRACKS: usize = 0x78;
const OFF_PLAYLISTS: usize = 0x80;
const OFF_TOTAL: usize = 0x84;
const OFF_FREE: usize = 0x8c;
pub fn encode(&self) -> Vec<u8> {
let mut body = vec![0u8; Self::LEN];
put_utf16le(
&mut body,
Self::OFF_VOLUME,
Self::LEN_VOLUME,
&self.volume_name,
);
put_utf16le(
&mut body,
Self::OFF_CREATED,
Self::LEN_CREATED,
&self.created,
);
put_u32le(&mut body, Self::OFF_TRACKS, self.track_count);
if self.plain {
put_u32le(&mut body, Self::OFF_TRACKS + 4, 0x0002_0000);
} else {
put_utf16le(&mut body, Self::OFF_UNKNOWN_TEXT, 8, "1000");
put_u32le(&mut body, Self::OFF_TRACKS + 4, 0x0101_0000);
}
put_u32le(&mut body, Self::OFF_PLAYLISTS, self.playlist_count);
put_u64_as_words(&mut body, Self::OFF_TOTAL, self.total_bytes);
put_u64_as_words(&mut body, Self::OFF_FREE, self.free_bytes);
body
}
pub fn parse(body: &[u8]) -> Option<Self> {
if body.len() < Self::LEN {
return None;
}
Some(Self {
volume_name: utf16le(body, Self::OFF_VOLUME, Self::LEN_VOLUME),
created: utf16le(body, Self::OFF_CREATED, Self::LEN_CREATED),
track_count: u32le(body, Self::OFF_TRACKS),
playlist_count: u32le(body, Self::OFF_PLAYLISTS),
total_bytes: u64_from_words(body, Self::OFF_TOTAL),
free_bytes: u64_from_words(body, Self::OFF_FREE),
plain: body.get(Self::OFF_TRACKS + 6) == Some(&2),
})
}
}
fn put_u64_as_words(out: &mut [u8], offset: usize, value: u64) {
let high = u32::try_from(value >> 32).unwrap_or(u32::MAX);
let low = u32::try_from(value & u64::from(u32::MAX)).unwrap_or(u32::MAX);
put_u32le(out, offset, high);
put_u32le(out, offset.saturating_add(4), low);
}
fn u64_from_words(body: &[u8], offset: usize) -> u64 {
(u64::from(u32le(body, offset)) << 32) | u64::from(u32le(body, offset.saturating_add(4)))
}
fn put_utf16le(out: &mut [u8], offset: usize, width: usize, text: &str) {
let Some(field) = out.get_mut(offset..offset.saturating_add(width)) else {
return;
};
for (pair, unit) in field.chunks_exact_mut(2).zip(text.encode_utf16()) {
pair.copy_from_slice(&unit.to_le_bytes());
}
}
fn put_u32le(out: &mut [u8], offset: usize, value: u32) {
if let Some(field) = out.get_mut(offset..offset.saturating_add(4)) {
field.copy_from_slice(&value.to_le_bytes());
}
}
fn utf16le(body: &[u8], offset: usize, width: usize) -> String {
let Some(field) = body.get(offset..offset.saturating_add(width)) else {
return String::new();
};
let units: Vec<u16> = field
.chunks_exact(2)
.filter_map(|pair| <[u8; 2]>::try_from(pair).ok())
.map(u16::from_le_bytes)
.take_while(|&unit| unit != 0)
.collect();
String::from_utf16_lossy(&units)
}
fn u32le(body: &[u8], offset: usize) -> u32 {
body.get(offset..offset.saturating_add(4))
.and_then(|field| <[u8; 4]>::try_from(field).ok())
.map_or(0, u32::from_le_bytes)
}