From 157c2c0a0409a3c9b7e7ecf2dd6dd1fe037b88da Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Sun, 27 Sep 2026 20:06:09 +0200 Subject: [PATCH] Fixed issues with OneLibrary export --- CLAUDE.md | 51 ++++- backend/konduktor-sidecar.spec | 5 +- .../konduktor/adapters/onelibrary/adapter.py | 2 +- .../adapters/onelibrary/capabilities.py | 4 +- .../konduktor/adapters/onelibrary/export.py | 140 +++++++++---- .../konduktor/adapters/onelibrary/store.py | 44 ++++- .../konduktor/adapters/rekordbox/adapter.py | 3 +- .../adapters/rekordbox/anlz_writer.py | 134 ++++++++++++- .../konduktor/adapters/rekordbox/artwork.py | 56 ++++++ .../konduktor/adapters/rekordbox/export.py | 40 +++- .../konduktor/adapters/rekordbox/palette.py | 93 +++++++++ .../adapters/rekordbox/projection.py | 8 +- backend/konduktor/adapters/rekordbox/store.py | 26 ++- .../konduktor/adapters/rekordbox/timebase.py | 64 ++++++ backend/konduktor/core/cue_colors.py | 33 ++++ backend/konduktor/core/export.py | 5 + backend/konduktor/core/waveform.py | 149 +++++++++++--- backend/konduktor/exporter.py | 11 ++ backend/requirements.txt | 2 + backend/test_export_pioneer.py | 186 +++++++++++++++++- backend/test_onelibrary_adapter.py | 18 +- backend/test_rekordbox_fidelity.py | 13 +- frontend/package.json | 2 +- frontend/src/lib/cues.ts | 3 +- 24 files changed, 981 insertions(+), 111 deletions(-) create mode 100644 backend/konduktor/adapters/rekordbox/artwork.py create mode 100644 backend/konduktor/adapters/rekordbox/palette.py create mode 100644 backend/konduktor/adapters/rekordbox/timebase.py create mode 100644 backend/konduktor/core/cue_colors.py diff --git a/CLAUDE.md b/CLAUDE.md index f5942b5..2d6e996 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1022,9 +1022,54 @@ that number and nothing else — everything derives from it: first marker on the first DOWNBEAT — the generic first marker is bar 1 — and `beats_from_markers` writes the lead-in beats back, numbered as they were; before this every bar of such a track landed two beats early, on import to - Traktor as well as on export. Still NOT written: the `.EXT`/`.2EX` waveforms - (song-list preview, scrolling deck waveform) and artwork (`image` table + - `PIONEER/Artwork/00001/a.jpg`, `b.jpg` and `_m` variants). `adapters/rekordbox/export.py` writes a `master.db` and + Traktor as well as on export. **Rekordbox's clock runs 1105 samples (~25 ms) + behind the decoded audio on MP3/AAC** — the codec delay it does not trim; + measured +25.0 ms on 16 MP3s, +24.5 on 4 M4As, 0 on WAV. The generic model is + the decoded time base, so `adapters/rekordbox/timebase.py` is applied at EVERY + Pioneer boundary: both exporters add it, the OneLibrary reader and the + Rekordbox adapter subtract it on read and add it on write (`set_cue`, + `set_cue_type`, grid save). Without it every cue sat 25 ms early in rekordbox. + **Drawn waveforms** (`.EXT` `PWV3`/`PWV5`, `.2EX` `PWV7`/`PWV6`/`PWVC`) are + generated from one decode (`core/waveform.py`: 150 frames/s, bands split at + 200 Hz / 2.5 kHz) with constants fitted to rekordbox's own files for 12 local + tracks and checked on 5 held-out ones (per-band correlation 0.77-0.96). + **rekordbox 7's SONG LIST draws `PWV6` — and only when `content.contentLink` + is set.** Both measured by bisecting a rekordbox-written stick: removing a + track's `PWV6` emptied its row (removing `PWV4` changed nothing), and blanking + its `contentLink` alone turned the row plain blue with a "?" beside CUE — what + every Konduktor-exported row showed while the exporter left it NULL. It now + writes rekordbox's 788224 (beside `analysedBits` 41; meaning unknown). + `masterDbId`/`masterContentId` do NOT matter, so no link to a rekordbox + collection is claimed. `PWV4` is still written (every rekordbox file has it); + its low/mid/high bytes cannot be matched per column (b4/b5 are sampled + at one instant: column-to-column correlation 0.05/0.16), so each byte is a + QUANTILE MAP fitted to rekordbox's distribution (`_PWV4_MAPS`); smoothed, it + tracks rekordbox's at 0.5-0.99. A very loud master draws smaller than in + rekordbox, whose PWV4 keeps some absolute level. rekordbox reads 200+ covers + from one `Artwork/00001` folder (verified on a 207-track export). Decoding is + **PyAV** first (FFmpeg in its wheel: AAC on every OS; measured to start on the + same sample as librosa) with librosa as fallback. **Cue colour on export** is + what Konduktor SHOWS (`core/cue_colors.py`, mirroring `lib/cues.ts`): a stored + colour, else the type's — blue cue, green loop — because "unset" makes + rekordbox draw its own defaults (green/orange). **rekordbox draws a hot cue + from its palette CODE** (`PCP2` byte 44, before the RGB; `djmdCue.ColorTableIndex` + in master.db), not the RGB — `adapters/rekordbox/palette.py` holds the 16-swatch + table MEASURED from a rekordbox 7 export (one swatch, ~0x12 teal-green, still + unmeasured). Type colours map by intent (cue -> light blue 0x05, loop -> green + 0x16), anything else to the nearest hue; the palette has NO white, so a grid + companion is code 0 + RGB white (what rekordbox draws for it: unverified). The + `master.db` exporter still writes no cue colour (generic `set_cue` has none). + **Artwork** (`adapters/rekordbox/artwork.py`, Pillow), measured on a rekordbox 7 + export: `PIONEER/Artwork/00001/{a,b}.jpg` at 80 px and `_m` at 240 px, `a` + byte-identical to `b`, baseline JPEG q85 4:2:0, non-square art LETTERBOXED onto + black (a crop or stretch is visibly wrong); `image.path` names the `b` file and + `content.image_id` points at it; one image per track, never shared. The runner + carries each cover as `ExportTrack.art` from `LibraryAdapter.cover_art` — not + re-read from the copied file, since a library's art is not always embedded. + The OneLibrary READER now serves `cover_art` too (the `_m` file). How rekordbox + itself splits a large library across `Artwork/000NN` folders is unknown; one + folder of 207 was verified to load in full. + The `master.db` target still writes no artwork. `adapters/rekordbox/export.py` writes a `master.db` and **replays cues through the ordinary `RekordboxAdapter.set_cue`**, so it inherits `_sync_content_cue`, the sparse `Kind` bank and their tests rather than redefining them; its ANLZ files go under a **`share/` directory beside diff --git a/backend/konduktor-sidecar.spec b/backend/konduktor-sidecar.spec index 4ed1450..d322fe3 100644 --- a/backend/konduktor-sidecar.spec +++ b/backend/konduktor-sidecar.spec @@ -20,8 +20,9 @@ binaries = [] for pkg in ("uvicorn", "xsdata", "dulwich"): hiddenimports += collect_submodules(pkg) -# Native standard extras — grab modules + shared libs + any data. -for pkg in ("uvloop", "httptools", "websockets"): +# Native standard extras — grab modules + shared libs + any data. PyAV (`av`) +# carries FFmpeg's shared libraries, which the export's waveform analysis needs. +for pkg in ("uvloop", "httptools", "websockets", "av"): d, b, h = collect_all(pkg) datas += d binaries += b diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index d8d0e1d..47aefd8 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -264,7 +264,7 @@ class OneLibraryAdapter: self._refuse("Editing cover art") def cover_art(self, track_id: str) -> tuple[bytes, str] | None: - return None + return self._store.cover_art(track_id) def create_playlist(self, name: str, parent_id: str | None = None) -> str: self._refuse("Creating playlists") diff --git a/backend/konduktor/adapters/onelibrary/capabilities.py b/backend/konduktor/adapters/onelibrary/capabilities.py index fba47d9..5b79ee9 100644 --- a/backend/konduktor/adapters/onelibrary/capabilities.py +++ b/backend/konduktor/adapters/onelibrary/capabilities.py @@ -70,8 +70,8 @@ def capabilities_for(device_name: str | None = None, version: str | None = None) rating_max=5, # stored 0-5 directly, as in master.db editable_fields=[], media_kinds=["audio"], - # The drive has an `image` table and an Artwork folder, but nothing - # is wired up to read them yet. + # `artwork` gates EDITING, and a drive is read-only here. Reading + # works: `store.cover_art` follows `content.image_id` -> `image.path`. artwork=False, artwork_note=None, ), diff --git a/backend/konduktor/adapters/onelibrary/export.py b/backend/konduktor/adapters/onelibrary/export.py index 86c0602..701a34e 100644 --- a/backend/konduktor/adapters/onelibrary/export.py +++ b/backend/konduktor/adapters/onelibrary/export.py @@ -43,7 +43,9 @@ from pathlib import Path from ...core import waveform from ...core.export import ExportPayload, ExportTrack, WrittenLibrary +from ...core.cue_colors import effective_color from ..rekordbox import anlz_writer as W +from ..rekordbox import artwork, palette, timebase from ..rekordbox.beatgrid import beats_from_markers from ..rekordbox.projection import render_key from .capabilities import capabilities_for @@ -60,6 +62,13 @@ SEED = SCHEMA.with_name("seed.sql") DB_VERSION = "1000" #: Seen on every track of a real export; semantics undocumented, copied as-is. ANALYSED_BITS = 41 +#: `content.contentLink`, as rekordbox 7 writes it beside `analysedBits` 41 (a +#: re-analysed track carried 1902336 beside 105; what the bits mean is unknown). +#: NOT optional: measured by blanking it on one track of a rekordbox-written +#: stick — that row's song-list preview fell back to plain blue and gained a "?" +#: beside CUE, exactly as every row of Konduktor's exports did while it was NULL. +#: `masterDbId`/`masterContentId` were cleared the same way and changed nothing. +CONTENT_LINK = 788224 OTHER_PLAYLIST = "Other" @@ -102,9 +111,13 @@ class OneLibraryExporter: yes to. Leaving the adapter's answer here would have the UI report that the thing it just wrote cannot be written. """ - return capabilities_for().model_copy( - update={"writable": True, "readonly_cause": None} - ) + caps = capabilities_for() + # An exported drive CARRIES artwork (`_write_art`); the adapter's False + # means "cannot edit a plugged-in drive's art", a different question. + return caps.model_copy(update={ + "writable": True, "readonly_cause": None, + "tracks": caps.tracks.model_copy(update={"artwork": True}), + }) def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary: import sqlcipher3.dbapi2 as sqlcipher @@ -141,6 +154,9 @@ class OneLibraryExporter: def _fill(self, con, payload: ExportPayload, root: Path) -> list[Path]: lookups = {name: {} for name in ("artist", "album", "genre", "label", "key")} + # Image ids are handed out in track order, one per track that HAS art — + # rekordbox does not share an image between tracks, even identical ones. + lookups["image"] = {"next": 0} written: list[Path] = [] by_source: dict[str, int] = {} @@ -188,16 +204,17 @@ class OneLibraryExporter: except OSError: size = 0 sample_rate, bit_depth = _audio_format(item.destination) + image_id, art_files = self._write_art(con, item, root, lookups["image"]) con.execute( "INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, " - "trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, " + "trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, image_id, " "djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, " "fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, " "isKuvoDeliverStatusOn, masterDbId, masterContentId, " - "analysisDataFilePath, analysedBits, hasModified, cueUpdateCount, " + "analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, " "analysisDataUpdateCount, informationUpdateCount) " - "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", ( content_id, track.title, (track.title or "").lower(), int(round((track.bpm or 0) * 100)) or None, track.length, @@ -211,48 +228,100 @@ class OneLibraryExporter: # where the deck expects "Cm". Rendered from the parsed wheel. self._lookup(con, "key", lookups["key"], render_key(track.key_wheel, track.key_mode)), + image_id, track.comment, track.rating or 0, track.release_date, date.today().isoformat(), rel, item.destination.name, size, # kbps, as every Pioneer library stores it; the generic model # carries bits per second. _file_type(item.destination), _kbps(track.bitrate), bit_depth, sample_rate, 1, 1, 0, content_id, - anlz_rel, ANALYSED_BITS, 0, 0, 0, 0, + anlz_rel, ANALYSED_BITS, CONTENT_LINK, 0, 0, 0, 0, ), ) - return self._write_anlz(item, rel, root / anlz_rel.lstrip("/")) + return art_files + self._write_anlz(item, rel, root / anlz_rel.lstrip("/")) + + # ---- artwork ------------------------------------------------------------- + + @staticmethod + def _write_art(con, item: ExportTrack, root: Path, counter: dict) -> tuple[int | None, list[Path]]: + """One track's cover: four JPEGs and an `image` row, as rekordbox 7 writes. + + `PIONEER/Artwork/00001/` holds `a.jpg` / `a_m.jpg` and a byte- + identical `b.jpg` / `b_m.jpg` (80 and 240 px); `image.path` names the + `b` file and `content.image_id` points at the row. rekordbox's own export + writes both letters — the `a` pair presumably for the legacy `export.pdb` + readers — so both are written here too. + + Everything goes in folder `00001`. How rekordbox splits a large library + across folders is not known (the reference export has 6 images); a single + folder is what it demonstrably reads. + """ + if not item.art: + return None, [] + jpegs = artwork.pioneer_jpegs(item.art[0]) + if jpegs is None: + return None, [] + counter["next"] += 1 + n = counter["next"] + folder = root / "PIONEER" / "Artwork" / "00001" + folder.mkdir(parents=True, exist_ok=True) + small, medium = jpegs + files = [] + for letter in ("a", "b"): + for suffix, data in (("", small), ("_m", medium)): + path = folder / f"{letter}{n}{suffix}.jpg" + path.write_bytes(data) + files.append(path) + con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)", + (n, f"/PIONEER/Artwork/00001/b{n}.jpg")) + return n, files # ---- the analysis files -------------------------------------------------- def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]: - """The `.DAT` and the `.EXT`, always both, as rekordbox writes them. + """The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 writes them. - Both files, and every cue list in each, even for a track with no cues: - rekordbox never produces a track without them, and `PCO2` — the complete - list, which readers prefer — lives only in the `.EXT`. + All three, and every cue list, even for a track with no cues: rekordbox + never produces a track without them, and `PCO2` — the complete list, + which readers prefer — lives only in the `.EXT`. **The `.DAT` must carry `PVBR` and the preview waveforms**, or rekordbox - shows neither the grid nor the cues (see `anlz_writer`). Tag order is - rekordbox's: PPTH, PVBR, PQTZ, PWAV, PWV2, PCOB, PCOB. + shows neither the grid nor the cues (see `anlz_writer`). The `.EXT` and + `.2EX` waveforms only affect drawing: the song-list preview and the + deck's scrolling waveform. Tag order is rekordbox's in each file: + .DAT PPTH PVBR PQTZ PWAV PWV2 PCOB PCOB + .EXT PPTH PWV3 PCOB PCOB PCO2 PCO2 PWV5 PWV4 + .2EX PPTH PWV7 PWV6 PWVC + An undecodable file still gets the `.DAT` (with a flat preview) and the + `.EXT` cue lists — its grid and cues must show — but no drawn waveforms. """ - measured = waveform.columns(item.destination, 400) + # rekordbox's clock runs ~25 ms behind the decoded audio on MP3/AAC (see + # `timebase`): beats and cues are computed in the decoded time base and + # shifted as they are packed, and the waveform frames are measured with + # the same lead so they line up with the beats. + off = timebase.offset(item.destination) + measured = waveform.analyse(item.destination, lead=off) # The DECODED length where there is one: `Track.length` is whole seconds # rounded down, and a grid expanded to it loses the track's last beat. beats = self._beats(item, measured.duration if measured else None) - cues = self._cue_dicts(item, beats) - previews = (W.preview_tags(measured.rms, measured.brightness) if measured - else W.flat_preview_tags()) + cues = self._cue_dicts(item, beats, off) + if measured: + previews = W.preview_tags(measured.columns.rms, measured.columns.brightness) + ext_waves, two_ex = W.waveform_tags(measured.frames.bands) + else: + previews, ext_waves, two_ex = W.flat_preview_tags(), [], [] tags = [W.path_tag(rel), W.vbr_tag(W.mp3_samples(item.destination))] if beats: - tags.append(W.beatgrid_tag(beats)) + tags.append(W.beatgrid_tag([(n, bpm, timebase.to_pioneer(t, off)) + for n, bpm, t in beats])) tags += previews tags += W.cue_tags(cues, extended=False) - return [ - W.write_anlz(dat, tags), - W.write_anlz(dat.with_suffix(".EXT"), - [W.path_tag(rel), *W.cue_tags(cues, extended=True)]), - ] + ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]] + written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), ext)] + if two_ex: + written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex])) + return written @staticmethod def _beats(item: ExportTrack, duration: float | None = None) -> list[tuple[int, float, float]]: @@ -272,7 +341,7 @@ class OneLibraryExporter: return list(zip(nums, bpms, times)) @staticmethod - def _cue_dicts(item: ExportTrack, beats: list | None = None) -> list[dict]: + def _cue_dicts(item: ExportTrack, beats: list | None = None, off: float = 0.0) -> list[dict]: """Generic cues in the shape `anlz_writer` packs. Slot numbering is ANLZ's own: **dense 1-based**, 0 for a memory cue. @@ -283,12 +352,19 @@ class OneLibraryExporter: out: list[dict] = [] for cue in (item.cues.cues if item.cues else []): is_loop = cue.type == "loop" or cue.length > 0 + # A hot cue carries what Konduktor SHOWS — stored colour, else the + # type's (blue cue, green loop) — as a rekordbox palette CODE, which + # is what rekordbox draws from; "unset" draws its own defaults. A + # memory cue keeps rekordbox's own "unset". + code, rgb = palette.code_for(cue.color if cue.role == "memory" else effective_color(cue)) out.append({ "hot_cue": 0 if cue.role == "memory" or cue.slot is None else cue.slot + 1, "kind": 2 if is_loop else 1, - "time_ms": int(round(cue.start * 1000)), - "loop_ms": int(round((cue.start + cue.length) * 1000)) if is_loop else None, - "rgb": _rgb(cue.color), + "time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)), + "loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000)) + if is_loop else None), + "rgb": rgb, + "code": code, "beats": _loop_beats(cue.start, cue.length, beats or []) if is_loop else None, }) return out @@ -390,11 +466,3 @@ def _loop_beats(start: float, length: float, beats: list[tuple[int, float, float whole = round(count) return whole if whole >= 1 and abs(count - whole) < 0.05 else None - -def _rgb(color: str | None) -> tuple[int, int, int] | None: - if not color or not color.startswith("#") or len(color) != 7: - return None - try: - return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)) - except ValueError: - return None diff --git a/backend/konduktor/adapters/onelibrary/store.py b/backend/konduktor/adapters/onelibrary/store.py index 295d3ed..45ad774 100644 --- a/backend/konduktor/adapters/onelibrary/store.py +++ b/backend/konduktor/adapters/onelibrary/store.py @@ -25,6 +25,7 @@ from pathlib import Path from ...core.adapter import LibraryNotSupported, NotFound from ...core.model import CuePoint from . import beatgrid, cues as cue_reader +from ..rekordbox import timebase from .layout import DriveLayout log = logging.getLogger(__name__) @@ -148,6 +149,30 @@ class OneLibraryStore: def audio_path(self, track_id: str) -> Path | None: return self.layout.resolve(getattr(self.content(track_id), "path", None)) + def cover_art(self, track_id: str) -> tuple[bytes, str] | None: + """The track's artwork: `content.image_id` -> `image.path` -> the file. + + The row names the 80 px JPEG (`.../b.jpg`); a `_m` sibling at 240 px + sits beside it on every export seen, and is what is served — 80 px is a + CDJ browse thumbnail, too small for anything Konduktor draws. + """ + image_id = getattr(self.content(track_id), "image_id", None) + if not image_id: + return None + from pyrekordbox.devicelib_plus import models + + row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none() + small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None + if small is None: + return None + medium = small.with_name(small.stem + "_m" + small.suffix) + for path in (medium, small): + try: + return path.read_bytes(), "image/jpeg" + except OSError: + continue + return None + def all_audio_paths(self) -> list[str]: out: list[str] = [] for row in self.iter_content(): @@ -185,8 +210,9 @@ class OneLibraryStore: return None return cache[key] - def anlz_grid(self, track_id: str) -> tuple[list[float], list[float]] | None: - """The per-beat ``(times, bpms)`` from the track's `PQTZ` tag. + def anlz_grid(self, track_id: str) -> tuple[list[float], list[float], list[int]] | None: + """The per-beat ``(times, bpms, beat_in_bar)`` from the track's `PQTZ` + tag, in the DECODED time base (see `rekordbox.timebase`). `PQTZ` is in the `.DAT`, which is the cheap file — a grid read does not pay for the `.EXT`'s waveforms. @@ -194,7 +220,12 @@ class OneLibraryStore: anlz = self._anlz(track_id, extended=False) if anlz is None: return None - return beatgrid.beats_from_pqtz(anlz) + grid = beatgrid.beats_from_pqtz(anlz) + if grid is None: + return None + off = timebase.offset(self.audio_path(track_id)) + times, bpms, beats = grid + return [timebase.from_pioneer(t, off) for t in times], bpms, beats def cues(self, track_id: str) -> list[CuePoint]: """The track's cues, already generic. @@ -204,10 +235,15 @@ class OneLibraryStore: only mean anything once merged across two files, and handing that to the projection would put ANLZ knowledge on both sides of the boundary. """ - return cue_reader.cues_from_anlz( + cues = cue_reader.cues_from_anlz( self._anlz(track_id, extended=False), self._anlz(track_id, extended=True), ) + # Positions are stored on rekordbox's clock; the generic model is the + # decoded audio's. A loop keeps its length. + off = timebase.offset(self.audio_path(track_id)) + return [c.model_copy(update={"start": timebase.from_pioneer(c.start, off)}) + for c in cues] if off else cues # ---- playlists ------------------------------------------------------- def playlists(self) -> list: diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index d88665f..975969d 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -124,7 +124,8 @@ class RekordboxAdapter: if self._index.get(track_id) is None: return None cues = projection.to_track_cues( - self._store.cues(track_id), self._store.anlz_grid(track_id) + self._store.cues(track_id), self._store.anlz_grid(track_id), + self._store.time_offset(track_id), ) # The track projection carries an APPROXIMATE grid_marker_count until the # grid is actually read (see projection.to_track). This is that moment — diff --git a/backend/konduktor/adapters/rekordbox/anlz_writer.py b/backend/konduktor/adapters/rekordbox/anlz_writer.py index bb77418..06d07d3 100644 --- a/backend/konduktor/adapters/rekordbox/anlz_writer.py +++ b/backend/konduktor/adapters/rekordbox/anlz_writer.py @@ -70,7 +70,8 @@ _TAG_PREFIX = 12 #: Each tag counts a different number of its leading CONTENT fields as part of #: its header. Read off `pyrekordbox`'s own tag classes rather than guessed. _LEN_HEADER = {"PPTH": 16, "PQTZ": 24, "PCOB": 24, "PCO2": 20, - "PVBR": 16, "PWAV": 20, "PWV2": 20} + "PVBR": 16, "PWAV": 20, "PWV2": 20, + "PWV3": 24, "PWV5": 24, "PWV4": 24, "PWV7": 24, "PWV6": 20, "PWVC": 14} def _wrap(kind: str, body: bytes) -> bytes: @@ -181,6 +182,128 @@ def preview_tags(rms, brightness) -> list[bytes]: ] +# ---- the detail and 3-band waveforms (`.EXT` / `.2EX`) ------------------------- +# +# These only affect DRAWING — rekordbox shows the grid and cues without them — but +# without them its song list has no preview and its deck draws a flat blue line, +# and it warns the device was "analyzed by an older version". All constants are +# fitted against rekordbox 7's own files for 12 local tracks, measured through +# `core.waveform` exactly as the exporter measures (per-band mean error ~8 on the +# 0-127 scale). rekordbox 7's song list draws `PWV6` — but ONLY for a track +# whose `content.contentLink` is set (see the OneLibrary exporter); with it NULL +# the row is plain blue whatever the files hold. `PWV4` is written by +# distribution matching, not per-column fitting (see `_PWV4_MAPS`). + +#: PWV7 byte per band = top * (energy / its 99.5th percentile) ** gamma. +_PWV7 = ((88, 0.6), (92, 0.9), (68, 1.7)) # low, mid, high +#: PWV6: the same, over 1200 overview columns (column = mean of its frames). +_PWV6 = ((40, 0.5), (34, 0.5), (34, 0.5)) +#: PWVC: a per-band gain, = C / (the band's 99.5th percentile), floored at 80 — +#: rekordbox's own values follow this to about +/-20%. What rekordbox does with +#: it is not known; it is reproduced rather than invented. +_PWVC_C, _PWVC_FLOOR = (20763.0, 15220.0, 12571.0), 80 +#: PWV3/PWV5 height (5 bits) from overall energy: 28 * x ** 1.5. +_HEIGHT = (28, 1.5) +#: PWV5 colour (3 bits each) from each band's SHARE of the frame's energy. +_RGB = ((8.47, 0.54), (7.60, 0.47), (13.78, 1.83)) # red<-low, green<-mid, blue<-high +_OVERVIEW_COLUMNS = 1200 + +#: PWV4 — the 6-byte colour overview. NOT what rekordbox 7's song list draws +#: (that is PWV6: removing PWV6 from a rekordbox-written track left its row +#: empty, removing PWV4 changed nothing); written because every rekordbox file +#: carries it and its RGB mode and older players may read it. Per column: b0 overall level, b1 a +#: companion of b0, b2 the height, b3/b4/b5 the low/mid/high (red/green/blue) +#: levels. Two measured facts shape it: b4 and b5 are sampled at ONE instant per +#: column (their column-to-column correlation is 0.05 and 0.16, against ~0.6 for +#: the rest), and rekordbox's per-column bytes are too jumpy to reproduce one by +#: one — so each byte is a QUANTILE MAP, (normalised measurement knots, byte +#: knots), fitted on 12 tracks so the distribution matches rekordbox's (held-out +#: medians within a few levels, the same spiky top end). b2 and b1 follow from +#: the others by linear fits on rekordbox's own bytes (mean error 10 and 12). +_PWV4_MAPS = { + "b0": ((0.0, 0.1027, 0.1843, 0.3094, 0.3971, 0.4832, 0.5759, 0.6569, 0.731, 0.8102, 0.8973, 0.9419, 0.971, 1.1784), + (0, 17, 28, 45, 56, 62, 65, 69, 74, 115, 127, 127, 127, 127)), + "b3": ((0.0, 0.0135, 0.0473, 0.1407, 0.26, 0.3841, 0.5027, 0.5911, 0.6686, 0.7617, 0.8646, 0.9209, 0.9645, 1.1825), + (0, 1, 4, 15, 24.7, 37, 44, 54, 62, 68, 89, 107, 120, 127)), + "b4": ((0.0, 0.0305, 0.0654, 0.1307, 0.1855, 0.2325, 0.2819, 0.3342, 0.3977, 0.4809, 0.6036, 0.708, 0.8719, 1.2804), + (0, 2, 7, 12, 17, 21, 25, 30, 35, 43, 62, 109, 127, 127)), + "b5": ((0.0, 0.0077, 0.0223, 0.0511, 0.09, 0.1298, 0.1809, 0.2427, 0.3167, 0.4143, 0.5749, 0.7209, 0.863, 1.4313), + (0, 1, 4, 7, 10, 12, 16, 20, 24, 31, 60, 127, 127, 127)), +} + + +def _pwv4(bands) -> bytes: + import numpy as np + + full = np.sqrt((bands ** 2).sum(axis=1)) + x = np.column_stack([bands, full]) # low, mid, high, full + cols = [idx for idx in np.array_split(np.arange(len(x)), _OVERVIEW_COLUMNS)] + mean = np.array([x[i].mean(axis=0) if len(i) else np.zeros(4) for i in cols]) + instant = np.array([x[i[len(i) // 2]] if len(i) else np.zeros(4) for i in cols]) + + def mapped(values, key): + ref = float(np.percentile(values, 99.5)) or 1.0 + knots_x, knots_y = _PWV4_MAPS[key] + return np.clip(np.round(np.interp(values / ref, knots_x, knots_y)), 0, 127).astype(int) + + b0, b3 = mapped(mean[:, 3], "b0"), mapped(mean[:, 0], "b3") + b4, b5 = mapped(instant[:, 1], "b4"), mapped(instant[:, 2], "b5") + b2 = np.clip(np.round(0.83 * np.maximum(b3, np.maximum(b4, b5)) + 11.6), 0, 127).astype(int) + b1 = np.clip(np.round(235.2 - 0.77 * b0), 0, 255).astype(int) + return np.column_stack([b0, b1, b2, b3, b4, b5]).astype(np.uint8).tobytes() + + +def _norm(x, top: float, gamma: float, cap: int): + import numpy as np + + ref = float(np.percentile(x, 99.5)) or 1.0 + return np.clip(np.round(top * np.clip(x / ref, 0, None) ** gamma), 0, cap).astype(int) + + +def waveform_tags(bands) -> tuple[list[bytes], list[bytes]]: + """(`.EXT` tags, `.2EX` tags) from 150-per-second low/mid/high band energy. + + `.EXT`: `PWV3` (detail, 1 byte: whiteness << 5 | height), `PWV5` (detail + colour, 2 bytes: rrr ggg bbb hhhhh 00) and `PWV4` (the RGB-mode colour + overview, 1200 x 6 bytes — see `_PWV4_MAPS`). `.2EX`: `PWV7` (3-band detail, one + byte per band), `PWV6` (3-band overview, 1200 columns) and `PWVC`. The frames + must already be on rekordbox's clock (`waveform.analyse(lead=offset)`). + """ + import numpy as np + + bands = np.asarray(bands, dtype=float) + n = len(bands) + full = np.sqrt((bands ** 2).sum(axis=1)) + share = bands / (bands.sum(axis=1, keepdims=True) + 1e-12) + + height = _norm(full, *_HEIGHT, 31) + white = np.clip(np.round(2.5 + 10.0 * share[:, 2]), 0, 7).astype(int) + pwv3 = bytes(int((w << 5) | h) for w, h in zip(white, height)) + rgb = [np.clip(np.round(k * share[:, i] + c), 0, 7).astype(int) + for i, (k, c) in enumerate(_RGB)] + pwv5 = b"".join(struct.pack(">H", (int(r) << 13) | (int(g) << 10) | (int(b) << 7) | (int(h) << 2)) + for r, g, b, h in zip(*rgb, height)) + + pwv7 = np.stack([_norm(bands[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV7)], axis=1) + cols = np.array([bands[idx].mean(axis=0) if len(idx) else np.zeros(3) + for idx in np.array_split(np.arange(n), _OVERVIEW_COLUMNS)]) + pwv6 = np.stack([_norm(cols[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV6)], axis=1) + gains = [max(_PWVC_FLOOR, int(round(c / (float(np.percentile(bands[:, i], 99.5)) or 1.0)))) + for i, c in enumerate(_PWVC_C)] + + ext = [ + _wrap("PWV3", struct.pack(">III", 1, n, 0x00960000) + pwv3), + _wrap("PWV5", struct.pack(">III", 2, n, 0x00960305) + pwv5), + _wrap("PWV4", struct.pack(">III", 6, _OVERVIEW_COLUMNS, 0) + _pwv4(bands)), + ] + two_ex = [ + _wrap("PWV7", struct.pack(">III", 3, n, 0x00960000) + pwv7.astype(np.uint8).tobytes()), + _wrap("PWV6", struct.pack(">II", 3, _OVERVIEW_COLUMNS) + pwv6.astype(np.uint8).tobytes()), + _wrap("PWVC", struct.pack(">H", 0) + struct.pack(">HHH", *[min(g, 0xFFFF) for g in gains])), + ] + return ext, two_ex + + def flat_preview_tags() -> list[bytes]: """Empty previews, for a file nothing could decode, so the grid and cues can still show. That an all-zero preview satisfies rekordbox is an assumption, @@ -189,7 +312,7 @@ def flat_preview_tags() -> list[bytes]: def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None, - rgb: tuple[int, int, int] | None, beats: int | None) -> bytes: + rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> bytes: """One `PCP2` entry, byte-for-byte as rekordbox 7 writes it. Two constants in here are rekordbox's, not the documented struct's: the @@ -204,7 +327,9 @@ def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None, b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind, 1000, int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms), 0, 1, beats or 0, 1 if beats else 0, len(comment), - ) + comment + struct.pack(">4B", 0, red, green, blue) + bytes( + # The colour is the palette CODE, then RGB: rekordbox draws from the code + # (`palette`); a code of 0 draws its default colour whatever the RGB says. + ) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes( PCP2_ENTRY_LEN - 48 - len(comment) ) @@ -243,7 +368,8 @@ def _pcob(cue_type: int, chosen: list[dict]) -> bytes: def _pco2(cue_type: int, chosen: list[dict]) -> bytes: blob = b"".join( _pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"], - loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats")) + loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"), + code=c.get("code", 0)) for c in chosen ) return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob) diff --git a/backend/konduktor/adapters/rekordbox/artwork.py b/backend/konduktor/adapters/rekordbox/artwork.py new file mode 100644 index 0000000..ba4a8a1 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/artwork.py @@ -0,0 +1,56 @@ +"""Cover art the way a Pioneer library stores it: two small square JPEGs. + +Measured on a rekordbox 7 USB export rather than assumed: + + * two sizes per image — **80 x 80** (`.jpg`) and **240 x 240** (`_m.jpg`); + * **baseline JPEG at quality 85, 4:2:0** — its quantisation table is libjpeg's + standard table scaled to exactly 85, with no EXIF and a plain JFIF header; + * a non-square cover is **letterboxed onto black**, aspect kept and centred. + Motorola's 4112 x 1112 art matches rekordbox's own to a mean of 1.8 levels + that way; a centre crop is off by 26, a stretch by 19.5. + +Where the files go and how the database points at them is the target's business +(a OneLibrary drive: `PIONEER/Artwork/00001/`, see its exporter). +""" +from __future__ import annotations + +import io +import logging + +log = logging.getLogger(__name__) + +SMALL, MEDIUM = 80, 240 +_QUALITY = 85 + + +def _square(image, size: int): + from PIL import Image + + fitted = image.copy() + fitted.thumbnail((size, size), Image.BICUBIC) # the closest of Pillow's filters + canvas = Image.new("RGB", (size, size), (0, 0, 0)) + canvas.paste(fitted, ((size - fitted.width) // 2, (size - fitted.height) // 2)) + return canvas + + +def _jpeg(image) -> bytes: + out = io.BytesIO() + # subsampling=2 is 4:2:0; progressive/optimize off = the baseline rekordbox writes. + image.save(out, format="JPEG", quality=_QUALITY, subsampling=2, + progressive=False, optimize=False) + return out.getvalue() + + +def pioneer_jpegs(data: bytes) -> tuple[bytes, bytes] | None: + """(80 px JPEG, 240 px JPEG) from any image the source library holds, or None + when it cannot be read — a bad cover costs the artwork, not the export.""" + try: + from PIL import Image + + with Image.open(io.BytesIO(data)) as src: + src.load() + rgb = src.convert("RGB") # PNG alpha / palette / CMYK -> RGB + except Exception as ex: # noqa: BLE001 — any unreadable image + log.warning("could not read cover art (%s); exporting without it", ex) + return None + return _jpeg(_square(rgb, SMALL)), _jpeg(_square(rgb, MEDIUM)) diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py index 6652fbe..df5c3b2 100644 --- a/backend/konduktor/adapters/rekordbox/export.py +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -59,6 +59,7 @@ from sqlalchemy import text from ...core.export import ExportPayload, ExportTrack, WrittenLibrary from ...core import waveform from . import anlz_writer as W +from . import timebase from .beatgrid import beats_from_markers from .capabilities import capabilities_for from .cue_types import kind_for @@ -309,26 +310,45 @@ class RekordboxExporter: content.AnalysisUpdated = 1 db.flush() - # The same shape as a rekordbox-analysed track's `.DAT`: PVBR and the - # preview waveforms are what rekordbox needs before it shows a grid at - # all (measured on a OneLibrary stick; the same Pioneer file here), and - # the cue lists are present but EMPTY — master.db keeps cues in djmdCue. - measured = waveform.columns(item.destination, 400) - tags = [W.path_tag(str(item.destination)), W.vbr_tag(W.mp3_samples(item.destination))] + # The same three files as a rekordbox-analysed track. The `.DAT` needs + # PVBR and the preview waveforms before rekordbox shows a grid at all + # (measured on a OneLibrary stick; the same Pioneer file here); the + # `.EXT`/`.2EX` carry the drawn waveforms. Cue lists are present but + # EMPTY — master.db keeps cues in djmdCue. + off = timebase.offset(item.destination) + measured = waveform.analyse(item.destination, lead=off) + path = str(item.destination) + tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(item.destination))] markers = item.cues.grid_markers if item.cues else [] if markers: duration = ((measured.duration if measured else 0.0) or float(item.track.length or 0) or (markers[-1].start + 60.0)) nums, bpms, times = beats_from_markers(markers, duration) if nums: - tags.append(W.beatgrid_tag(list(zip(nums, bpms, times)))) - tags += (W.preview_tags(measured.rms, measured.brightness) if measured - else W.flat_preview_tags()) + # Onto rekordbox's clock (~25 ms behind on MP3/AAC — `timebase`). + # The cues need no such line: they are replayed through + # `set_cue`, which applies the same offset itself. + tags.append(W.beatgrid_tag( + [(n, bpm, timebase.to_pioneer(t, off)) for n, bpm, t in zip(nums, bpms, times)])) + if measured: + tags += W.preview_tags(measured.columns.rms, measured.columns.brightness) + ext_waves, two_ex = W.waveform_tags(measured.frames.bands) + else: + tags += W.flat_preview_tags() + ext_waves, two_ex = [], [] tags += W.cue_tags([], extended=False) # AnalysisDataPath is rooted at a `share` directory BESIDE master.db, # not at the library root — the read path joins it that way, and writing # it anywhere else produces a track whose grid silently reads as empty. - return [W.write_anlz(root / "share" / rel.lstrip("/"), tags)] + dat = root / "share" / rel.lstrip("/") + written = [ + W.write_anlz(dat, tags), + W.write_anlz(dat.with_suffix(".EXT"), [W.path_tag(path), *ext_waves[:1], + *W.cue_tags([], extended=True), *ext_waves[1:]]), + ] + if two_ex: + written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(path), *two_ex])) + return written # ---- playlists --------------------------------------------------------------- diff --git a/backend/konduktor/adapters/rekordbox/palette.py b/backend/konduktor/adapters/rekordbox/palette.py new file mode 100644 index 0000000..ca915af --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/palette.py @@ -0,0 +1,93 @@ +"""rekordbox's hot-cue colour palette: a generic `#RRGGBB` -> (palette code, RGB). + +**rekordbox draws a hot cue from its palette CODE, not from its RGB bytes.** An +export that wrote only RGB (code 0) had every cue drawn in rekordbox's defaults +— green cues, orange loops. The code is `PCP2`'s colour byte (offset 44, before +the RGB triple) in the ANLZ `.EXT`, and `djmdCue.ColorTableIndex` in `master.db`. + +The table was MEASURED, not recalled: 16 hot cues coloured through rekordbox 7's +own palette, one colour per pad, exported to a stick, and read back. Rekordbox +writes the palette's exact RGB beside each code. + + * One palette colour went unmeasured — the teal-green between 0x0E and 0x16 + (probably code 0x12); a cue that should be it maps to its nearest neighbour. + * 0x2B (#FF0017) was observed on a real export though it is not one of the 16 + swatches; it is kept so such a colour survives a round trip exactly. + * **The palette has no white or grey.** A colourless (white/grey) cue — above + all Traktor's white grid-marker companion — gets code 0 with its RGB. rekordbox + produces that state itself (the reference fixture's cues are code 0 + RGB); + what rekordbox DRAWS for it is not yet verified. +""" +from __future__ import annotations + +import colorsys + +#: code -> RGB, exactly as rekordbox 7 writes them. +PALETTE: dict[int, tuple[int, int, int]] = { + 0x31: (0xFF, 0x00, 0xA1), # magenta + 0x38: (0xB3, 0x00, 0xFF), # purple + 0x3C: (0x4D, 0x00, 0xFF), # violet + 0x3E: (0x1A, 0x00, 0xFF), # blue-violet + 0x01: (0x00, 0x00, 0xFF), # blue + 0x05: (0x00, 0x70, 0xFF), # light blue + 0x09: (0x00, 0xE0, 0xFF), # cyan + 0x0E: (0x00, 0xFF, 0xA3), # teal + 0x16: (0x1A, 0xFF, 0x00), # green + 0x1A: (0x80, 0xFF, 0x00), # lime + 0x1E: (0xE6, 0xFF, 0x00), # yellow-lime + 0x20: (0xFF, 0xE8, 0x00), # yellow + 0x26: (0xFF, 0x5E, 0x00), # orange + 0x2A: (0xFF, 0x00, 0x00), # red + 0x2B: (0xFF, 0x00, 0x17), # red (observed, not a swatch) + 0x2D: (0xFF, 0x00, 0x45), # pink-red +} + +#: Konduktor's TYPE colours (`core.cue_colors`) -> the swatch a DJ would call by +#: the same name. Nearest-hue alone sends the mint loop green to TEAL, and a +#: Traktor user reads a loop as green; so the type colours are pinned by intent. +_BY_INTENT: dict[str, int] = { + "#4D94FF": 0x05, # cue -> light blue + "#3DDC84": 0x16, # loop -> green + "#FF9A3D": 0x26, # fade -> orange + "#FFD23D": 0x20, # load -> yellow +} + +#: Below this saturation a colour is white/grey, which the palette cannot show. +_GREY = 0.2 + + +def _parse(color: str) -> tuple[int, int, int] | None: + c = (color or "").strip().lstrip("#") + if len(c) != 6: + return None + try: + return int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16) + except ValueError: + return None + + +def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]: + """(palette code, RGB to store) for a generic `#RRGGBB`; (0, black) for none. + + An exact palette RGB keeps its code; a type colour maps by intent; a + white/grey keeps its RGB with code 0; anything else takes the swatch of the + nearest hue, and stores THAT swatch's RGB so code and colour agree. + """ + rgb = _parse(color) if color else None + if rgb is None: + return 0, (0, 0, 0) + for code, value in PALETTE.items(): + if value == rgb: + return code, value + intent = _BY_INTENT.get(f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}") + if intent is not None: + return intent, PALETTE[intent] + h, _l, s = colorsys.rgb_to_hls(*(v / 255 for v in rgb)) + if s < _GREY or max(rgb) - min(rgb) < 40: + return 0, rgb + def hue_gap(code: int) -> float: + ph = colorsys.rgb_to_hls(*(v / 255 for v in PALETTE[code]))[0] + d = abs(ph - h) + return min(d, 1 - d) + best = min((c for c in PALETTE if c != 0x2B), key=hue_gap) + return best, PALETTE[best] diff --git a/backend/konduktor/adapters/rekordbox/projection.py b/backend/konduktor/adapters/rekordbox/projection.py index 41b547c..a8dcd08 100644 --- a/backend/konduktor/adapters/rekordbox/projection.py +++ b/backend/konduktor/adapters/rekordbox/projection.py @@ -8,7 +8,7 @@ from __future__ import annotations import re from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues -from . import beatgrid +from . import beatgrid, timebase from .cue_types import cue_type, role_and_slot # Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or @@ -161,7 +161,7 @@ def to_track(row, cue_kinds=()) -> Track: ) -def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) -> TrackCues: +def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0) -> TrackCues: """Project a track's cues and beatgrid. `grid` is the per-beat ``(times, bpms, beats)`` from the ANLZ file, collapsed here @@ -195,7 +195,9 @@ def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) name=(getattr(c, "Comment", None) or None), type=kind, role=role, - start=in_msec / 1000.0, + # rekordbox's clock -> the decoded audio's (see `timebase`); the + # grid arrives already converted by the store. + start=timebase.from_pioneer(in_msec / 1000.0, time_offset), length=length, slot=slot, color=_cue_color(c), diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 72ed480..a8df250 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -40,6 +40,7 @@ from sqlalchemy.orm import joinedload from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome from ...core.edit_journal import EditJournal from ...core.pathmap import PathMapping +from . import timebase from .cue_types import beat_loop_size, kind_for, role_and_slot log = logging.getLogger(__name__) @@ -266,6 +267,10 @@ class RekordboxStore: if key in self._grid_cache: return self._grid_cache[key] result = self._read_anlz_grid(key) + if result is not None: + off = self.time_offset(key) + times, bpms, beats = result + result = ([timebase.from_pioneer(t, off) for t in times], bpms, beats) self._grid_cache[key] = result return result @@ -315,6 +320,14 @@ class RekordboxStore: return None return self._mapping.apply(Path(str(folder))) + def time_offset(self, track_id: str) -> float: + """Seconds rekordbox's clock runs behind the decoded audio for this + track (~25 ms on MP3/AAC, 0 lossless). Added on every position written, + subtracted on every position read — see `timebase`. Decided by the + stored FolderPath's format, so it holds even when the file is offline.""" + folder = getattr(self.content(track_id), "FolderPath", None) + return timebase.offset(str(folder) if folder else None) + def cover_art(self, track_id: str) -> tuple[bytes, str] | None: """The art embedded in the audio file, else Rekordbox's own copy. @@ -641,9 +654,11 @@ class RekordboxStore: if int(slot) < 0: raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}") row = self.content(track_id) - in_ms = int(round(start_sec * 1000)) + off = self.time_offset(track_id) + in_ms = int(round(timebase.to_pioneer(start_sec, off) * 1000)) is_loop = cue_type == "loop" and length_sec > 0 - out_ms = int(round((start_sec + length_sec) * 1000)) if is_loop else -1 + out_ms = (int(round(timebase.to_pioneer(start_sec + length_sec, off) * 1000)) + if is_loop else -1) kind = kind_for("hotcue", slot) existing = self._cue_row(track_id, slot) @@ -698,7 +713,8 @@ class RekordboxStore: cue = self._cue_row(track_id, slot) if cue is None: raise NotFound(f"No cue in slot {slot}") - start = (cue.InMsec or 0) / 1000.0 + # Back to the decoded time base: set_cue re-applies the offset. + start = timebase.from_pioneer((cue.InMsec or 0) / 1000.0, self.time_offset(track_id)) length = 0.0 if cue_type == "loop": if cue.OutMsec and cue.OutMsec > 0: @@ -920,5 +936,7 @@ class RekordboxStore: path = self.path.parent / "share" / str(rel).lstrip("/\\") if not path.is_file(): raise InvalidCommand(f"Analysis file is missing: {path}") - grid_math.write_pqtz(path, beat_nums, bpms, times) + off = self.time_offset(track_id) + grid_math.write_pqtz(path, beat_nums, bpms, + [timebase.to_pioneer(t, off) for t in times]) self._pending_grids.clear() diff --git a/backend/konduktor/adapters/rekordbox/timebase.py b/backend/konduktor/adapters/rekordbox/timebase.py new file mode 100644 index 0000000..2ad903a --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/timebase.py @@ -0,0 +1,64 @@ +"""Pioneer's clock vs the decoded audio's — one rule, used at every boundary. + +**On MP3 and AAC, rekordbox's time 0 is NOT the decoded audio's time 0.** It does +not trim the codec delay a decoder removes, so every position it stores — beats, +cues, loops — sits a constant 1105 samples (~25 ms at 44.1 kHz) LATER than the +same moment in the decoded audio. Lossless files have no such delay. + +Measured, not assumed: Konduktor's grid detector (which works in the decoded +time base) against rekordbox's own grids for the local library gave a median of ++25.0 ms on 16 MP3s, +24.5 ms on 4 M4As and 0.0 ms on 7 WAVs. 1105 samples is the +classic MP3 codec delay (576 encoder + 529 decoder). + +The generic model is in the DECODED time base — it is what Konduktor's deck plays, +what Traktor's positions line up with, and what the grid detector measures. So a +Pioneer adapter ADDS the offset on every write and SUBTRACTS it on every read. +Get it wrong and nothing fails: every cue and beat is simply 25 ms early in +rekordbox (as the first OneLibrary exports were), or late in Konduktor. +""" +from __future__ import annotations + +from functools import lru_cache +from pathlib import Path + +#: The codec delay rekordbox does not trim. +CODEC_DELAY_SAMPLES = 1105 +#: Formats that carry one. `.stem.m4a` (a Traktor STEM) is AAC. +LOSSY = frozenset({".mp3", ".m4a", ".mp4", ".aac"}) +_DEFAULT_RATE = 44100 + + +@lru_cache(maxsize=4096) +def _sample_rate(path: str) -> int: + try: + import mutagen + + rate = getattr(getattr(mutagen.File(path), "info", None), "sample_rate", None) + return int(rate) if rate else _DEFAULT_RATE + except Exception: # an unreadable header: assume the overwhelmingly common rate + return _DEFAULT_RATE + + +def offset(path: Path | str | None) -> float: + """Seconds to ADD to a decoded-audio time to get rekordbox's; 0 if lossless. + + A missing path (a track whose audio cannot be located) gets 0: there is no + file to say which format it is, and guessing lossy would move a lossless + track's cues. + """ + if not path: + return 0.0 + p = Path(path) + if p.suffix.lower() not in LOSSY: + return 0.0 + return CODEC_DELAY_SAMPLES / _sample_rate(str(p)) + + +def to_pioneer(seconds: float, off: float) -> float: + return seconds + off + + +def from_pioneer(seconds: float, off: float) -> float: + """Back to the decoded time base, never before the start of the track: a + rekordbox position inside the codec delay is the track's first sample.""" + return max(0.0, seconds - off) diff --git a/backend/konduktor/core/cue_colors.py b/backend/konduktor/core/cue_colors.py new file mode 100644 index 0000000..a7f613d --- /dev/null +++ b/backend/konduktor/core/cue_colors.py @@ -0,0 +1,33 @@ +"""The colour a cue is SHOWN in — the one backend definition. + +A stored colour wins; otherwise the cue's type decides. That is Traktor's own +convention (it stores a colour only on a grid marker's white companion cue and +draws every other cue from its type) and it is exactly what Konduktor's deck and +table draw. **Keep in lockstep with `TYPE_COLORS` in `frontend/src/lib/cues.ts`.** + +Why the backend needs it: an export to a platform that stores a colour per cue +(rekordbox) must write what the user SEES. Writing "no colour" hands the choice +to the target, which draws its own defaults — rekordbox showed green cues and +orange loops where Konduktor and Traktor show blue and green. +""" +from __future__ import annotations + +from .model import CuePoint + +TYPE_COLORS = { + "cue": "#4D94FF", # blue + "fade_in": "#FF9A3D", # orange + "fade_out": "#FF9A3D", # orange + "load": "#FFD23D", # yellow + "loop": "#3DDC84", # green +} +MEMORY_COLOR = "#9AA1B2" # grey + + +def effective_color(cue: CuePoint) -> str: + """`#RRGGBB` — the stored colour, or the type's.""" + if cue.color: + return cue.color.upper() + if cue.role == "memory": + return MEMORY_COLOR + return TYPE_COLORS.get(cue.type, MEMORY_COLOR) diff --git a/backend/konduktor/core/export.py b/backend/konduktor/core/export.py index c73959f..5409478 100644 --- a/backend/konduktor/core/export.py +++ b/backend/konduktor/core/export.py @@ -45,6 +45,11 @@ class ExportTrack: #: write should be discovering. destination: Path cues: TrackCues | None = None + #: The cover as the SOURCE library serves it — `(bytes, mime)` from + #: `LibraryAdapter.cover_art` — or None. Carried rather than re-read from the + #: copied file, because a library's art is not always embedded in the audio + #: (rekordbox keeps its own copy under `share/`). + art: tuple[bytes, str] | None = None @property def source_id(self) -> str: diff --git a/backend/konduktor/core/waveform.py b/backend/konduktor/core/waveform.py index 8c2d7c9..6738e89 100644 --- a/backend/konduktor/core/waveform.py +++ b/backend/konduktor/core/waveform.py @@ -1,18 +1,25 @@ -"""Per-column loudness and brightness of a track, for drawing a waveform OVERVIEW. +"""What a track's waveform is made of — measured once, drawn by whoever needs it. Platform-independent on purpose: this decodes and measures, and stops there. How -a column becomes pixels — Pioneer's 5-bit height plus 3-bit "whiteness", say — -is the target's business (`adapters/rekordbox/anlz_writer.py`). +a measurement becomes pixels — Pioneer's 5-bit heights, 3-band bytes, colour +bits — is the target's business (`adapters/rekordbox/anlz_writer.py`). -Why an export needs it at all: rekordbox shows a track's beatgrid and hot cues -ONLY when its `.DAT` also carries the preview waveform (and a `PVBR` tag). -Measured by stripping tags from a rekordbox-written stick one at a time — the -grid and cue tags alone, byte-for-byte rekordbox's own, show nothing. +Two resolutions, from ONE decode: -Decoding goes through `librosa`, like grid detection: libsndfile for most -formats and, for AAC (every Traktor `.stem.m4a`), `audioread`'s CoreAudio -backend on macOS. Where nothing can decode a file, `columns()` returns None and -the caller decides what a missing overview means. + * `columns` — `n` equal slices of the whole track (loudness + brightness), for + an overview such as Pioneer's blue `PWAV` preview; + * `frames` — 150 per second, each split into low / mid / high band energy, + for a detail waveform and a 3-band overview (Pioneer's `PWV3`-`PWV7`). + +The bands cross over at 200 Hz and 2.5 kHz: fitted against rekordbox's own 3-band +waveforms for ten local tracks (correlation 0.89 / 0.80 / 0.77 per band). Energy +is left unscaled — each target normalises it its own way. + +Decoding goes through PyAV (FFmpeg, bundled in its wheel) and falls back to +`librosa`, like grid detection: libsndfile for most formats +and, for AAC (every Traktor `.stem.m4a`), `audioread`'s CoreAudio backend on macOS. +Where nothing can decode a file, `analyse()` returns None and the caller decides +what a missing waveform means. """ from __future__ import annotations @@ -24,10 +31,15 @@ import numpy as np log = logging.getLogger(__name__) -#: Plenty for an overview, and half the decode cost of 44.1 kHz. Brightness is -#: measured below 11 kHz, which is where it is audible anyway. -_SR = 22050 -#: "Bright" = share of spectral energy above this. +#: Plenty for a waveform, and half the decode cost of 44.1 kHz. The high band +#: runs to 11 kHz, which is where most of its visible energy is anyway. +SR = 22050 +#: Detail resolution. Pioneer's detail tags are 150 entries per second. +FPS = 150 +N_FFT = 1024 +#: Band crossovers, Hz. +LOW_MAX, MID_MAX = 200.0, 2500.0 +#: "Bright" (for `columns`) = share of spectral energy above this. _BRIGHT_HZ = 2500.0 @@ -43,24 +55,113 @@ class Columns: duration: float -def columns(path: Path, n: int) -> Columns | None: - """Measure `n` columns of `path`, or None when it cannot be decoded.""" +@dataclass +class Frames: + """150-per-second band energies, low / mid / high, shape (n, 3). + + Frame i covers `[i/150, (i+1)/150)` seconds on the clock the caller asked + for — see `analyse(lead=…)`. + """ + + bands: np.ndarray + #: Decoded length in seconds (of the audio, not counting any lead). + duration: float + + +@dataclass +class Analysis: + columns: Columns + frames: Frames + + @property + def duration(self) -> float: + return self.columns.duration + + +def _decode_pyav(path: Path) -> np.ndarray: + """Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel. + + The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY + OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured + to start on exactly the same sample as librosa's decode for MP3 and AAC, so + switching decoders moves nothing against the beats. + """ + import av + + with av.open(str(path)) as container: + stream = container.streams.audio[0] + resampler = av.AudioResampler(format="flt", layout="mono", rate=SR) + chunks = [] + for frame in container.decode(stream): + for out in resampler.resample(frame): + chunks.append(out.to_ndarray().reshape(-1)) + for out in resampler.resample(None): # flush + chunks.append(out.to_ndarray().reshape(-1)) + return np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32) + + +def _decode(path: Path) -> np.ndarray | None: + try: + return _decode_pyav(path) + except Exception as ex: # PyAV missing, or a file FFmpeg cannot open + log.debug("PyAV could not decode %s (%s); trying librosa", path, ex) try: import librosa - y, sr = librosa.load(str(path), sr=_SR, mono=True) - except Exception as ex: # any decoder failure: no overview, not a failed export + y, _ = librosa.load(str(path), sr=SR, mono=True) + return y + except Exception as ex: # any decoder failure: no waveform, not a failed export log.warning("could not decode %s for a waveform: %s", path, ex) return None - if len(y) < n: - return None + +def _columns(y: np.ndarray, n: int) -> Columns: import librosa rms = np.array([float(np.sqrt(np.mean(c * c))) for c in np.array_split(y, n)]) - spec = np.abs(librosa.stft(y, n_fft=1024, hop_length=1024)) ** 2 - freqs = librosa.fft_frequencies(sr=sr, n_fft=1024) + spec = np.abs(librosa.stft(y, n_fft=N_FFT, hop_length=N_FFT)) ** 2 + freqs = librosa.fft_frequencies(sr=SR, n_fft=N_FFT) share = spec[freqs > _BRIGHT_HZ].sum(0) / (spec.sum(0) + 1e-12) brightness = np.array([float(c.mean()) if len(c) else 0.0 for c in np.array_split(share, n)]) - return Columns(rms=rms, brightness=brightness, duration=len(y) / sr) + return Columns(rms=rms, brightness=brightness, duration=len(y) / SR) + + +def _frames(y: np.ndarray, lead: float) -> Frames: + """Band energies at 150/s, with the frame grid starting `lead` s BEFORE the + audio — how a target whose clock runs behind the decoded audio (rekordbox on + MP3/AAC) gets frames that line up with its own positions.""" + import librosa + + duration = len(y) / SR + pad = int(round(max(0.0, lead) * SR)) + padded = np.concatenate([np.zeros(pad, dtype=y.dtype), y]) if pad else y + n = int(np.ceil((len(padded) / SR) * FPS)) + hop = SR / FPS # 147 samples at 22050 Hz + spec = np.abs(librosa.stft(padded, n_fft=N_FFT, hop_length=int(round(hop)), + center=True)) ** 2 + f = librosa.fft_frequencies(sr=SR, n_fft=N_FFT) + bands = np.stack([ + np.sqrt(spec[f < LOW_MAX].sum(0)), + np.sqrt(spec[(f >= LOW_MAX) & (f < MID_MAX)].sum(0)), + np.sqrt(spec[f >= MID_MAX].sum(0)), + ], axis=1)[:n] + if len(bands) < n: + bands = np.vstack([bands, np.zeros((n - len(bands), 3))]) + return Frames(bands=bands, duration=duration) + + +def analyse(path: Path, *, n_columns: int = 400, lead: float = 0.0) -> Analysis | None: + """Decode `path` once and measure both resolutions; None if undecodable.""" + y = _decode(path) + if y is None or len(y) < max(n_columns, N_FFT): + return None + return Analysis(columns=_columns(y, n_columns), frames=_frames(y, lead)) + + +def columns(path: Path, n: int) -> Columns | None: + """Just the overview columns — for a caller that needs no detail.""" + y = _decode(path) + if y is None or len(y) < n: + return None + return _columns(y, n) diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py index c8b5076..6df4f6f 100644 --- a/backend/konduktor/exporter.py +++ b/backend/konduktor/exporter.py @@ -376,6 +376,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: track=adapter.track(planned.track_id), destination=target, cues=adapter.track_cues(planned.track_id), + art=_cover(adapter, planned.track_id), ) ) @@ -438,6 +439,16 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: raise +def _cover(adapter, track_id: str): + """The source's cover art, or None. A missing or unreadable cover costs the + artwork on the stick, never the export.""" + try: + return adapter.cover_art(track_id) + except Exception as ex: # noqa: BLE001 + log.warning("no cover art for %s: %s", track_id, ex) + return None + + def _files(root: Path) -> set[Path]: try: return {p for p in root.rglob("*") if p.is_file()} diff --git a/backend/requirements.txt b/backend/requirements.txt index 449c9b0..91a72c2 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -4,6 +4,8 @@ fastapi>=0.115 uvicorn[standard]>=0.34 pydantic>=2.11 mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF) +av>=18.1 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS +Pillow>=11 # cover art -> the 80/240 px JPEGs a Pioneer export carries python-multipart>=0.0.9 # multipart form parsing for cover-art upload # Version-history backups: a self-contained git impl (no system git needed; # ships prebuilt py3.14 wheels, no from-source build) + a per-OS user-writable diff --git a/backend/test_export_pioneer.py b/backend/test_export_pioneer.py index d21d4ad..783e6e8 100644 --- a/backend/test_export_pioneer.py +++ b/backend/test_export_pioneer.py @@ -35,7 +35,7 @@ from konduktor.adapters.traktor.driver import TraktorDriver # noqa: E402 from konduktor.adapters.traktor.projection import parse_key as traktor_key_parse # noqa: E402 from konduktor.core import export as core_export # noqa: E402 from konduktor.core.export import ExportPayload, ExportPlaylist, ExportTrack # noqa: E402 -from konduktor.core.model import GridMarker, TrackCues # noqa: E402 +from konduktor.core.model import CuePoint, GridMarker, TrackCues # noqa: E402 failed = False @@ -149,8 +149,13 @@ for platform, reopen in ( print(f"-- {platform}: the prep crossed") for track in chosen: s, o = src.track_cues(track.id), back.track_cues(by_title[track.title].id) + # Same pads, same places — to the millisecond Pioneer stores (a position + # now crosses a 25 ms clock shift and back, so 2-dp rounding can flip). + ho, hs = hotcues(o), hotcues(s) check(f"{track.title[:22]}: hot cues keep their PAD", - hotcues(o) == hotcues(s), f"{hotcues(o)} vs {hotcues(s)}") + [p for p, _ in ho] == [p for p, _ in hs] + and all(abs(a - b) <= 0.011 for (_, a), (_, b) in zip(ho, hs)), + f"{ho} vs {hs}") check(f"{track.title[:22]}: the grid survives expansion + collapse", grid(o) == grid(s), f"{grid(o)} vs {grid(s)}") check("the flexible grid really is multi-tempo", @@ -191,6 +196,7 @@ import struct # noqa: E402 from konduktor.adapters.onelibrary.export import OneLibraryExporter, _file_type, _kbps # noqa: E402 from konduktor.adapters.rekordbox import anlz_writer as W # noqa: E402 +from konduktor.adapters.rekordbox import artwork as artwork_mod # noqa: E402 ol_root = Path(__file__).resolve().parent / "fixtures" / "onelibrary" ol = OneLibraryDriver().open(ol_root) @@ -198,7 +204,10 @@ demo = next(t for t in ol.tracks if "Demo Track 1" in (t.title or "")) demo_item = ExportTrack(track=demo, destination=ol_root / demo.id.lstrip("/"), cues=ol.track_cues(demo.id)) demo_beats = OneLibraryExporter._beats(demo_item) -demo_cues = OneLibraryExporter._cue_dicts(demo_item, demo_beats) +# The reader moved the fixture's positions onto the decoded clock; packing puts +# them back on rekordbox's, so the bytes must come back unchanged. +from konduktor.adapters.rekordbox import timebase # noqa: E402 +demo_cues = OneLibraryExporter._cue_dicts(demo_item, demo_beats, timebase.offset(demo_item.destination)) def _real_cue_tags(path: Path) -> list[bytes]: @@ -212,6 +221,19 @@ def _real_cue_tags(path: Path) -> list[bytes]: return out +def _mask_colour(tag: bytes) -> bytes: + """A PCO2 tag with each entry's code + RGB (after its comment) zeroed.""" + if tag[:4] != b"PCO2": + return tag + out, off = bytearray(tag), struct.unpack(">I", tag[4:8])[0] + while off < len(tag): + length = struct.unpack(">I", tag[off + 8:off + 12])[0] + at = off + 44 + struct.unpack(">I", tag[off + 40:off + 44])[0] + out[at:at + 4] = bytes(4) + off += length + return bytes(out) + + anlz = ol_root / "PIONEER" / "USBANLZ" / "P016" / "0000875E" / "ANLZ0000" for suffix, extended, shape in ((".DAT", False, "hot + memory PCOB"), (".EXT", True, "hot + memory PCOB, hot + memory PCO2")): @@ -219,9 +241,13 @@ for suffix, extended, shape in ((".DAT", False, "hot + memory PCOB"), ours = W.cue_tags(demo_cues, extended=extended) check(f"{suffix}: the same tags in the same order ({shape})", len(real) == len(ours), f"{len(ours)} vs rekordbox's {len(real)}") - check(f"{suffix}: every cue tag is byte-identical to rekordbox's", - all(r == o for r, o in zip(real, ours)), - [i for i, (r, o) in enumerate(zip(real, ours)) if r != o]) + # Byte-identical EXCEPT the four colour bytes of each PCP2 entry. The + # fixture's cues carry rekordbox's OLD form (code 0 + an arbitrary RGB); the + # writer now stores a palette code, which is what rekordbox 7 draws from — + # pinned separately below against a real rekordbox 7 palette export. + check(f"{suffix}: every cue tag is byte-identical to rekordbox's (colour aside)", + all(_mask_colour(r) == _mask_colour(o) for r, o in zip(real, ours)), + [i for i, (r, o) in enumerate(zip(real, ours)) if _mask_colour(r) != _mask_colour(o)]) check("a track with no cues still gets every list, empty", [t[:4] for t in W.cue_tags([], extended=True)] == [b"PCOB", b"PCOB", b"PCO2", b"PCO2"]) check("a Traktor STEM file is an M4A to a Pioneer player", @@ -288,6 +314,9 @@ wf_written = core_export.for_platform("onelibrary").write( ) dats = [p for p in wf_written.extra if p.suffix == ".DAT"] check("two tracks, two .DAT files", len(dats) == 2) +check("every file written is reported, so a re-export can clear it", + all(p.exists() for p in wf_written.all_paths) + and {p.suffix for p in wf_written.extra} == {".DAT", ".EXT", ".2EX"}) for dat in dats: check(f"{dat.parent.name}: rekordbox's tag set, in rekordbox's order", _tag_kinds(dat) == REKORDBOX_DAT_ORDER, _tag_kinds(dat)) @@ -297,6 +326,36 @@ check("PVBR is 400 seek points plus a trailing length, as rekordbox writes", check("the writer reported each track to the status bar", len(seen) == 2 and all("Analysing" in m for m in seen), seen) +# The drawn waveforms: rekordbox 7's song-list preview and scrolling deck read +# the .2EX (3-band) and .EXT. Same tags, same order as rekordbox writes. +live_dat = next(d for d in dats if (d.with_suffix(".2EX")).exists()) +check("a decodable track gets all three analysis files", + live_dat.with_suffix(".EXT").exists() and live_dat.with_suffix(".2EX").exists()) +check(".EXT: rekordbox's tag order", + _tag_kinds(live_dat.with_suffix(".EXT")) == [b"PPTH", b"PWV3", b"PCOB", b"PCOB", b"PCO2", b"PCO2", b"PWV5", b"PWV4"], + _tag_kinds(live_dat.with_suffix(".EXT"))) +check(".2EX: rekordbox's tag order", + _tag_kinds(live_dat.with_suffix(".2EX")) == [b"PPTH", b"PWV7", b"PWV6", b"PWVC"], + _tag_kinds(live_dat.with_suffix(".2EX"))) +pwv7 = _tag(live_dat.with_suffix(".2EX"), b"PWV7") +n7 = struct.unpack(">I", pwv7[16:20])[0] +check("PWV7 is 150 frames a second, 3 bytes each", abs(n7 - 8 * 150) <= 2 and len(pwv7) == 24 + 3 * n7, n7) +check("PWV6 is 1200 overview columns of 3 bytes", len(_tag(live_dat.with_suffix(".2EX"), b"PWV6")) == 20 + 3600) +# The song list's colour overview: without it rekordbox draws the row plain blue. +pwv4 = _tag(live_dat.with_suffix(".EXT"), b"PWV4") +check("PWV4 is 1200 columns of 6 bytes, with rekordbox's header", + len(pwv4) == 24 + 7200 and pwv4[12:24] == bytes.fromhex("00000006000004b000000000"), pwv4[12:24].hex()) +p4 = np.frombuffer(pwv4[24:], np.uint8).reshape(-1, 6).astype(int) +check("its colour overview is loud where the audio is loud (height byte)", + p4[:600, 2].mean() > p4[600:, 2].mean() + 10, (p4[:600, 2].mean(), p4[600:, 2].mean())) +p7 = np.frombuffer(pwv7[24:], np.uint8).reshape(-1, 3).astype(int) +check("the 3-band detail is loud where the audio is loud", + p7[: n7 // 2].mean() > p7[n7 // 2:].mean() + 10, (p7[: n7 // 2].mean(), p7[n7 // 2:].mean())) +dead_dat = next(d for d in dats if d != live_dat) +check("an undecodable track still gets its .EXT cue lists, but no invented waveform", + dead_dat.with_suffix(".EXT").exists() and not dead_dat.with_suffix(".2EX").exists() + and b"PWV3" not in _tag_kinds(dead_dat.with_suffix(".EXT"))) + cols = waveform.columns(live, 400) check("decodable audio is measured", cols is not None and abs(cols.duration - 8.0) < 0.05) check("a loud half measures louder than a quiet half", @@ -329,5 +388,120 @@ try: except _Stop: check("a cancel between tracks stops the writer", True) +print("\n== positions cross onto rekordbox's clock (25 ms later on MP3/AAC) ==") +# Measured: rekordbox's grids sit a median 25.0 ms later than the decoded audio +# on 16 MP3s and 24.5 ms on 4 M4As, 0 on WAV — the codec delay it does not trim. +# Written at the decoded time, every cue showed ~25 ms early in rekordbox. +check("an MP3's offset is 1105 samples", abs(timebase.offset("a.mp3") - 1105 / 44100) < 1e-9) +check("a Traktor STEM (AAC) has it too", timebase.offset("a.stem.m4a") > 0.02) +check("a lossless file has none", timebase.offset("a.wav") == 0.0 and timebase.offset("a.flac") == 0.0) +check("a file of unknown location has none", timebase.offset(None) == 0.0) +probe = [CuePoint(type="cue", role="hotcue", start=30.0, length=0.0, slot=1)] +for name, want in (("probe.mp3", 30025), ("probe.wav", 30000)): + it = ExportTrack(track=cued, destination=Path(name), cues=TrackCues(track_id="p", cues=probe, grid_markers=[])) + got = OneLibraryExporter._cue_dicts(it, [], timebase.offset(it.destination))[0]["time_ms"] + check(f"a cue at 30.000 s in {name} is stored at {want} ms", got == want, got) +check("reading it back undoes it exactly", + abs(timebase.from_pioneer(30025 / 1000, timebase.offset("a.mp3")) - 30.0) < 0.0005) +check("a position inside the codec delay reads as the track's start", + timebase.from_pioneer(0.010, timebase.offset("a.mp3")) == 0.0) + +print("\n== cue colours cross as rekordbox PALETTE CODES ==") +# rekordbox draws a hot cue from the palette code, not the RGB: an export writing +# code 0 had every cue drawn in rekordbox's defaults (green cues, orange loops). +# The table was measured from a rekordbox 7 export of all 16 swatches. +from konduktor.adapters.rekordbox import palette # noqa: E402 + +check("a measured swatch keeps its exact code and RGB", + palette.code_for("#1AFF00") == (0x16, (0x1A, 0xFF, 0x00)) + and palette.code_for("#FF00A1") == (0x31, (0xFF, 0x00, 0xA1))) +check("a Konduktor cue (blue) is rekordbox's light blue", palette.code_for("#4D94FF")[0] == 0x05) +check("a Konduktor loop (green) is rekordbox's GREEN, not the nearer-hued teal", + palette.code_for("#3DDC84")[0] == 0x16) +check("white has no swatch: code 0, RGB kept", palette.code_for("#FFFFFF") == (0, (255, 255, 255))) +check("no colour is code 0, black", palette.code_for(None) == (0, (0, 0, 0))) +check("any other colour takes the nearest-hue swatch, and that swatch's RGB", + palette.code_for("#FF8C00") == (0x26, palette.PALETTE[0x26])) +typed = [CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0), + CuePoint(type="loop", role="hotcue", start=2.0, length=1.0, slot=1), + CuePoint(type="cue", role="hotcue", start=3.0, length=0.0, slot=2, color="#FFFFFF"), + CuePoint(type="cue", role="memory", start=4.0, length=0.0, slot=None)] +got = {c["hot_cue"]: (c["code"], c["rgb"]) for c in OneLibraryExporter._cue_dicts( + ExportTrack(track=cued, destination=Path("t.wav"), + cues=TrackCues(track_id="t", cues=typed, grid_markers=[])), [], 0.0)} +check("an uncoloured Traktor cue exports blue, a loop green, the grid cue white", + got[1][0] == 0x05 and got[2][0] == 0x16 and got[3] == (0, (255, 255, 255)), got) +check("a memory cue stays uncoloured, as rekordbox writes it", got[0] == (0, (0, 0, 0)), got[0]) +entry = W.cue_tags([{"hot_cue": 1, "kind": 1, "time_ms": 1000, "loop_ms": None, + "rgb": (0x1A, 0xFF, 0x00), "code": 0x16, "beats": None}], extended=True)[2] +check("the code is packed where rekordbox 7 puts it — byte 44, before the RGB", + entry[20 + 44:20 + 48] == bytes([0x16, 0x1A, 0xFF, 0x00]), entry[64:68].hex()) + +print("\n== artwork crosses the way rekordbox 7 writes it ==") +# Measured on a rekordbox 7 export: PIONEER/Artwork/00001/{a,b}{,_m}.jpg at +# 80 and 240 px (a == b byte for byte), baseline JPEG q85 4:2:0, non-square art +# letterboxed onto black, image.path -> the b file, content.image_id -> the row. +import io # noqa: E402 + +from PIL import Image, JpegImagePlugin # noqa: E402 + +art_root = Path(tempfile.mkdtemp()) +art_audio = art_root / "Contents" / "art.wav" +art_audio.parent.mkdir(parents=True) +sf.write(art_audio, tone, sr) +plain_audio = art_root / "Contents" / "plain.wav" +sf.write(plain_audio, tone, sr) +wide = Image.new("RGB", (400, 100), (220, 30, 30)) # a wide red banner +png = io.BytesIO(); wide.save(png, format="PNG") +with_art = ExportTrack(track=live_t.model_copy(update={"id": "art", "title": "art"}), + destination=art_audio, cues=grid, art=(png.getvalue(), "image/png")) +without = ExportTrack(track=live_t.model_copy(update={"id": "plain", "title": "plain"}), + destination=plain_audio, cues=grid) +art_written = core_export.for_platform("onelibrary").write( + ExportPayload(name="ART", tracks=[with_art, without]), art_root) +folder = art_root / "PIONEER" / "Artwork" / "00001" +names = sorted(p.name for p in folder.iterdir()) if folder.exists() else [] +check("one image: a1, a1_m, b1, b1_m — and none for the track without art", + names == ["a1.jpg", "a1_m.jpg", "b1.jpg", "b1_m.jpg"], names) +check("every art file is reported, so a re-export can clear it", + all((folder / n) in art_written.extra for n in names)) +check("the a and b copies are byte-identical, as rekordbox writes them", + (folder / "a1.jpg").read_bytes() == (folder / "b1.jpg").read_bytes() + and (folder / "a1_m.jpg").read_bytes() == (folder / "b1_m.jpg").read_bytes()) +small_img, medium_img = Image.open(folder / "b1.jpg"), Image.open(folder / "b1_m.jpg") +check("80 px and 240 px", small_img.size == (80, 80) and medium_img.size == (240, 240)) +ref = io.BytesIO(); Image.new("RGB", (8, 8)).save(ref, format="JPEG", quality=85, subsampling=2) +check("baseline JPEG, quality 85, 4:2:0 — rekordbox's own tables", + medium_img.quantization == Image.open(ref).quantization + and JpegImagePlugin.get_sampling(medium_img) == 2 and not medium_img.info.get("progressive")) +px = np.asarray(medium_img.convert("RGB")).astype(int) +check("a wide cover is letterboxed onto black, not cropped or stretched", + px[:40].mean() < 8 and px[-40:].mean() < 8 and px[120, 120, 0] > 150, + (px[:40].mean(), px[120, 120].tolist())) +reopened = OneLibraryDriver().open(art_root) +by_title_art = {t.title: t for t in reopened.tracks} +served = reopened.cover_art(by_title_art["art"].id) +check("Konduktor's reader serves it back (the 240 px file)", + served is not None and served[0] == (folder / "b1_m.jpg").read_bytes()) +check("and a track without art has none", reopened.cover_art(by_title_art["plain"].id) is None) + +print("\n== content.contentLink is what rekordbox writes ==") +# Measured: blanking it on ONE track of a rekordbox-written stick turned that +# row's song-list preview plain blue and put a "?" beside CUE — exactly what +# every row of Konduktor's exports showed while it was NULL. +import sqlcipher3.dbapi2 as _sq # noqa: E402 +from pyrekordbox.devicelib_plus.database import BLOB as _BLOB # noqa: E402 +from pyrekordbox.utils import deobfuscate as _deob # noqa: E402 + +_con = _sq.connect(str(art_written.library)) +_con.execute(f"PRAGMA key='{_deob(_BLOB)}'") +links = {r[0] for r in _con.execute("SELECT contentLink FROM content")} +bits = {r[0] for r in _con.execute("SELECT analysedBits FROM content")} +_con.close() +check("every track carries contentLink 788224, beside analysedBits 41", + links == {788224} and bits == {41}, (links, bits)) +check("an unreadable cover costs the artwork, not the export", + artwork_mod.pioneer_jpegs(b"not an image") is None) + print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) raise SystemExit(1 if failed else 0) diff --git a/backend/test_onelibrary_adapter.py b/backend/test_onelibrary_adapter.py index a507e2e..9743ee8 100644 --- a/backend/test_onelibrary_adapter.py +++ b/backend/test_onelibrary_adapter.py @@ -28,6 +28,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-ol-appdata from konduktor.adapters.onelibrary import discovery # noqa: E402 from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402 from konduktor.adapters.onelibrary.beatgrid import markers_from_beats # noqa: E402 +from konduktor.adapters.rekordbox import timebase # noqa: E402 from konduktor.adapters.onelibrary.cues import ( # noqa: E402 MEMORY_SLOT, NO_LOOP, @@ -235,7 +236,12 @@ markers = cues.grid_markers check("a flexible grid stays flexible", len(markers) == 2, str(len(markers))) check("the first segment is 128 BPM", markers[0].bpm == 128.0) check("the second segment is 90 BPM", markers[1].bpm == 90.0) -check("and it starts at 60 s", abs(markers[1].start - 60.0) < 0.001, str(markers[1].start)) +# Stored positions are on rekordbox's clock, 1105 samples behind the decoded +# audio on an MP3 (`timebase`); the generic model reports the decoded time. +OFF = timebase.offset("x.mp3") +check("the reader converts rekordbox's clock to the decoded audio's (~25 ms on MP3)", + abs(OFF - 1105 / 44100) < 1e-9, OFF) +check("and it starts at 60 s", abs(markers[1].start - (60.0 - OFF)) < 0.001, str(markers[1].start)) check("markers are ordered by position", [m.start for m in markers] == sorted(m.start for m in markers)) print("== cues, cross-checked against the same cues in master.db ==") @@ -246,20 +252,20 @@ print("== cues, cross-checked against the same cues in master.db ==") hot = {c.slot: c for c in cues.cues if c.role == "hotcue"} check("four hot cues, on pads A-D", sorted(hot) == [0, 1, 2, 3], str(sorted(hot))) check("pad A is the loop at 40.000 s", - hot[0].type == "loop" and abs(hot[0].start - 40.0) < 0.001) + hot[0].type == "loop" and abs(hot[0].start - (40.0 - OFF)) < 0.001) check("pad A's loop is 4 beats at 128 BPM = 1.875 s", abs(hot[0].length - 1.875) < 0.001) -check("pad B is at 18.775 s", abs(hot[1].start - 18.775) < 0.001, str(hot[1].start)) -check("pad C is at 90.667 s", abs(hot[2].start - 90.667) < 0.001, str(hot[2].start)) +check("pad B is at 18.775 s", abs(hot[1].start - (18.775 - OFF)) < 0.001, str(hot[1].start)) +check("pad C is at 90.667 s", abs(hot[2].start - (90.667 - OFF)) < 0.001, str(hot[2].start)) # Pad D exists ONLY in the .EXT. A reader that stopped at the .DAT would lose it, # and would do so silently. check("pad D is at 120.000 s — the cue that lives only in the .EXT", - abs(hot[3].start - 120.0) < 0.001, str(hot[3].start)) + abs(hot[3].start - (120.0 - OFF)) < 0.001, str(hot[3].start)) check("hot cues carry their RGB colour", all(c.color and c.color.startswith("#") for c in hot.values())) memory = [c for c in cues.cues if c.role == "memory"] check("the memory cue is preserved", len(memory) == 1) check("it has no slot", memory[0].slot is None) -check("it is the same loop, at the same place", abs(memory[0].start - 40.0) < 0.001) +check("it is the same loop, at the same place", abs(memory[0].start - (40.0 - OFF)) < 0.001) check("no cue on a read-only drive is editable", all(not c.editable for c in cues.cues)) print("== playlists ==") diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index 26a751e..e7c3ae1 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -288,9 +288,16 @@ with tempfile.TemporaryDirectory() as d: row = cue_rows[0][3] check("the 0-based slot is stored as its measured Kind", row["Kind"] == 7, str(row["Kind"])) - check("positions are stored in ms AND frames at 150fps", - row["InMsec"] == 30000 and row["InFrame"] == 4500, - f"{row['InMsec']}/{row['InFrame']}") + # On rekordbox's clock: 30.000 s of DECODED audio is stored 1105 samples + # later on an MP3/AAC (`timebase`), and exactly at 30.000 s lossless. + from konduktor.adapters.rekordbox import timebase + want_ms = int(round((30.0 + adapter._store.time_offset(cue_track.id)) * 1000)) + check("positions are stored in ms AND frames at 150fps, on rekordbox's clock", + row["InMsec"] == want_ms and row["InFrame"] == int(want_ms * 150 / 1000), + f"{row['InMsec']}/{row['InFrame']} (want {want_ms})") + check("and read back at exactly the position that was set", + abs(next(c.start for c in adapter.track_cues(cue_track.id).cues if c.slot == 5) + - 30.0) < 0.0005) check("a non-loop has no out-point", row["OutMsec"] == -1, str(row["OutMsec"])) check("an uncoloured cue matches Rekordbox's own convention", row["Color"] == -1 and row["ColorTableIndex"] is None, diff --git a/frontend/package.json b/frontend/package.json index e1e9a7e..be94b78 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "0.2.0", + "version": "0.2.1", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/lib/cues.ts b/frontend/src/lib/cues.ts index b0a4f23..adfd2d7 100644 --- a/frontend/src/lib/cues.ts +++ b/frontend/src/lib/cues.ts @@ -2,7 +2,8 @@ import type { CuePoint, CueType } from '../api' import { BEATS_PER_BAR, type BeatGrid } from './beatgrid' import type { IconName } from './icons' -// Fallback colour by cue type, used when the platform stored none. +// Fallback colour by cue type, used when the platform stored none. Mirrored by +// `backend/konduktor/core/cue_colors.py` (what an export writes) — keep in lockstep. const TYPE_COLORS: Record = { cue: '#4d94ff', // blue fade_in: '#ff9a3d', // orange