prolink_proto/lib.rs
1// Copyright (C) 2026 the prolink authors.
2//
3// This program is free software: you can redistribute it and/or modify it under
4// the terms of the GNU General Public License as published by the Free Software
5// Foundation, version 3.
6//
7// SPDX-License-Identifier: GPL-3.0-only
8
9//! Wire codecs for the Pioneer Pro DJ Link protocol.
10//!
11//! Pure encoding and decoding: no sockets, no filesystem, no clock. Everything
12//! here is a function from bytes to values and back, so the whole protocol
13//! surface is testable against captured traffic without a network — which is
14//! how it is tested, against 33 pcapng captures of two CDJ-2000NXS running
15//! firmware 1.44.
16//!
17//! # The four wire formats
18//!
19//! | Module | Transport | Carries |
20//! |---|---|---|
21//! | [`djl`] | UDP 50000, broadcast | Discovery, device-number claiming, keep-alive |
22//! | [`status`] | UDP 50002, unicast | Player status, media queries, device settings |
23//! | [`dbserver`] | TCP 1051 | The metadata protocol the LINK button drives |
24//! | [`rpc`] | UDP 111 / 2049 / 48276 | ONC RPC v2, the portmapper, MOUNT and NFSv2 |
25//!
26//! [`analysis`] is not a wire format but a set of transforms: rekordbox writes
27//! a track's analysis one way and dbserver puts it on the wire another, and
28//! three of the five blobs change layout in between.
29//!
30//! # Endianness is not uniform, and that is the point
31//!
32//! Two conventions coexist and they are opposites:
33//!
34//! - **dbserver** strings are UTF-16 **big**-endian, length-prefixed in
35//! *characters* including the terminating NUL.
36//! - **NFS** paths and names are UTF-16 **little**-endian, length-prefixed in
37//! *bytes*.
38//!
39//! They must never share a helper. [`dbserver::encode_string`] and
40//! [`rpc::xdr::Writer::utf16le_string`] are deliberately separate.
41//!
42//! # Provenance
43//!
44//! Every constant here was observed on the wire. Where a value is reproduced
45//! without being understood, the doc comment says so and cites the finding
46//! number (`F<n>`, `C<n>`, `O<n>`) in the research record that establishes it.
47//! Several fields are copied verbatim precisely because substituting a
48//! plausible zero has broken playback (F33, F35).
49
50// Tests are allowed to panic: an assertion *is* the failure mode, and a test
51// that carefully propagated errors would report them as passes.
52#![cfg_attr(
53 test,
54 allow(
55 clippy::unwrap_used,
56 clippy::expect_used,
57 clippy::panic,
58 clippy::indexing_slicing,
59 clippy::as_conversions
60 )
61)]
62
63pub mod analysis;
64pub mod beat;
65pub mod dbserver;
66pub mod device;
67pub mod djl;
68pub mod rpc;
69pub mod status;
70
71mod error;
72mod status_templates;
73
74pub use device::{BrowsableDeviceNumber, DeviceKind, DeviceName, DeviceNumber, MacAddress};
75pub use error::{Error, Result};
76
77/// Encode a `binrw` value into a fresh buffer.
78///
79/// Infallible by construction: the only two things `binrw` can fail on are a
80/// short write and an argument it cannot satisfy, and a `Vec` never runs out of
81/// room while every type in this crate writes with `()` arguments. Centralised
82/// so the reasoning is written down once instead of at every call site.
83pub(crate) fn to_bytes<T>(value: &T) -> Vec<u8>
84where
85 T: binrw::BinWrite + for<'a> binrw::meta::WriteEndian,
86 for<'a> <T as binrw::BinWrite>::Args<'a>: Default,
87{
88 let mut out = std::io::Cursor::new(Vec::new());
89 #[expect(
90 clippy::expect_used,
91 reason = "writing to a Vec cannot fail; see the doc comment"
92 )]
93 binrw::BinWrite::write(value, &mut out).expect("encoding into a Vec cannot fail");
94 out.into_inner()
95}
96
97/// The 10-byte magic every Pro DJ Link datagram starts with, on all three UDP
98/// ports.
99pub const MAGIC: [u8; 10] = *b"Qspt1WmJOL";
100
101/// UDP port carrying discovery, device-number claiming and keep-alive.
102pub const DISCOVERY_PORT: u16 = 50000;
103
104/// UDP port carrying beat and sync packets.
105pub const BEAT_PORT: u16 = 50001;
106
107/// UDP port carrying player status, media queries and device settings.
108pub const STATUS_PORT: u16 = 50002;
109
110/// A media slot, numbered as the status packets number them.
111///
112/// A newtype rather than an enum because slot bytes outside 0–4 do turn up in
113/// the corpus, and a decoder that refuses them would drop a whole packet over
114/// one field it does not need.
115#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
116pub struct Slot(pub u8);
117
118impl Slot {
119 /// No slot / nothing loaded.
120 pub const NONE: Self = Self(0);
121 /// The CD drive.
122 pub const CD: Self = Self(1);
123 /// The SD card slot.
124 pub const SD: Self = Self(2);
125 /// The USB slot.
126 pub const USB: Self = Self(3);
127 /// A rekordbox collection reached over the network.
128 pub const REKORDBOX: Self = Self(4);
129
130 /// The lowercase name used on the command line and in log output.
131 pub fn name(self) -> &'static str {
132 match self {
133 Self::NONE => "none",
134 Self::CD => "cd",
135 Self::SD => "sd",
136 Self::USB => "usb",
137 Self::REKORDBOX => "rekordbox",
138 _ => "unknown",
139 }
140 }
141
142 /// Parse a slot from its [`name`](Self::name), accepting `rb` for
143 /// `rekordbox`.
144 pub fn parse(name: &str) -> Option<Self> {
145 Some(match name.to_ascii_lowercase().as_str() {
146 "none" => Self::NONE,
147 "cd" => Self::CD,
148 "sd" => Self::SD,
149 "usb" => Self::USB,
150 "rb" | "rekordbox" => Self::REKORDBOX,
151 _ => return None,
152 })
153 }
154}
155
156impl core::fmt::Debug for Slot {
157 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
158 match *self {
159 Self::NONE | Self::CD | Self::SD | Self::USB | Self::REKORDBOX => {
160 f.write_str(self.name())
161 }
162 Self(raw) => write!(f, "Slot({raw:#04x})"),
163 }
164 }
165}
166
167impl core::fmt::Display for Slot {
168 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
169 core::fmt::Debug::fmt(self, f)
170 }
171}