Skip to main content

prolink_cxx/
lib.rs

1// SPDX-License-Identifier: GPL-3.0-only
2
3//! A C++ binding for [`prolink`], generated by [`cxx`].
4//!
5//! Built for Mixxx, whose Pro DJ Link support is being replaced by calls into
6//! this library, and shaped by that: the C++ side is meant to be a thin shell
7//! that renders, so **everything here hands over state that is ready to
8//! display** rather than parts a caller has to reassemble. There is no packet,
9//! no socket and no parsing in this API.
10//!
11//! # Why `cxx` and not a C ABI
12//!
13//! A hand-written C header has to be kept in step with the Rust by hand, and
14//! the failure mode when it is not is a caller's stack corrupted at run time,
15//! on a machine the author does not have. `cxx` generates both sides from this
16//! one file, so the same mistake is a compile error in both languages — and
17//! `String` and `Vec` cross as `rust::String` and `rust::Vec` rather than as
18//! fixed-size buffers with a length convention.
19//!
20//! Nothing on the C++ side of this boundary is `unsafe`, and nothing it
21//! receives needs freeing.
22//!
23//! # Two rules the surface follows
24//!
25//! **Events are drained, never pushed.** A callback would be invoked from a
26//! tokio worker thread, which for a Qt host means every handler has to be
27//! thread-safe and re-entrant, and a slow one stalls the network. Instead
28//! `drain_events` returns everything queued since the last call, on the
29//! caller's own thread, from a timer or an idle handler. Back-pressure is
30//! bounded rather than unbounded: `Event::dropped` says how much was missed.
31//!
32//! **Absent numbers are negative, never zero.** A host drawing a tempo has to
33//! tell "not playing" from "0.00 BPM", and zero cannot. `cxx` has no `Option`
34//! in a shared struct, so the convention is explicit and applied everywhere:
35//! `-1.0` means "no value", not a value of minus one.
36//!
37//! # Example
38//!
39//! ```cpp
40//! #include "prolink-cxx/src/lib.rs.h"
41//!
42//! auto session = prolink::open(prolink::default_config());
43//!
44//! // From a UI timer, on your own thread:
45//! for (const prolink::Event& event : session->drain_events()) {
46//!     if (event.kind == prolink::EventKind::Beat) { /* ... */ }
47//! }
48//!
49//! for (const prolink::Player& player : session->players()) {
50//!     if (player.is_master) {
51//!         meter->setPhase(player.bar_phase);
52//!     }
53//! }
54//! ```
55
56mod anlz;
57mod browse;
58mod convert;
59mod logging;
60mod pdb;
61mod serve;
62mod session;
63
64pub use logging::init_logging;
65pub use session::Session;
66
67/// The shared vocabulary, and the entry points.
68///
69/// `cxx` generates the C++ declarations for everything in here, so a field
70/// added on one side cannot go missing on the other: it is a compile error in
71/// both languages rather than a layout mismatch at run time.
72#[allow(
73    unsafe_code,
74    reason = "the bridge macro expands to the extern declarations that make \
75              the two languages agree on layout and lifetime, and those cannot \
76              be written safely. Nothing hand-written in this crate is unsafe, \
77              which is the whole reason for choosing cxx over a C ABI."
78)]
79#[cxx::bridge(namespace = "prolink")]
80pub mod ffi {
81    /// What a device says it is.
82    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
83    #[repr(u8)]
84    enum DeviceKind {
85        /// Anything we have no name for.
86        Unknown,
87        /// A player.
88        Cdj,
89        /// A mixer.
90        Mixer,
91        /// rekordbox on a computer, and also the CDJ-3000.
92        Rekordbox,
93    }
94
95    /// Which slot media is in.
96    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
97    #[repr(u8)]
98    enum Slot {
99        /// Nothing.
100        None,
101        /// The CD drive.
102        Cd,
103        /// The SD card.
104        Sd,
105        /// The USB slot.
106        Usb,
107        /// Another player's media, over LINK.
108        Rekordbox,
109    }
110
111    /// What a platter is doing.
112    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
113    #[repr(u8)]
114    enum PlayState {
115        /// Nothing loaded.
116        NoTrack,
117        /// Loading.
118        Loading,
119        /// Playing.
120        Playing,
121        /// Playing inside a loop.
122        Looping,
123        /// Paused.
124        Paused,
125        /// Stopped at the cue point.
126        Cued,
127        /// Playing from the cue point while the button is held.
128        CuePlay,
129        /// Searching.
130        Searching,
131        /// Spun down.
132        SpunDown,
133        /// The medium went away mid-play and the deck is looping its buffer.
134        Emergency,
135        /// A value this library has never seen on the wire.
136        Other,
137    }
138
139    /// What happened.
140    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
141    #[repr(u8)]
142    enum EventKind {
143        /// A device appeared.
144        DeviceFound,
145        /// A device's details changed.
146        DeviceChanged,
147        /// A device stopped sending keep-alives.
148        DeviceLost,
149        /// A player started a beat. `beat_in_bar` says which.
150        Beat,
151        /// A player's status changed: what is loaded, or what it is doing.
152        PlayerChanged,
153        /// Tempo master moved. `device` is the new master, or zero for nobody.
154        TempoMaster,
155        /// A player stopped sending beats.
156        Stopped,
157        /// A transfer advanced. `transfer`, `done` and `total` are set.
158        TransferProgress,
159        /// A transfer finished. `ok` says whether it succeeded, `detail`
160        /// carries the reason when it did not, and `path` is where it was
161        /// written.
162        TransferDone,
163        /// A player described one of its slots: volume name and counts.
164        ///
165        /// A deck sends this once, when it first browses a slot, so a host
166        /// that only polls `media()` may wait a long time for it (F37).
167        MediaInfo,
168    }
169
170    /// How to start a session.
171    #[derive(Debug, Clone)]
172    struct Config {
173        /// The interface to use, or empty to choose one.
174        ///
175        /// Choosing automatically prefers a link-local address, which is what
176        /// a DJ network always is; on a machine with two candidates it is a
177        /// coin toss, so a host with a settings screen should name one.
178        interface: String,
179
180        /// Whether to announce as a virtual CDJ.
181        ///
182        /// **Off means the loaded track, the play state and the tempo master
183        /// are never populated**, because a player unicasts status to peers
184        /// that have announced themselves and to nobody else (F21). Tempo and
185        /// beat phase still arrive, since beats are broadcast.
186        announce: bool,
187
188        /// The player number to ask for, 1–4, or 0 for whichever is free.
189        ///
190        /// Not a cosmetic choice, and not a number to invent: a deck offers
191        /// LINK sources and answers browse requests only for players 1–4, and
192        /// at any other number it accepts the announcement in full and then
193        /// silently never asks us anything (F45). The claim chain negotiates
194        /// for real — it watches first, backs off when a number is defended,
195        /// and defends the one it takes — so this is a preference, not an
196        /// assertion.
197        ///
198        /// A host restarting a session should pass back the number it last
199        /// held, so a refresh keeps the identity the decks already know.
200        preferred_number: u8,
201
202        /// Whether to offer this machine's own rekordbox sticks to the players.
203        ///
204        /// On, the session scans the mount points every two seconds and serves
205        /// what it finds — USB first, then SD, which is all a CDJ has. That is
206        /// what makes this machine appear in a deck's LINK menu; a player with
207        /// no media is listed nowhere, whatever its number (F24).
208        ///
209        /// Off, `serve_media` still works: a host that knows its own media,
210        /// or wants a stick the DJ chose rather than every stick, drives it
211        /// directly.
212        share_local_media: bool,
213    }
214
215    /// A network interface that could carry Pro DJ Link traffic.
216    #[derive(Debug, Clone)]
217    struct NetworkInterface {
218        /// The system's name for it.
219        name: String,
220        /// Its IPv4 address.
221        address: String,
222        /// Its broadcast address.
223        broadcast: String,
224        /// Whether the address is link-local, which a DJ network's always is.
225        ///
226        /// A host choosing automatically should prefer these: a CDJ
227        /// self-assigns in `169.254.0.0/16` after DHCP fails (F8).
228        is_link_local: bool,
229    }
230
231    /// A device on the network.
232    #[derive(Debug, Clone)]
233    struct Device {
234        /// 1–6 for a player, higher for other things.
235        number: u8,
236        /// What kind of device it says it is.
237        kind: DeviceKind,
238        /// Whether it is a player, and so something that can be browsed.
239        is_player: bool,
240        /// Whether it is still sending keep-alives.
241        online: bool,
242        /// Its hardware address, as `00:11:22:33:44:55`.
243        mac: String,
244        /// Its name. `CDJ-2000nexus` and the like.
245        name: String,
246        /// Its IPv4 address.
247        address: String,
248        /// Milliseconds since its last keep-alive.
249        last_seen_ms: u64,
250    }
251
252    /// What one player is doing, as a host would render it.
253    ///
254    /// The fields that need a status packet — the loaded track, the play
255    /// state, the tempo master — are populated only when the session
256    /// announced itself (F21). `has_status` says whether they mean anything,
257    /// so a host never draws a confident zero it was never told.
258    #[derive(Debug, Clone)]
259    struct Player {
260        /// The player's number.
261        number: u8,
262        /// Its name.
263        name: String,
264
265        /// Whether the status fields below mean anything.
266        has_status: bool,
267        /// Whether it is sending beats, and so playing a rekordbox track.
268        is_beating: bool,
269        /// Whether its status says it is playing: flag `0x40` of byte `0x89`,
270        /// which goes with beats and with taking master. Not the play state:
271        /// a deck playing a plain file is at play state 3 with this clear,
272        /// sends no beats and never takes master (emulated, E12). False
273        /// without status.
274        is_playing: bool,
275
276        /// The tempo actually playing: the track's BPM with pitch applied.
277        /// Negative when unknown.
278        effective_bpm: f64,
279        /// The track's own BPM, before pitch. Negative when unknown.
280        track_bpm: f64,
281        /// The pitch fader as a percentage, zero at centre.
282        ///
283        /// **Not the fader position while `is_synced`**: a synced deck slews
284        /// this to hold its effective tempo equal to the master's (F51).
285        pitch_percent: f64,
286
287        /// Position within the current beat, `0.0` on the beat. Negative when
288        /// the player is not beating or the estimate has gone stale.
289        beat_phase: f64,
290        /// Position within the four-beat bar, `0.0` on the downbeat. Negative
291        /// when unknown.
292        bar_phase: f64,
293        /// Where in the bar the deck's status packet puts the playhead, `0.0`
294        /// on the downbeat, **to the nearest beat below**. Negative when
295        /// unknown.
296        ///
297        /// For a deck that is not playing, which `bar_phase` has nothing to say
298        /// about: beats stop with the platter, status does not, and this
299        /// follows the jog wheel a beat at a time.
300        bar_position: f64,
301        /// Which beat of the bar, 1–4. Zero when the player has no bar to be
302        /// in, which is what an unanalysed track reports.
303        beat_in_bar: u8,
304        /// How long ago its last beat packet arrived, in milliseconds.
305        /// Negative when none has.
306        ///
307        /// `beat_phase` and `bar_phase` stop at the end of the beat when the
308        /// next packet is late rather than run on, so a host comparing its
309        /// own phase against them needs this to tell "on the beat" from "the
310        /// next beat has not arrived yet".
311        beat_age_ms: f64,
312        /// How long ago its last status packet arrived, in milliseconds.
313        /// Negative when none has.
314        ///
315        /// A deck that has gone (cable pulled, powered off) keeps its last
316        /// status, mastership included, until it is forgotten some 30 s later.
317        /// A deck sends status every ~200 ms, so an age well past that means
318        /// the fields above describe a deck that is no longer there.
319        status_age_ms: f64,
320
321        /// Whether this player holds tempo master.
322        is_master: bool,
323        /// Whether SYNC is lit.
324        is_synced: bool,
325        /// The device it is handing master to, or zero.
326        ///
327        /// Non-zero for only the one or two packets of a handoff, during which
328        /// **both** decks report themselves master; a host that ignores this
329        /// will see mastership flicker (F52).
330        yielding_to: u8,
331
332        /// What the platter is doing.
333        play_state: PlayState,
334        /// The loaded track's row id, or zero.
335        track_id: u32,
336        /// Which player the loaded track came from.
337        track_source_player: u8,
338        /// Which of that player's slots.
339        track_source_slot: Slot,
340        /// Whether the loaded track is a rekordbox-analysed one, the only kind
341        /// whose `track_id` is a row in that medium's export.pdb. An
342        /// unanalysed file's id is the player's own numbering, and looking it
343        /// up there finds an unrelated track.
344        track_is_rekordbox: bool,
345    }
346
347    /// A row in a browse menu: a track, an artist, an album, a category.
348    #[derive(Debug, Clone)]
349    struct Row {
350        /// What the row names — a track id in a track list, an artist id in an
351        /// artist list. What to pass back when the user opens it.
352        id: u32,
353        /// The first line: a title, a name, a category label.
354        label: String,
355        /// The second line, which the sort chooses: the artist under a title,
356        /// the tempo under a BPM sort. Empty when the sort is numeric.
357        detail: String,
358        /// The raw item type, so a host can tell a track row from a category
359        /// row without matching on the label.
360        item_type: u32,
361        /// The artwork to fetch for this row, or zero.
362        artwork_id: u32,
363        /// Its 1-based position inside a playlist, or its track number.
364        position: u32,
365        /// Whether this row is the track the browsing deck has loaded.
366        is_loaded: bool,
367        /// Whether this row is in the deck's tag list.
368        is_tagged: bool,
369    }
370
371    /// Everything a deck will tell us about one track.
372    #[derive(Debug, Clone)]
373    struct Metadata {
374        /// The track's row id.
375        id: u32,
376        /// Its title.
377        title: String,
378        /// Its artist.
379        artist: String,
380        /// Its album.
381        album: String,
382        /// Its genre.
383        genre: String,
384        /// Its musical key, as the medium spells it — Camelot on one export,
385        /// classical on another, because that is a rekordbox setting.
386        key: String,
387        /// Its record label.
388        label: String,
389        /// Its colour tag.
390        colour: String,
391        /// The DJ comment.
392        comment: String,
393        /// When it was added, as `2025-06-24`.
394        date_added: String,
395        /// How long it runs, in seconds.
396        duration_seconds: u32,
397        /// Its tempo in hundredths of a BPM, before any pitch fader.
398        tempo_centibpm: u32,
399        /// Its star rating.
400        rating: u32,
401        /// Its bitrate in kbps.
402        bitrate: u32,
403        /// The artwork to fetch, or zero.
404        artwork_id: u32,
405    }
406
407    /// One folder or file of a player's plain stick, as its FOLDER menus list
408    /// it.
409    #[derive(Debug, Clone)]
410    struct PlainEntry {
411        /// Its id on the player's medium: what the player names it by.
412        id: u32,
413        /// The folder holding it, or 0 at the top of the stick.
414        parent: u32,
415        /// Its name, a file's with its extension, as the player shows it.
416        name: String,
417        /// A folder rather than a file.
418        is_folder: bool,
419    }
420
421    /// What one of a player's slots holds.
422    #[derive(Debug, Clone)]
423    struct MediaInfo {
424        /// Which player.
425        device: u8,
426        /// Which slot.
427        slot: Slot,
428        /// Whether a medium is present and mounted.
429        has_media: bool,
430        /// A stick with no rekordbox library, offered by its folders: the
431        /// player said so in its description (`02` at `0xaa`). False until it
432        /// has described the slot.
433        plain: bool,
434        /// The volume name, empty until the player has described the slot.
435        volume_name: String,
436        /// When the export was written, as `2025-06-24`. Empty until known.
437        created: String,
438        /// How many tracks it holds. Zero until known.
439        track_count: u32,
440        /// How many playlists. Zero until known.
441        playlist_count: u32,
442    }
443
444    /// How to serve local media to real players.
445    #[derive(Debug, Clone)]
446    struct ServeConfig {
447        /// The interface to use, or empty to choose one.
448        interface: String,
449        /// The medium to present in the USB slot, or empty for none.
450        usb_path: String,
451        /// The medium to present in the SD slot, or empty for none.
452        ///
453        /// A second USB stick shown as an SD card is exactly what a CDJ
454        /// expects to see.
455        sd_path: String,
456    }
457
458    /// One of our own slots, as we offer it.
459    #[derive(Debug, Clone)]
460    struct ServedSlot {
461        /// Which slot we present it in.
462        slot: Slot,
463        /// The volume name a deck shows.
464        volume_name: String,
465        /// Where it came from on this machine.
466        local_path: String,
467        /// The NFS export path a deck mounts.
468        export_path: String,
469        /// How many tracks it holds: a plain stick's files.
470        track_count: u32,
471        /// How many playlists.
472        playlist_count: u32,
473        /// Whether it is a stick with no rekordbox library, offered by its
474        /// folders.
475        plain: bool,
476        /// Whether the medium behind this is **gone** while a player is still
477        /// playing off it.
478        ///
479        /// It stays announced, because that is what keeps the consumer's mount
480        /// valid and its player from erroring out mid-track, and it is served
481        /// from copies made while the stick was in. It is no longer browsable:
482        /// menus answer empty, so nobody can start something we could not
483        /// finish. It leaves for real once the last consumer moves on.
484        phantom: bool,
485    }
486
487    /// A player that has taken a track off our media.
488    #[derive(Debug, Clone)]
489    struct ServeConsumer {
490        /// Which player.
491        device_number: u8,
492        /// Its name.
493        device_name: String,
494        /// Its address.
495        address: String,
496        /// Which of our slots it took the track from.
497        slot: Slot,
498        /// The track's row id.
499        track_id: u32,
500        /// Whether it is playing right now.
501        playing: bool,
502    }
503
504    /// What a running server is doing.
505    #[derive(Debug, Clone)]
506    struct ServeStatus {
507        /// Whether we hold a player number, without which nothing else here
508        /// matters: a deck validates it in every dbserver request (F45).
509        active: bool,
510        /// The number we hold, 1–4.
511        device_number: u8,
512        /// The address we serve from.
513        address: String,
514        /// The interface we serve on.
515        interface: String,
516        /// Where the portmapper is listening.
517        ///
518        /// **Must be 111.** With nothing there a deck retries `GETPORT` once a
519        /// second for ever rather than falling back to the well-known ports,
520        /// and never reaches the dbserver at all (F46).
521        portmap_port: u16,
522        /// Where mountd is listening.
523        mount_port: u16,
524        /// Where nfsd is listening.
525        nfs_port: u16,
526        /// Where the dbserver is listening.
527        dbserver_port: u16,
528        /// Whether a real player can actually find us — the portmapper is on
529        /// 111 and we hold a browsable number.
530        is_discoverable: bool,
531        /// The media we are offering.
532        media: Vec<ServedSlot>,
533        /// The players reading from us, and what each has loaded.
534        consumers: Vec<ServeConsumer>,
535    }
536
537    /// One track, as `export.pdb` stores it.
538    ///
539    /// The names are resolved as well as their row ids given: a host that only
540    /// wants to show a track never has to join anything, and one building a
541    /// browse tree still can.
542    #[derive(Debug, Clone)]
543    struct PdbTrack {
544        /// The row id, which is what every other request names a track by.
545        id: u32,
546        /// The track's title.
547        title: String,
548        /// Its artist, resolved from the artist table.
549        artist: String,
550        /// Its album.
551        album: String,
552        /// Its genre.
553        genre: String,
554        /// Its musical key, as the medium spells it.
555        key: String,
556        /// Its record label.
557        label: String,
558        /// Its colour tag.
559        color: String,
560        /// The DJ comment.
561        comment: String,
562        /// The path on the medium, with a leading slash, exactly as the
563        /// database stores it — which is what a fetch takes verbatim.
564        file_path: String,
565        /// The `.DAT` beside it, holding the beat grid and waveforms.
566        analyze_path: String,
567        /// The artwork file on the medium, if it has one.
568        artwork_path: String,
569        /// When it was added, as `2025-06-24`.
570        date_added: String,
571        /// Its release year, or zero.
572        year: u32,
573        /// How long it runs.
574        duration_seconds: u32,
575        /// In kbps.
576        bitrate: u32,
577        /// Hundredths of a BPM, so 145.00 is 14500.
578        tempo_centibpm: u32,
579        /// Its star rating.
580        rating: u32,
581        /// The artwork to fetch, or zero.
582        artwork_id: u32,
583        /// In Hz.
584        sample_rate: u32,
585        /// In bytes.
586        file_size: u32,
587        /// Its number within its album.
588        track_number: u32,
589        /// Its disc, for a multi-disc album.
590        disc_number: u32,
591        /// How many times a deck has played it.
592        play_count: u32,
593        /// The container byte, which is what a deck uses to decide how to
594        /// decode the file.
595        file_type: u32,
596        /// The artist's row id, for a browse tree.
597        artist_id: u32,
598        /// The album's row id.
599        album_id: u32,
600        /// The genre's row id.
601        genre_id: u32,
602        /// The key's row id. Per-medium, not a canonical index.
603        key_id: u32,
604        /// The label's row id.
605        label_id: u32,
606        /// The colour's palette index.
607        color_id: u32,
608    }
609
610    /// A playlist, or a folder of them.
611    #[derive(Debug, Clone)]
612    struct PdbPlaylist {
613        /// Its row id.
614        id: u32,
615        /// The folder it sits in, or zero at the top level.
616        parent_id: u32,
617        /// Where it sorts among its siblings.
618        sort_order: u32,
619        /// Its name.
620        name: String,
621        /// Whether it holds other playlists rather than tracks.
622        is_folder: bool,
623        /// Empty for a folder, and in the DJ's own order for a playlist.
624        track_ids: Vec<u32>,
625    }
626
627    /// One history playlist: what a player played off this medium, in order.
628    ///
629    /// rekordbox writes one of these every time a player mounts the medium, so
630    /// a well-travelled stick carries a session per gig. They are the only
631    /// record of what was played that survives on the medium itself -- a deck
632    /// that mounts read-only, as TriMixxx does, never adds to them.
633    ///
634    /// There is no timestamp anywhere in the format. Order is all there is:
635    /// later row id means a later session, and later position within one means
636    /// later in that session.
637    #[derive(Debug, Clone)]
638    struct PdbHistoryPlaylist {
639        /// Its row id. Ascending with the session, which is what makes it
640        /// usable as a clock.
641        id: u32,
642        /// `HISTORY 001` and so on.
643        name: String,
644        /// The tracks, in the order they were played.
645        track_ids: Vec<u32>,
646    }
647
648    /// One beat of a `PQTZ` grid.
649    ///
650    /// `time_ms` is the beat's position and `tempo` is what rekordbox analysed
651    /// it at. Both are given because they disagree, and which one a host should
652    /// believe depends on the track: rekordbox writes beat times as **whole
653    /// milliseconds**, so at 144 BPM the stored gaps alternate 417, 417, 416 and
654    /// a grid built from them has a tempo that swings by up to 0.45 BPM
655    /// depending on which pair of beats is measured. `tempo` is centi-BPM and
656    /// exact. A host that finds one distinct tempo across the grid should use
657    /// it and anchor at the first beat; one that finds several has a genuinely
658    /// variable-tempo track and nothing but the positions.
659    #[derive(Debug, Clone)]
660    struct AnlzBeat {
661        /// Which beat of the bar, 1-4. The first beat numbered 1 is the only
662        /// record of the grid's phase.
663        beat_number: u16,
664        /// Centi-BPM at this beat.
665        tempo: u16,
666        /// Milliseconds from the start of the track.
667        time_ms: u32,
668    }
669
670    /// One cue or loop, from either cue tag.
671    ///
672    /// Flat rather than two types, because a host applies both in one pass and
673    /// the older tag is simply the newer one without the comment and the
674    /// colours. `extended` says which tag it came from, so a host can tell an
675    /// absent comment from an empty one.
676    #[derive(Debug, Clone)]
677    struct AnlzCue {
678        /// True when this came from `PCO2`, and so when the comment and colour
679        /// fields below mean anything.
680        extended: bool,
681        /// True for the hot-cue list, false for the memory-cue list. **A file
682        /// carries one list of each**, so a reader that takes the first tag
683        /// gets half the cues and no error.
684        hot_list: bool,
685        /// 0 for a memory cue, 1 for hot cue A, 2 for B, and so on.
686        hot_cue: u32,
687        /// True when this is a loop and `loop_time_ms` means something.
688        is_loop: bool,
689        /// Where it sits, in milliseconds at normal pitch.
690        time_ms: u32,
691        /// Where a loop jumps back from, in milliseconds. Zero unless `is_loop`.
692        loop_time_ms: u32,
693        /// The DJ's comment, already out of the file's UTF-16BE. Empty unless
694        /// `extended`.
695        comment: String,
696        /// Row id in rekordbox's colour table, for a memory cue given one.
697        color_id: u32,
698        /// Red component of the colour a player lights the pad with. Zero
699        /// unless `extended`.
700        color_red: u8,
701        /// Green component.
702        color_green: u8,
703        /// Blue component.
704        color_blue: u8,
705    }
706
707    /// One column of the `PWV5` colour scrolling waveform.
708    ///
709    /// **The three bands are a hue and `height` is the amplitude**, which is
710    /// what makes this a colour waveform rather than three waveforms. The bands
711    /// sit near saturation whatever the track is doing and correlate with the
712    /// height at only 0.0-0.4, while the height correlates with the monochrome
713    /// `PWV3` waveform of the same track at 0.99. A renderer that derives its
714    /// height from the bands draws the spectral balance instead of the
715    /// envelope, quantised to the eight levels three bits allow.
716    #[derive(Debug, Clone)]
717    struct AnlzColourColumn {
718        /// Bits 15-13. The loudest and slowest-varying band, drawn red.
719        bass: u8,
720        /// Bits 9-7. Drawn green.
721        mid: u8,
722        /// Bits 12-10. The quietest and spikiest band, drawn blue.
723        treble: u8,
724        /// Bits 6-2. The envelope, 0-31.
725        height: u8,
726    }
727
728    /// Everything read out of one `ANLZ####.DAT` or `.EXT`.
729    ///
730    /// Whichever of these a file has: a `.DAT` carries the grid and the plain
731    /// cues, a `.EXT` the extended cues and the colour waveforms. An absent tag
732    /// is an empty vector and not an error — which tags a file has depends on
733    /// the rekordbox version that wrote it.
734    #[derive(Debug, Clone)]
735    struct AnlzContents {
736        /// Whether the file parsed. On false the rest is empty and `error` says
737        /// why. A tag that does not parse costs that tag, not the file, and
738        /// leaves `ok` true.
739        ok: bool,
740        /// Why it did not parse. Empty when `ok`.
741        error: String,
742        /// `PQTZ`, the beat grid.
743        beats: Vec<AnlzBeat>,
744        /// `PCOB` and `PCO2`, both lists of each, in file order.
745        cues: Vec<AnlzCue>,
746        /// `PWV5`, the colour scrolling waveform, at 150 columns per second.
747        colour_detail: Vec<AnlzColourColumn>,
748        /// `PWAV`, the preview waveform: 400 packed bytes, height in the low
749        /// five bits and shade in the top three.
750        preview: Vec<u8>,
751    }
752
753    /// One column of the `PWV4` colour preview waveform.
754    ///
755    /// **The band names are not the colour names**, and which byte is which was
756    /// measured rather than taken from the field order: across three tracks off
757    /// a real stick the envelope byte correlates with the `PWAV` preview of the
758    /// same track at 0.78-0.87, the three bands fall in mean level (100, 56,
759    /// 29) and rise in roughness (0.05, 0.40, 0.56) exactly as `PWV5`'s do, and
760    /// the byte before them correlates *negatively* — so it is not an energy at
761    /// all and is left out.
762    #[derive(Debug, Clone)]
763    struct AnlzPreviewColumn {
764        /// Bottom third. Drawn red.
765        bass: u8,
766        /// Middle third. Drawn green.
767        mid: u8,
768        /// Top third. Drawn blue.
769        treble: u8,
770        /// Energy of the bottom half, which is the best proxy for the column's
771        /// height: it is what tracks the monochrome preview.
772        envelope: u8,
773    }
774
775    /// The preview waveforms of one analysis file, and nothing else from it.
776    ///
777    /// Separate from `read_anlz` because of what it does *not* do. A `.EXT` is
778    /// around 157 kB, of which the two full-resolution detail waveforms are
779    /// nearly all — some fifty thousand entries each — and a caller that wants
780    /// the 1200-column preview should not decode those to reach it. This walks
781    /// the tag headers and seeks past everything it was not asked for.
782    #[derive(Debug, Clone)]
783    struct AnlzPreview {
784        /// Whether the file could be read and its container parsed.
785        ok: bool,
786        /// Why not. Empty when `ok`.
787        error: String,
788        /// `PWAV`: 400 packed bytes, height in the low five bits and shade in
789        /// the top three. Empty when the file has none — a `.EXT` never does.
790        mono: Vec<u8>,
791        /// `PWV4`: 1200 colour columns. Empty when the file has none, which is
792        /// every `.DAT` and any `.EXT` written before the NXS2.
793        colour: Vec<AnlzPreviewColumn>,
794    }
795
796    /// A row of one of the lookup tables, for building a browse tree.
797    #[derive(Debug, Clone)]
798    struct PdbNamed {
799        /// The row id a track refers to.
800        id: u32,
801        /// What to show for it.
802        name: String,
803    }
804
805    /// Everything read out of one `export.pdb`.
806    #[derive(Debug, Clone)]
807    struct PdbContents {
808        /// Whether it parsed. On false the rest is empty and `error` says why.
809        ok: bool,
810        /// Why it did not parse. Empty when `ok`.
811        error: String,
812        /// Every track on the medium.
813        tracks: Vec<PdbTrack>,
814        /// Every playlist and folder.
815        playlists: Vec<PdbPlaylist>,
816        /// One per player mount: what was played off this medium, in order.
817        history: Vec<PdbHistoryPlaylist>,
818        /// The artist table.
819        artists: Vec<PdbNamed>,
820        /// The album table.
821        albums: Vec<PdbNamed>,
822        /// The genre table.
823        genres: Vec<PdbNamed>,
824        /// The key table. Its ids are per-medium.
825        keys: Vec<PdbNamed>,
826        /// The record-label table.
827        labels: Vec<PdbNamed>,
828        /// The colour palette.
829        colors: Vec<PdbNamed>,
830        /// The artwork table: id to file path.
831        artwork: Vec<PdbNamed>,
832    }
833
834    /// One thing that happened.
835    ///
836    /// Flat rather than a variant per kind, because C++ has no cheap sum type
837    /// and a host switches on `kind` and reads the two or three fields that
838    /// kind gives meaning to.
839    #[derive(Debug, Clone)]
840    struct Event {
841        /// What happened.
842        kind: EventKind,
843        /// Which device, or zero where the event is not about one.
844        device: u8,
845        /// Which beat of the bar, for `Beat`. Zero otherwise.
846        beat_in_bar: u8,
847        /// How many events were discarded before this one because the host
848        /// stopped draining.
849        ///
850        /// Non-zero means state was missed, and the host should re-read
851        /// `devices()` and `players()` rather than trust its running picture.
852        /// Never a `TransferDone` or a `MediaInfo`, which nothing repeats.
853        dropped: u32,
854
855        /// Which transfer, for the two transfer kinds. Zero otherwise.
856        transfer: u32,
857        /// Bytes transferred so far, in total. A fraction to show a user, and
858        /// **not** a statement about which bytes are on disk: a streaming fetch
859        /// takes the head, then the tail, then the middle, so after two steps
860        /// `done` counts bytes that are not contiguous with each other.
861        ///
862        /// Anything deciding whether a byte may be read must use `offset` and
863        /// `len` instead. Reading a hole is silent — it yields the zeros of a
864        /// sparse file rather than an error — so the difference matters far more
865        /// than it looks.
866        done: u64,
867        /// Bytes the file holds. Zero if not yet known.
868        ///
869        /// A streaming fetch announces the size on its own, in a first event
870        /// with `len` zero, as soon as the file has been opened and stat'd.
871        /// That is what lets a host size its view of the file and start
872        /// decoding without waiting for any content at all.
873        total: u64,
874        /// For `TransferProgress`, where the range that just landed starts.
875        offset: u64,
876        /// For `TransferProgress`, how long that range is. Zero when the event
877        /// carries no new bytes — the size announcement above, and the final
878        /// summary — and such an event must not be taken as data arriving.
879        len: u64,
880        /// For `TransferDone`, whether it succeeded.
881        ok: bool,
882        /// For a failed `TransferDone`, why. Empty otherwise.
883        detail: String,
884        /// For `TransferDone`, the local path it was written to.
885        ///
886        /// Carried as well as the id, because a host that keyed its own state
887        /// on the path it asked for should not have to keep an id table to get
888        /// back to it.
889        path: String,
890        /// For `MediaInfo`, which slot was described.
891        slot: Slot,
892    }
893
894    extern "Rust" {
895        /// A running session: sockets, timers, and the state they maintain.
896        type Session;
897
898        /// The interfaces that could carry Pro DJ Link traffic.
899        fn interfaces() -> Vec<NetworkInterface>;
900
901        /// A config that chooses an interface and announces.
902        fn default_config() -> Config;
903
904        /// Send this library's own log to standard error.
905        ///
906        /// Off until asked for, because a host owns its output and a library
907        /// that writes to it uninvited is a nuisance. But the protocol's
908        /// diagnosis lives in these lines and nowhere else — which player
909        /// number was claimed and why, which stick was mounted, and whether
910        /// the portmapper got port 111, without which no deck will ever list
911        /// us however well everything else works (F46).
912        ///
913        /// `filter` is a `tracing` directive: empty for a sensible default of
914        /// `prolink=info`, `prolink=debug` for the packet-level detail, or
915        /// whatever `PROLINK_LOG` says when that is set — which wins, so a
916        /// deck can be turned up without a rebuild.
917        ///
918        /// Safe to call more than once; only the first call installs anything.
919        fn init_logging(filter: &str);
920
921        /// Read a rekordbox `export.pdb` off disk.
922        ///
923        /// Never throws: a database that does not parse comes back with `ok`
924        /// false and `error` set, because a host that has just pulled several
925        /// megabytes over NFS wants to show the user why rather than unwind.
926        fn read_pdb(path: &str) -> PdbContents;
927
928        /// Read a rekordbox `export.pdb` a host already has in memory.
929        ///
930        /// The same contract as `read_pdb`. This is the one a host that
931        /// fetched the database itself wants, so that reading the file and
932        /// parsing it stay separate failures with separate messages.
933        fn read_pdb_bytes(bytes: &[u8]) -> PdbContents;
934
935        /// Read one `ANLZ####.DAT` or `.EXT` off disk.
936        ///
937        /// Never throws, like `read_pdb`: a file that does not parse comes
938        /// back with `ok` false and `error` set. A missing file is the same
939        /// answer — analysis is an enhancement, and a track with no grid
940        /// still plays.
941        ///
942        /// A free function and not a `Session` method, so it is safe to call
943        /// from a worker thread with no session running at all.
944        fn read_anlz(path: &str) -> AnlzContents;
945
946        /// Read only the preview waveforms out of one analysis file.
947        ///
948        /// Seeks past every tag it was not asked for, so reaching the 1200
949        /// colour columns of a 157 kB `.EXT` costs about 10 kB of reads and no
950        /// decoding of the fifty-thousand-entry detail waveforms beside them.
951        ///
952        /// Same never-throws contract as `read_anlz`, and a free function for
953        /// the same reason.
954        fn read_anlz_preview(path: &str) -> AnlzPreview;
955
956        /// Start a session. Throws on failure, with the reason.
957        fn open(config: &Config) -> Result<Box<Session>>;
958
959        /// The number we announced as, or zero if we did not announce.
960        fn device_number(self: &Session) -> u8;
961
962        /// Everyone on the network, as of now.
963        fn devices(self: &Session) -> Vec<Device>;
964
965        /// What every player is doing, as of now.
966        fn players(self: &Session) -> Vec<Player>;
967
968        /// Tell the network what this host is playing.
969        ///
970        /// **Without this we are a device with no tempo.** Everything else
971        /// here reads the network; this is the one call that makes us
972        /// something other players can beat-match to, and until it is made no
973        /// CDJ will draw a phase for us however well the rest works.
974        ///
975        /// `bpm` is the track's own tempo before the fader and
976        /// `pitch_percent` the fader itself, as the wire carries them.
977        /// `beat_number` counts beats from 1, and `beat_fraction` is how far
978        /// through that beat the playhead is. Zero for `beat_number` means
979        /// there is no grid to publish. `scratching` is the platter held or
980        /// dragged by hand: no beats are sent for it.
981        ///
982        /// Call it from a timer several times a second. Beats between calls
983        /// are projected from the tempo, so this rate sets how fast a tempo
984        /// change propagates, not the accuracy of the beats.
985        fn set_playback(
986            self: &Session,
987            bpm: f64,
988            pitch_percent: f64,
989            playing: bool,
990            scratching: bool,
991            beat_number: u32,
992            beat_fraction: f64,
993        );
994
995        /// State what this host has loaded, and whose medium it came from.
996        ///
997        /// **A tempo without this is ignored.** A deck publishes both or
998        /// neither; a CDJ asked to follow a master that claims a tempo and no
999        /// track does not follow it. `source_player` is the player whose
1000        /// medium the track came from — our own number when playing off our
1001        /// own stick — and `track_id` is the rekordbox row id.
1002        ///
1003        /// `plain` for a file off a stick with no rekordbox library: `track_id`
1004        /// is then that file's id on its medium (`served_file_id` for one of
1005        /// ours), and a player names it with `GET_GENERIC_METADATA`.
1006        fn set_loaded_track(
1007            self: &Session,
1008            source_player: u8,
1009            slot: Slot,
1010            track_id: u32,
1011            plain: bool,
1012        );
1013
1014        /// Nothing is loaded here. The network stops seeing a tempo from us.
1015        fn clear_playback(self: &Session);
1016
1017        /// Take tempo master, asking whoever holds it to hand over first.
1018        ///
1019        /// Returns immediately. If another device holds master the claim only
1020        /// takes effect once that device has yielded, which takes a packet or
1021        /// two — watch `is_tempo_master`.
1022        fn take_tempo_master(self: &Session);
1023
1024        /// Whether SYNC is engaged here.
1025        ///
1026        /// Published as flag bit 4, which is what a CDJ lights its own SYNC
1027        /// button from and what says this deck is following rather than flying
1028        /// its own tempo.
1029        fn set_synced(self: &Session, synced: bool);
1030
1031        /// Give up tempo master.
1032        fn release_tempo_master(self: &Session);
1033
1034        /// Take a mastership another deck is handing us unasked, naming us at
1035        /// byte `0x9f`. True when one was, and we now claim it.
1036        fn accept_tempo_master(self: &Session) -> bool;
1037
1038        /// Hand tempo master to `device` unasked, as a CDJ master that stops
1039        /// does for a synced deck playing on; kept if it never picks up.
1040        fn offer_tempo_master(self: &Session, device: u8) -> bool;
1041
1042        /// Whether we are claiming tempo master.
1043        fn is_tempo_master(self: &Session) -> bool;
1044
1045        /// Everything that has happened since the last call.
1046        ///
1047        /// Empty is the normal case. Call it from a timer; nothing is ever
1048        /// pushed from a network thread.
1049        fn drain_events(self: &Session) -> Vec<Event>;
1050
1051        /// Fetch one file from a player's medium into `local_path`.
1052        ///
1053        /// Returns a transfer id. Progress arrives as `TransferProgress`
1054        /// events carrying that id, and exactly one `TransferDone` ends it.
1055        ///
1056        /// `remote_path` is taken verbatim from `export.pdb`, which stores
1057        /// paths relative to the medium root with a leading slash.
1058        ///
1059        /// **Nothing partial is ever written.** The file is assembled and
1060        /// written once, because a truncated `export.pdb` parses far enough to
1061        /// look plausible and then yields a library missing its last few
1062        /// hundred tracks.
1063        /// Fetch a track head-first so it can be played before it has fully
1064        /// arrived.
1065        ///
1066        /// The local file is created at its full size immediately, sparse, so a
1067        /// decoder reading it sees the right duration from the start. Then:
1068        ///
1069        ///  * the **first** `TransferProgress` carries `total` and nothing else
1070        ///    — the size, as soon as the file has been opened and stat'd, which
1071        ///    is everything a caller needs to start;
1072        ///  * each one after it carries the `offset` and `len` of a range that
1073        ///    has landed and been flushed, head first, then tail, then the
1074        ///    middle in playhead order;
1075        ///  * `TransferDone` means the whole file is local.
1076        ///
1077        /// **The gaps are real.** Until a range has been announced, that part
1078        /// of the file is a sparse hole and reads back as zeros, successfully.
1079        /// A caller that decodes ahead of the announcements gets silence, not
1080        /// an error, so it must block on anything it has not been told about.
1081        fn fetch_file_streaming(
1082            self: &Session,
1083            device_number: u8,
1084            slot: Slot,
1085            remote_path: &str,
1086            local_path: &str,
1087            head_bytes: u32,
1088        ) -> Result<u32>;
1089
1090        fn fetch_file(
1091            self: &Session,
1092            device_number: u8,
1093            slot: Slot,
1094            remote_path: &str,
1095            local_path: &str,
1096        ) -> Result<u32>;
1097
1098        /// Whether the sockets are up and we are hearing the network.
1099        fn is_listening(self: &Session) -> bool;
1100
1101        /// Offer a local rekordbox medium to the players on the network.
1102        ///
1103        /// `path` is the mount point — the directory holding `PIONEER/`.
1104        /// Replaces whatever was in that slot. Returns at once; reading the
1105        /// database and walking the files takes a second or two, and a path
1106        /// that is not a rekordbox export is reported through `last_error`.
1107        ///
1108        /// Not needed when `Config::share_local_media` is on, which serves
1109        /// every stick this machine has.
1110        fn serve_media(self: &Session, slot: Slot, path: &str);
1111
1112        /// Stop offering whatever is in a slot.
1113        ///
1114        /// Ejects it first, which takes a couple of seconds when a deck is
1115        /// reading from us — it is told through the slot state in our status
1116        /// packets and answers with UMNT. Returns at once; the eject happens
1117        /// on the session's own runtime.
1118        fn stop_serving(self: &Session, slot: Slot);
1119
1120        /// What we are offering, and which players are reading it.
1121        fn serve_status(self: &Session) -> ServeStatus;
1122
1123        /// The id a plain stick we serve gives one of its files, or zero.
1124        ///
1125        /// `path` is where the file is from the stick's root, as the host plays
1126        /// it; the id is what this host says it has loaded, with `plain`, so a
1127        /// player browsing us can name the track (`set_loaded_track`). Zero
1128        /// when nothing plain is served in that slot, or the file is not one
1129        /// it offers.
1130        fn served_file_id(self: &Session, slot: Slot, path: &str) -> u32;
1131
1132        /// Where a file of a plain stick we serve is from the stick's root,
1133        /// `/` first, by the id it is served under; empty for none.
1134        ///
1135        /// The other way from `served_file_id`: a player playing one of our
1136        /// plain files names it by that id in its status, and the host knows
1137        /// its tracks by their paths.
1138        fn served_file_path(self: &Session, slot: Slot, file_id: u32) -> String;
1139
1140        /// The interface currently bound, or empty if none is.
1141        ///
1142        /// Not fixed for the life of the session: a host is often started
1143        /// before its ethernet is plugged in, and the session moves when a
1144        /// better interface appears.
1145        fn interface_name(self: &Session) -> String;
1146
1147        /// Whether startup has finished.
1148        ///
1149        /// `open` returns before the sockets are bound, because claiming a
1150        /// player number takes about five seconds of watching and negotiating
1151        /// and a host must not spend that frozen. Until this is true
1152        /// `device_number` is zero and the tables are empty; if it stays false,
1153        /// `last_error` says what went wrong.
1154        fn is_ready(self: &Session) -> bool;
1155
1156        /// The last thing that went wrong, or empty. For a status line.
1157        fn last_error(self: &Session) -> String;
1158
1159        /// Forget every device and re-learn the network.
1160        ///
1161        /// A host offers this when a user has re-cabled the rig: a deck that
1162        /// vanished without a keep-alive is otherwise held for the full
1163        /// timeout.
1164        fn refresh(self: &mut Session);
1165
1166        /// What every player's slots hold, as of now.
1167        ///
1168        /// A slot a player has not yet described comes back with
1169        /// `has_media` true and the counts zero: the presence is published in
1170        /// every status packet, the description only when a deck first asks
1171        /// (F20, F37).
1172        fn media(self: &Session) -> Vec<MediaInfo>;
1173
1174        /// The root menu of a player's slot, as its LINK button shows it.
1175        ///
1176        /// **Blocks on the network, and claims a browsable device number the
1177        /// first time.** Call it off the UI thread; a dbserver request needs a
1178        /// number in 1–4, which contends with the decks for one (F45).
1179        fn root_menu(self: &mut Session, device_number: u8, slot: Slot) -> Result<Vec<Row>>;
1180
1181        /// Every track on a player's slot, under the given sort.
1182        ///
1183        /// Blocks; see `root_menu`. `sort` is zero for the default, which is
1184        /// by title.
1185        fn track_rows(
1186            self: &mut Session,
1187            device_number: u8,
1188            slot: Slot,
1189            sort: u32,
1190        ) -> Result<Vec<Row>>;
1191
1192        /// Search a player's slot, the way its on-screen keyboard does.
1193        ///
1194        /// Blocks; see `root_menu`. The term is upper-cased on the way out,
1195        /// because a deck's own keyboard has no lower case and its dbserver is
1196        /// case-sensitive (F44).
1197        fn search(
1198            self: &mut Session,
1199            device_number: u8,
1200            slot: Slot,
1201            term: &str,
1202        ) -> Result<Vec<Row>>;
1203
1204        /// Everything a player will say about one track.
1205        ///
1206        /// Blocks; see `root_menu`.
1207        fn metadata(
1208            self: &mut Session,
1209            device_number: u8,
1210            slot: Slot,
1211            track_id: u32,
1212        ) -> Result<Metadata>;
1213
1214        /// Ask a player for a track's preview waveform.
1215        ///
1216        /// Returns a transfer id. The bytes arrive as a `TransferDone` with
1217        /// that id and are collected with `take_waveform_preview`; nothing is
1218        /// written to a filesystem at either end.
1219        fn fetch_waveform_preview(
1220            self: &Session,
1221            device_number: u8,
1222            slot: Slot,
1223            track_id: u32,
1224        ) -> Result<u32>;
1225
1226        /// Ask a player what one of its plain files is, without blocking.
1227        ///
1228        /// For a track a player has loaded off a stick with no rekordbox
1229        /// library (`Player::track_is_rekordbox` false): `GET_GENERIC_METADATA`,
1230        /// what the player reads off the file's tags. Returns a transfer id;
1231        /// the answer arrives as a `TransferDone` with that id and is collected
1232        /// with `take_metadata`.
1233        fn fetch_plain_metadata(
1234            self: &Session,
1235            device_number: u8,
1236            slot: Slot,
1237            file_id: u32,
1238        ) -> Result<u32>;
1239
1240        /// Take a finished `fetch_plain_metadata`'s answer, by transfer id.
1241        ///
1242        /// Empty if it failed or has already been taken.
1243        fn take_metadata(self: &Session, transfer: u32) -> Metadata;
1244
1245        /// Walk a player's plain stick, without blocking: every folder and
1246        /// file its FOLDER menus list, names only. Returns a transfer id; the
1247        /// entries are collected with `take_plain_tree` once its `TransferDone`
1248        /// arrives. A CDJ lists no directory over NFS, so this is the only way
1249        /// to a plain stick's files.
1250        fn fetch_plain_tree(self: &Session, device_number: u8, slot: Slot) -> Result<u32>;
1251
1252        /// Take a finished `fetch_plain_tree`'s entries, by transfer id. Empty
1253        /// if it failed or has already been taken.
1254        fn take_plain_tree(self: &Session, transfer: u32) -> Vec<PlainEntry>;
1255
1256        /// Fetch a plain file's cover into `local_path`, by the file's own id,
1257        /// without blocking: as `fetch_artwork`.
1258        fn fetch_plain_artwork(
1259            self: &Session,
1260            device_number: u8,
1261            slot: Slot,
1262            file_id: u32,
1263            local_path: &str,
1264        ) -> Result<u32>;
1265
1266        /// Fetch a plain file head first, as `fetch_file_streaming` does a
1267        /// path, by its id: a plain file has no path, and is opened by the two
1268        /// numbers its track info carries.
1269        fn fetch_plain_file_streaming(
1270            self: &Session,
1271            device_number: u8,
1272            slot: Slot,
1273            file_id: u32,
1274            local_path: &str,
1275            head_bytes: u32,
1276        ) -> Result<u32>;
1277
1278        /// Take the bytes of a finished preview fetch, by transfer id.
1279        ///
1280        /// Empty if it failed or has already been taken. 900 bytes on success:
1281        /// `PWAV` as (height, shade) pairs, then the tiny `PWV2`.
1282        fn take_waveform_preview(self: &Session, transfer: u32) -> Vec<u8>;
1283
1284        /// Fetch a track's artwork into `local_path`.
1285        ///
1286        /// Returns a transfer id and does **not** block: the answer arrives as
1287        /// a `TransferDone` event carrying that id and the path.
1288        ///
1289        /// A host asks for these by the hundred — a 651-track medium has some
1290        /// six hundred distinct covers — so a blocking call would freeze a UI
1291        /// for six hundred round trips. They are queued onto one connection
1292        /// and answered in order.
1293        ///
1294        /// **Over dbserver, not NFS.** Two full load-and-play captures contain
1295        /// LOOKUPs for audio files and not one image; asking NFS for covers
1296        /// works for the first hundred and then fails wholesale, because
1297        /// walking `PIONEER/Artwork/000NN` per image churns the player's
1298        /// filehandle table until it answers `NFSERR_STALE` to handles a
1299        /// millisecond old (F28).
1300        fn fetch_artwork(
1301            self: &Session,
1302            device_number: u8,
1303            slot: Slot,
1304            artwork_id: u32,
1305            local_path: &str,
1306        ) -> Result<u32>;
1307
1308        /// The device number a MAC currently holds, or zero.
1309        ///
1310        /// A player's *number* can be reassigned while its MAC cannot, so a
1311        /// host that keeps a request across time should hold the MAC and
1312        /// resolve it here rather than cache the number.
1313        fn device_number_of(self: &Session, mac: &str) -> u8;
1314
1315        /// Fetch a player's `export.pdb`, the database a browse is built from.
1316        ///
1317        /// The same contract as `fetch_file`; this is the path a host does not
1318        /// have to know.
1319        fn fetch_database(
1320            self: &Session,
1321            device_number: u8,
1322            slot: Slot,
1323            local_path: &str,
1324        ) -> Result<u32>;
1325    }
1326
1327    extern "Rust" {
1328        /// A running server: our media, offered to real players.
1329        type Server;
1330
1331        /// Start serving. Throws on failure, with the reason.
1332        ///
1333        /// **Needs UDP/111**, which is privileged: run as root, or on Linux
1334        /// set `net.ipv4.ip_unprivileged_port_start=111`. Without it a deck
1335        /// retries `GETPORT` once a second for ever and never finds us (F46).
1336        fn serve(config: &ServeConfig) -> Result<Box<Server>>;
1337
1338        /// What this server is doing.
1339        fn status(self: &Server) -> ServeStatus;
1340
1341        /// Stop serving, ejecting the media first.
1342        ///
1343        /// Not the same as dropping it. A deck reading our files has a mount
1344        /// open, and sockets that simply vanish leave it retrying against
1345        /// nothing; ejecting walks each slot through the unmounting states a
1346        /// consumer waits for before the slot goes empty (F20).
1347        fn stop(self: &mut Server);
1348    }
1349}
1350
1351pub use ffi::{
1352    Config, Device, DeviceKind, Event, EventKind, MediaInfo, Metadata, NetworkInterface,
1353    PdbContents, PdbNamed, PdbPlaylist, PdbTrack, PlainEntry, PlayState, Player, Row, ServeConfig,
1354    ServeConsumer, ServeStatus, ServedSlot, Slot,
1355};
1356pub use serve::{Server, serve};
1357
1358/// The slot the library receives for one C++ named, for tests.
1359#[doc(hidden)]
1360#[must_use]
1361pub fn slot_back_for_test(slot: Slot) -> prolink_proto::Slot {
1362    convert::slot_back(slot)
1363}
1364
1365/// A `TransferDone` event as the transfer path builds it, for tests.
1366#[doc(hidden)]
1367#[must_use]
1368pub fn transfer_done_for_test(id: u32, path: &str, failure: Option<&str>) -> Event {
1369    let mut event = convert::plain(EventKind::TransferDone, 0, 0);
1370    event.transfer = id;
1371    path.clone_into(&mut event.path);
1372    if let Some(reason) = failure {
1373        event.ok = false;
1374        reason.clone_into(&mut event.detail);
1375    }
1376    event
1377}
1378
1379/// A player we have heard beats from but no status, for tests.
1380#[doc(hidden)]
1381#[must_use]
1382pub fn empty_player_for_test() -> Player {
1383    convert::player(&prolink::PlayerState {
1384        device: prolink::DeviceNumber::ONE,
1385        name: prolink::DeviceName::default(),
1386        beat: None,
1387        status: None,
1388    })
1389}
1390
1391/// One browse row, for tests that cannot reach a deck.
1392///
1393/// The two live marks a server puts on a track row are the thing most worth
1394/// pinning, and a test cannot get one off the network on a build machine.
1395#[doc(hidden)]
1396#[must_use]
1397pub fn row_for_test(item: &prolink_proto::dbserver::MenuItem) -> Row {
1398    convert::row(item)
1399}
1400pub use anlz::{read_anlz, read_anlz_preview};
1401pub use pdb::{read_pdb, read_pdb_bytes};
1402pub use session::{default_config, interfaces, open};