From 4878d82671746a2bb59ebd03122892bd1ceb0cad Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Sun, 27 Sep 2026 16:27:55 +0200 Subject: [PATCH] Fixed OneLibrary export missing data --- CLAUDE.md | 34 ++- backend/fixtures/onelibrary/seed.sql | 81 +++++++ backend/konduktor-sidecar.spec | 10 + .../konduktor/adapters/onelibrary/beatgrid.py | 13 +- .../konduktor/adapters/onelibrary/export.py | 123 ++++++++-- .../adapters/onelibrary/projection.py | 3 +- .../adapters/rekordbox/anlz_writer.py | 216 +++++++++++++----- .../konduktor/adapters/rekordbox/beatgrid.py | 35 ++- .../konduktor/adapters/rekordbox/export.py | 25 +- .../adapters/rekordbox/projection.py | 8 +- backend/konduktor/adapters/rekordbox/store.py | 45 ++-- backend/konduktor/core/export.py | 7 +- backend/konduktor/core/model.py | 2 +- backend/konduktor/core/waveform.py | 66 ++++++ backend/konduktor/exporter.py | 5 + backend/test_export_pioneer.py | 148 ++++++++++++ backend/test_rekordbox_adapter.py | 21 ++ 17 files changed, 733 insertions(+), 109 deletions(-) create mode 100644 backend/fixtures/onelibrary/seed.sql create mode 100644 backend/konduktor/core/waveform.py diff --git a/CLAUDE.md b/CLAUDE.md index da244e4..f5942b5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -992,7 +992,39 @@ that number and nothing else — everything derives from it: Rekordbox cannot open. `adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/ exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`, - paths drive-relative). `adapters/rekordbox/export.py` writes a `master.db` and + paths drive-relative). **What rekordbox needs was MEASURED** — by stripping + tags from a rekordbox-written stick one at a time and loading each track in + rekordbox 7 (`goober`, 2026-09-27): a `.DAT` must carry **`PVBR` AND the preview + waveform (`PWAV`/`PWV2`)** or rekordbox shows NEITHER the grid NOR the hot + cues, even when those tags are rekordbox's own bytes. It follows the + `analysisDataFilePath` column (the `P0xx/xxxxxxxx` names need not match its + own path hash, which is no standard hash of the path), and the `.EXT` + waveforms and whole `.2EX` only affect drawing. So every export decodes each + track once (`core/waveform.py`, ~1.5 s each via librosa — CoreAudio for AAC + on macOS; an undecodable file gets a flat preview) and `PVBR` is 400 zeros + plus the MP3's length in samples. Both Pioneer exporters write the full + seven-tag `.DAT`; the `master.db` target's need is inferred, not measured. + Progress and cancel reach the writer through `ExportPayload.checkpoint`. + **pyrekordbox accepting an ANLZ file proves nothing**: its parser ignores + `len_header` and the constants (a 12-byte `PCPT` header round-tripped + perfectly; real: 28). The cue tags are therefore pinned **byte-for-byte** against the fixture's rekordbox-written + files (`test_export_pioneer.py`): both files always, every list always (hot + + memory `PCOB` in each, hot + memory `PCO2` in the `.EXT`, empty ones + included), hot cues highest pad first, the `1000`/`1` constants in `PCP2`. + `fixtures/onelibrary/seed.sql` holds rekordbox's browse scaffolding + (`menuItem`/`category`/`sort`/`color`), like the Rekordbox target's. + `fileType` follows the suffix (a `.stem.m4a` is 4, M4A), bitrate is written in + kbps — **the generic `Track.bitrate` is bits per second** (the table divides by + 1000; the Pioneer readers multiply) — and a stale `exportLibrary.db-wal`/`-shm` + is deleted before writing, because Rekordbox leaves both on a stick it mounted + and SQLite replays a leftover WAL into a new database. **A Pioneer grid can + start mid-bar** (Motorola opens on beat 3): `markers_from_beats` puts the + 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 **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/fixtures/onelibrary/seed.sql b/backend/fixtures/onelibrary/seed.sql new file mode 100644 index 0000000..368f706 --- /dev/null +++ b/backend/fixtures/onelibrary/seed.sql @@ -0,0 +1,81 @@ +-- rekordbox's own scaffolding rows for a OneLibrary drive: the browse menu +-- items, the categories and sort columns a player offers, and the colour +-- palette. Extracted verbatim from fixtures/onelibrary/PIONEER/rekordbox/ +-- exportLibrary.db (a real rekordbox 7.2.18 export). No user data, no +-- machine identity. rekordbox writes these on every export, so a drive without +-- them is not a shape any player has been tested against. + +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (1, 128, 'GENRE'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (2, 129, 'ARTIST'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (3, 130, 'ALBUM'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (4, 131, 'TRACK'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (5, 133, 'BPM'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (6, 134, 'RATING'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (7, 135, 'YEAR'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (8, 136, 'REMIXER'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (9, 137, 'LABEL'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (10, 138, 'ORIGINAL ARTIST'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (11, 139, 'KEY'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (12, 141, 'CUE'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (13, 142, 'COLOR'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (14, 146, 'TIME'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (15, 147, 'BITRATE'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (16, 148, 'FILE NAME'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (17, 132, 'PLAYLIST'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (18, 152, 'HOT CUE BANK'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (19, 149, 'HISTORY'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (20, 145, 'SEARCH'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (21, 150, 'COMMENTS'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (22, 140, 'DATE ADDED'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (23, 151, 'DJ PLAY COUNT'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (24, 144, 'FOLDER'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (25, 161, 'DEFAULT'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (26, 162, 'ALPHABET'); +INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (27, 170, 'MATCHING'); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (1, 1, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (2, 2, 1, 1); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (3, 3, 2, 1); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (4, 4, 3, 1); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (5, 17, 5, 1); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (6, 5, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (7, 6, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (8, 7, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (9, 8, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (10, 9, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (11, 10, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (12, 11, 4, 1); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (15, 13, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (17, 24, 9, 1); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (18, 20, 7, 1); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (19, 14, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (20, 15, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (21, 16, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (22, 19, 6, 1); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (23, 18, 0, 0); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (26, 27, 8, 1); +INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (27, 22, 10, 1); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (0, 25, 1, 1, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (1, 26, 2, 1, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (2, 2, 3, 1, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (3, 3, 4, 1, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (4, 5, 5, 1, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (5, 6, 6, 1, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (6, 1, 0, 0, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (7, 21, 0, 0, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (8, 14, 0, 0, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (9, 8, 0, 0, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (10, 9, 0, 0, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (11, 10, 0, 0, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (12, 11, 7, 1, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (13, 15, 0, 0, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (15, 13, 0, 0, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (16, 23, 0, 0, 0); +INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (17, 22, 0, 0, 0); +INSERT INTO "color" ("color_id", "name") VALUES (1, 'Pink'); +INSERT INTO "color" ("color_id", "name") VALUES (2, 'Red'); +INSERT INTO "color" ("color_id", "name") VALUES (3, 'Orange'); +INSERT INTO "color" ("color_id", "name") VALUES (4, 'Yellow'); +INSERT INTO "color" ("color_id", "name") VALUES (5, 'Green'); +INSERT INTO "color" ("color_id", "name") VALUES (6, 'Aqua'); +INSERT INTO "color" ("color_id", "name") VALUES (7, 'Blue'); +INSERT INTO "color" ("color_id", "name") VALUES (8, 'Purple'); diff --git a/backend/konduktor-sidecar.spec b/backend/konduktor-sidecar.spec index 7ba891e..4ed1450 100644 --- a/backend/konduktor-sidecar.spec +++ b/backend/konduktor-sidecar.spec @@ -35,6 +35,16 @@ hiddenimports += ["multipart", "anyio"] # app version — see konduktor/__init__.py). Path is relative to this spec. datas += [("../frontend/package.json", ".")] +# The Rekordbox and OneLibrary exporters build their databases from the real +# DDL + scaffolding rows under fixtures/, found at `parents[3] / "fixtures"` — +# i.e. the bundle root. Without these a packaged app cannot export to either. +datas += [ + ("fixtures/rekordbox/schema.sql", "fixtures/rekordbox"), + ("fixtures/rekordbox/seed.sql", "fixtures/rekordbox"), + ("fixtures/onelibrary/schema.sql", "fixtures/onelibrary"), + ("fixtures/onelibrary/seed.sql", "fixtures/onelibrary"), +] + a = Analysis( ["sidecar.py"], pathex=[], diff --git a/backend/konduktor/adapters/onelibrary/beatgrid.py b/backend/konduktor/adapters/onelibrary/beatgrid.py index f739932..7cf95a8 100644 --- a/backend/konduktor/adapters/onelibrary/beatgrid.py +++ b/backend/konduktor/adapters/onelibrary/beatgrid.py @@ -27,8 +27,8 @@ from ..rekordbox.beatgrid import BPM_EPSILON, markers_from_beats # noqa: F401 __all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from_anlz"] -def beats_from_pqtz(anlz) -> tuple[list[float], list[float]] | None: - """Per-beat ``(times_sec, bpms)`` from a parsed ANLZ file's `PQTZ` tag. +def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None: + """Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag. Returns None when the file has no `PQTZ` — which is a real state, not an error: rekordbox analyses one-shot samples too, and gives them an analysis @@ -44,13 +44,16 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float]] | None: return None times: list[float] = [] bpms: list[float] = [] + beats: list[int] = [] for e in entries: try: - times.append(int(e.time) / 1000.0) - bpms.append(int(e.tempo) / 100.0) + time, tempo, beat = int(e.time) / 1000.0, int(e.tempo) / 100.0, int(e.beat) except (AttributeError, TypeError, ValueError): continue - return (times, bpms) if times else None + times.append(time) + bpms.append(tempo) + beats.append(beat) + return (times, bpms, beats) if times else None return None diff --git a/backend/konduktor/adapters/onelibrary/export.py b/backend/konduktor/adapters/onelibrary/export.py index cb51401..86c0602 100644 --- a/backend/konduktor/adapters/onelibrary/export.py +++ b/backend/konduktor/adapters/onelibrary/export.py @@ -41,6 +41,7 @@ import logging from datetime import date from pathlib import Path +from ...core import waveform from ...core.export import ExportPayload, ExportTrack, WrittenLibrary from ..rekordbox import anlz_writer as W from ..rekordbox.beatgrid import beats_from_markers @@ -51,6 +52,9 @@ from .layout import DB_SUBPATH log = logging.getLogger(__name__) SCHEMA = Path(__file__).resolve().parents[3] / "fixtures" / "onelibrary" / "schema.sql" +#: rekordbox's scaffolding rows — browse menu items, categories, sort columns, +#: the colour palette — copied from a real export. See the file's header. +SEED = SCHEMA.with_name("seed.sql") #: rekordbox writes this in `property.dbVersion` on a real export. DB_VERSION = "1000" @@ -110,8 +114,14 @@ class OneLibraryExporter: root = Path(destination) library = root / "PIONEER" / DB_SUBPATH library.parent.mkdir(parents=True, exist_ok=True) - if library.exists(): - library.unlink() # SQLCipher will not re-key an existing file + # SQLCipher will not re-key an existing file — and the WAL and shared + # memory files beside it must go too. rekordbox leaves both on a stick + # it has mounted, and SQLite REPLAYS a leftover WAL into whatever + # database it finds, so a fresh library would open with the old one's + # pages written over it. + for stale in (library, *(library.with_name(library.name + s) for s in ("-wal", "-shm"))): + if stale.exists(): + stale.unlink() extra: list[Path] = [] con = sqlcipher.connect(str(library)) @@ -120,6 +130,7 @@ class OneLibraryExporter: # stick is readable by any of them, which is the point of it. con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'") con.executescript(SCHEMA.read_text()) + con.executescript(SEED.read_text(encoding="utf-8")) extra += self._fill(con, payload, root) con.commit() finally: @@ -133,7 +144,11 @@ class OneLibraryExporter: written: list[Path] = [] by_source: dict[str, int] = {} + total = len(payload.tracks) for n, item in enumerate(payload.tracks, start=1): + # Each track is DECODED for its waveform, so this loop is the slow + # part of the write — report it, and let a cancel land between tracks. + payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})") by_source[item.source_id] = n written += self._write_track(con, n, item, root, lookups) @@ -172,16 +187,17 @@ class OneLibraryExporter: size = item.destination.stat().st_size except OSError: size = 0 + sample_rate, bit_depth = _audio_format(item.destination) con.execute( "INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, " "trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, " "djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, " - "fileType, bitrate, samplingRate, isHotCueAutoLoadOn, " + "fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, " "isKuvoDeliverStatusOn, masterDbId, masterContentId, " "analysisDataFilePath, analysedBits, 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, @@ -197,7 +213,10 @@ class OneLibraryExporter: render_key(track.key_wheel, track.key_mode)), track.comment, track.rating or 0, track.release_date, date.today().isoformat(), rel, item.destination.name, size, - 1, track.bitrate, None, 1, 1, 0, content_id, + # 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, ), ) @@ -206,29 +225,37 @@ class OneLibraryExporter: # ---- the analysis files -------------------------------------------------- def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]: - """The `.DAT` and, when there are cues beyond pad C, the `.EXT`. + """The `.DAT` and the `.EXT`, always both, as rekordbox writes them. - Always both when there are any cues: `PCO2` lives only in the `.EXT` and - is the complete list, which is what the reader prefers. + 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`. + + **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. """ - cues = self._cue_dicts(item) - beats = self._beats(item) + measured = waveform.columns(item.destination, 400) + # 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()) - tags = [W.path_tag(rel)] + tags = [W.path_tag(rel), W.vbr_tag(W.mp3_samples(item.destination))] if beats: tags.append(W.beatgrid_tag(beats)) + tags += previews tags += W.cue_tags(cues, extended=False) - written = [W.write_anlz(dat, tags)] - - if cues: - written.append( - W.write_anlz(dat.with_suffix(".EXT"), - [W.path_tag(rel), *W.cue_tags(cues, extended=True)]) - ) - return written + return [ + W.write_anlz(dat, tags), + W.write_anlz(dat.with_suffix(".EXT"), + [W.path_tag(rel), *W.cue_tags(cues, extended=True)]), + ] @staticmethod - def _beats(item: ExportTrack) -> list[tuple[int, float, float]]: + def _beats(item: ExportTrack, duration: float | None = None) -> list[tuple[int, float, float]]: """Every beat, expanded from the generic marker list. A Pioneer grid has no tempo markers — it is a flat list of beats — so a @@ -239,12 +266,13 @@ class OneLibraryExporter: cues = item.cues if not cues or not cues.grid_markers: return [] - duration = float(item.track.length or 0) or (cues.grid_markers[-1].start + 60.0) + duration = (duration or float(item.track.length or 0) + or (cues.grid_markers[-1].start + 60.0)) nums, bpms, times = beats_from_markers(cues.grid_markers, duration) return list(zip(nums, bpms, times)) @staticmethod - def _cue_dicts(item: ExportTrack) -> list[dict]: + def _cue_dicts(item: ExportTrack, beats: list | None = None) -> list[dict]: """Generic cues in the shape `anlz_writer` packs. Slot numbering is ANLZ's own: **dense 1-based**, 0 for a memory cue. @@ -261,7 +289,7 @@ class OneLibraryExporter: "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), - "beats": None, + "beats": _loop_beats(cue.start, cue.length, beats or []) if is_loop else None, }) return out @@ -314,6 +342,55 @@ class OneLibraryExporter: ) +#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them. +#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player. +_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11, + ".aif": 12, ".aiff": 12} + + +def _file_type(path: Path) -> int: + return _FILE_TYPES.get(path.suffix.lower(), 1) + + +def _kbps(bitrate: int | None) -> int | None: + """Generic bits per second → Pioneer's kbps.""" + if not bitrate: + return None + return int(round(bitrate / 1000)) + + +def _audio_format(path: Path) -> tuple[int | None, int | None]: + """(sample rate, bit depth) read from the COPIED file, or Nones. + + Not in the generic model, and not worth adding for one target: the file is + right here, and reading its header costs a millisecond. + """ + try: + import mutagen + + info = getattr(mutagen.File(str(path)), "info", None) + except Exception: # an unreadable file still exports; these stay empty + return None, None + rate = getattr(info, "sample_rate", None) + depth = getattr(info, "bits_per_sample", None) + return (int(rate) if rate else None), (int(depth) if depth else None) + + +def _loop_beats(start: float, length: float, beats: list[tuple[int, float, float]]) -> int | None: + """A loop's length in whole beats at the tempo governing its start. + + rekordbox stores it (`loop_num`/`loop_den`, e.g. 4/1). A loop that is not a + whole number of beats — or a track with no grid — gets none, as rekordbox + itself writes for a loop set by hand. + """ + bpm = next((b for _, b, t in reversed(beats) if t <= start + 1e-3), None) + if not bpm or length <= 0: + return None + count = length * bpm / 60.0 + 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 diff --git a/backend/konduktor/adapters/onelibrary/projection.py b/backend/konduktor/adapters/onelibrary/projection.py index 639363b..3de141d 100644 --- a/backend/konduktor/adapters/onelibrary/projection.py +++ b/backend/konduktor/adapters/onelibrary/projection.py @@ -93,7 +93,8 @@ def to_track(row, drive_path: str | None = None) -> Track: rating=max(0, min(5, int(getattr(row, "rating", 0) or 0))), playcount=getattr(row, "djPlayCount", None), length=getattr(row, "length", None), - bitrate=getattr(row, "bitrate", None), + # kbps here; the generic model (and the table) carry bits per second. + bitrate=(getattr(row, "bitrate", None) or 0) * 1000 or None, import_date=_iso_date(getattr(row, "dateAdded", None)), last_played=None, # the drive records history as playlists, not per track release_date=_iso_date(getattr(row, "releaseDate", None)) diff --git a/backend/konduktor/adapters/rekordbox/anlz_writer.py b/backend/konduktor/adapters/rekordbox/anlz_writer.py index 5429a71..bb77418 100644 --- a/backend/konduktor/adapters/rekordbox/anlz_writer.py +++ b/backend/konduktor/adapters/rekordbox/anlz_writer.py @@ -18,12 +18,27 @@ silently overwrites the first in the result; BUILDING is impossible, because satisfy a string `Const` and an integer field. So cue entries are packed here by hand, to the layout `pyrekordbox`'s own structs document: - PCP2: 4s magic · I len_header · I len_entry · I hot_cue · B kind · 3x - I time · I loop_time · B color_id · 7x · H loop_num · H loop_den - I len_comment · {n}s comment(utf-16-be) · 4B colour · {pad}x + PCP2: 4s magic · I len_header · I len_entry · I hot_cue · B kind · x + H 1000 · I time · I loop_time · B color_id · B 1 · 6x + H loop_num · H loop_den · I len_comment · {n}s comment(utf-16-be) + 4B colour · {pad}x -Everything is verified by parsing the result back through `pyrekordbox`, which is -the only check that matters: the reader is the thing that has to accept it. +**`pyrekordbox` accepting the result is NOT enough.** Its parser ignores +`len_header` and the constants, so an early version with a 12-byte `PCPT` +header round-tripped through Konduktor's own reader perfectly. The cue layout is +therefore pinned to a real rekordbox 7 export byte-for-byte +(`test_export_pioneer.py`). + +**Which tags a file needs was measured, not assumed** — by stripping tags from a +rekordbox-written stick one at a time and loading each track in rekordbox 7: + * `.DAT` needs `PVBR` AND the preview waveform (`PWAV`/`PWV2`) before rekordbox + shows the grid OR the hot cues. The grid and cue tags alone — rekordbox's + own bytes — show nothing. (This, not the cue bytes, was why an early + Konduktor export had no grid.) + * rekordbox follows the database's analysis-path column; the folder names + need not match its own path hash. + * `.EXT` extras (`PWV3`-`PWV5`, `PQT2`, `PSSI`) and the whole `.2EX` affect + only the drawn waveforms. Slot numbering here is ANLZ's own — a **dense 1-based** `hot_cue` where 0 means a memory cue. That is NOT `master.db`'s sparse `Kind` bank, which skips 4. @@ -54,7 +69,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} +_LEN_HEADER = {"PPTH": 16, "PQTZ": 24, "PCOB": 24, "PCO2": 20, + "PVBR": 16, "PWAV": 20, "PWV2": 20} def _wrap(kind: str, body: bytes) -> bytes: @@ -92,72 +108,168 @@ def beatgrid_tag(beats: list[tuple[int, float, float]]) -> bytes: return _wrap("PQTZ", body) +# ---- what rekordbox needs before it will show a grid or cues ------------------ +# +# Measured on a rekordbox-written stick by removing tags one at a time: with +# only PPTH + PQTZ + PCOB in the `.DAT` — the grid and cue tags byte-for-byte +# rekordbox's own — rekordbox shows NO grid and NO hot cues. Adding PVBR alone +# is not enough, nor PWAV + PWV2 alone; the full `.DAT` is. So every `.DAT` +# carries all three. (The `.EXT` and `.2EX` waveforms only affect drawing.) + +#: PVBR's entry count: 400 seek points plus one trailing value. +_PVBR_ENTRIES = 401 + + +def vbr_tag(total_samples: int = 0) -> bytes: + """`PVBR` as rekordbox writes it for a constant-rate file. + + 400 zero seek offsets, then the track's length in SAMPLES — for an MP3, + frames x 1152 (Demo Track 1: 6601 x 1152 = 7604352). An `.m4a` gets zero + there too. A VBR MP3 presumably gets real offsets; none of the reference + tracks is VBR, so that is unmeasured, and a zero index is what an `.m4a` + carries and rekordbox accepts. + """ + body = struct.pack(">I", 0) + bytes(4 * (_PVBR_ENTRIES - 1)) + struct.pack( + ">I", max(0, int(total_samples))) + return _wrap("PVBR", body) + + +def mp3_samples(path: Path) -> int: + """An MP3's length in samples — frames x 1152 — for `PVBR`; 0 otherwise. + + rekordbox writes this value only for MP3s (every `.m4a` carries 0). + """ + if path.suffix.lower() != ".mp3": + return 0 + try: + import mutagen + + info = mutagen.File(str(path)).info + return int(round(info.length * info.sample_rate / 1152)) * 1152 + except Exception: # an unreadable header costs the seek hint, not the export + return 0 + + +#: PWAV height = K * sqrt(rms) + B, fitted against rekordbox's own previews of +#: eight tracks (mean error 3.4 on the 0-31 scale, correlation 0.8). An absolute +#: scale, not normalised per track — a quiet master draws smaller, as in rekordbox. +_PWAV_K, _PWAV_B = 37.6, -5.2 + + +def preview_tags(rms, brightness) -> list[bytes]: + """`PWAV` (400 columns) and `PWV2` (100) from per-column RMS and brightness. + + `PWAV`: one byte per column — whiteness (3 bits) << 5 | height (5 bits). + `PWV2`: a 4-bit height per group of four `PWAV` columns, scaled so the + track's tallest column is 15; that reproduces rekordbox's own to a mean + error of 1.7. Whiteness loosely follows brightness in rekordbox's output + (it is cosmetic: the colour of the blue-to-white preview). + """ + import numpy as np + + rms = np.asarray(rms, dtype=float) + heights = np.clip(np.round(_PWAV_K * np.sqrt(rms) + _PWAV_B), 0, 31).astype(int) + white = np.clip(np.round(2.5 + 10.0 * np.asarray(brightness, dtype=float)), 0, 5).astype(int) + pwav = bytes(int((w << 5) | h) for w, h in zip(white, heights)) + + tallest = max(int(heights.max()), 1) + grouped = heights.reshape(100, 4).max(axis=1) + pwv2 = bytes(int(v) for v in np.clip(np.round(grouped * 15 / tallest), 0, 15)) + return [ + _wrap("PWAV", struct.pack(">II", len(pwav), 0x10000) + pwav), + _wrap("PWV2", struct.pack(">II", len(pwv2), 0x10000) + pwv2), + ] + + +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, + by analogy with the all-zero PVBR every `.m4a` carries — not measured.""" + return preview_tags([0.0] * 400, [0.0] * 400) + + 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: + """One `PCP2` entry, byte-for-byte as rekordbox 7 writes it. + + Two constants in here are rekordbox's, not the documented struct's: the + `1000` after the kind (the struct calls it padding) and the `1` after the + colour id. Both appear in every entry of a real export; zeros there were a + guess, and pyrekordbox's parser would never notice one. + """ comment = b"" red, green, blue = rgb or (0, 0, 0) return struct.pack( - ">4sIIIB3xIIB7xHHI", - b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind, + ">4sIIIBxHIIBB6xHHI", + 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, beats or 0, 1 if beats else 0, len(comment), + 0, 1, beats or 0, 1 if beats else 0, len(comment), ) + comment + struct.pack(">4B", 0, red, green, blue) + bytes( PCP2_ENTRY_LEN - 48 - len(comment) ) -def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None, - first: int, last: int) -> bytes: +def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes: + """One `PCPT` entry, byte-for-byte as rekordbox 7 writes it. + + `len_header` is **28**, not 12: a reader that trusts it finds the body 16 + bytes early. + Status is 0 on a hot cue and 4 on a memory cue, and rekordbox leaves the + linked-list order fields at 0xFFFF rather than linking the entries. + """ return struct.pack( ">4sIIIIIHHBxHII", - b"PCPT", 12, PCPT_ENTRY_LEN, hot_cue, - 4 if loop_ms is not None else 4, # status: 4 = active, as rekordbox writes - 0x10000, first, last, kind, 1000, + b"PCPT", 28, PCPT_ENTRY_LEN, hot_cue, + 0 if hot_cue else 4, + 0x10000, 0xFFFF, 0xFFFF, kind, 1000, int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms), ) + bytes(16) +def _pcob(cue_type: int, chosen: list[dict]) -> bytes: + blob = b"".join( + _pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"], + loop_ms=c["loop_ms"]) + for c in chosen + ) + # cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong + # shifts every following field and the reader sees garbage. The last field + # is -1 on a hot-cue list and (count - 1) on a memory list, as rekordbox + # writes it. + last = -1 if cue_type == 1 else len(chosen) - 1 + return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(chosen), last) + blob) + + +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")) + for c in chosen + ) + return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob) + + def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]: - """`PCOB` (+ `PCO2` in the .EXT) for one track's cues. + """The cue tags for one file, in the order and shape rekordbox writes them. - `PCOB` is **split by pad**: the `.DAT` carries hot cues 1-3 and the `.EXT` - carries 4 and up, which is why the reader merges across both files. Memory - cues go in their own `PCOB` with `cue_type` 0. `PCO2` is the complete list - and only exists in the `.EXT`. + `.DAT`: `PCOB` hot (pads 1-3), `PCOB` memory (every memory cue). + `.EXT`: `PCOB` hot (pads 4 and up), `PCOB` memory (EMPTY), then `PCO2` hot + and `PCO2` memory — each the complete list of its kind. + + **Every list is written even when empty.** A rekordbox file always carries + all of them, and a file missing one is not a shape rekordbox produces. + Hot cues are ordered by pad, HIGHEST first, which is also what it does. """ - hot = [c for c in cues if c["hot_cue"]] - memory = [c for c in cues if not c["hot_cue"]] - tags: list[bytes] = [] - - # PCOB, one per kind, filtered to the pads this file is responsible for. - for cue_type, group in ((0, memory), (1, hot)): - chosen = [ - c for c in group - if not c["hot_cue"] or ((c["hot_cue"] > 3) == extended) - ] if cue_type == 1 else (group if not extended else []) - if not chosen: - continue - blob = b"".join( - _pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"], - loop_ms=c["loop_ms"], - first=0xFFFF if i == 0 else i, - last=i + 1 if i + 1 < len(chosen) else 0xFFFF) - for i, c in enumerate(chosen) - ) - # cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong - # shifts every following field and the reader sees garbage. - header = struct.pack(">IHHi", cue_type, 0, len(chosen), len(chosen)) - tags.append(_wrap("PCOB", header + blob)) - - if extended and cues: - 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")) - for c in cues - ) - header = struct.pack(">IHH", 1 if hot else 0, len(cues), 0) - tags.append(_wrap("PCO2", header + blob)) - return tags + hot = sorted((c for c in cues if c["hot_cue"]), key=lambda c: -c["hot_cue"]) + memory = sorted((c for c in cues if not c["hot_cue"]), key=lambda c: c["time_ms"]) + if not extended: + return [_pcob(1, [c for c in hot if c["hot_cue"] <= 3]), _pcob(0, memory)] + return [ + _pcob(1, [c for c in hot if c["hot_cue"] > 3]), + _pcob(0, []), + _pco2(1, hot), + _pco2(0, memory), + ] #: `PMAI` + len_header + len_file + four unknowns. diff --git a/backend/konduktor/adapters/rekordbox/beatgrid.py b/backend/konduktor/adapters/rekordbox/beatgrid.py index e9c9081..642e1ea 100644 --- a/backend/konduktor/adapters/rekordbox/beatgrid.py +++ b/backend/konduktor/adapters/rekordbox/beatgrid.py @@ -31,8 +31,18 @@ def markers_from_beats( ) -> list[GridMarker]: """Collapse a per-beat grid into the generic marker list. - `times` are seconds, `bpms` the tempo in force at each beat. A marker is - emitted for the first beat and wherever the tempo changes. + `times` are seconds, `bpms` the tempo in force at each beat, `beats` the + beat-in-bar (1-4) of each. A marker is emitted for the start of the grid and + wherever the tempo changes. + + **The first marker goes on the first DOWNBEAT**, not the first beat. In the + generic model the first marker is bar 1 (Traktor's convention), but a + Pioneer grid often starts mid-bar: Motorola's opens on beat 3 at 0.026 s, + with its first downbeat at 0.986 s. Put the marker on the first beat and + every bar lands two beats early — in Traktor after an import, and on the + CDJ after an export. The beats before it are not lost: a grid extends back + to the start of the track from its first marker, and `beats_from_markers` + writes them back numbered as they were. """ if not times or not bpms: return [] @@ -42,6 +52,12 @@ def markers_from_beats( if last_bpm is None or abs(bpm - last_bpm) > BPM_EPSILON: out.append(GridMarker(start=float(t), bpm=float(bpm), name=None, companion=None)) last_bpm = float(bpm) + if beats and out: + # The first tempo run ends where the second marker starts (or never). + run_end = out[1].start if len(out) > 1 else float("inf") + downbeat = next((t for t, b in zip(times, beats) if int(b) == 1 and t < run_end), None) + if downbeat is not None: + out[0] = out[0].model_copy(update={"start": float(downbeat)}) return out @@ -54,8 +70,10 @@ def beats_from_markers( Returns ``(beat_in_bar, bpms, times)`` with beat numbers cycling 1-4 from each marker, which is how Rekordbox numbers bars. - Not used by the read-only adapter, but it is the inverse of - `markers_from_beats` and belongs beside it. + The first marker's tempo also runs BACKWARDS to the start of the track: a + grid covers the whole track in Traktor and in rekordbox alike, and a marker + placed on the first downbeat (see `markers_from_beats`) has beats before it + — numbered 4, 3, … counting back, which reproduces rekordbox's own grid. """ beat_nums: list[int] = [] bpms: list[float] = [] @@ -63,6 +81,15 @@ def beats_from_markers( if not markers: return beat_nums, bpms, times ordered = sorted(markers, key=lambda m: m.start) + + first = next((m for m in ordered if m.bpm > 0), None) + if first is not None: + step = 60.0 / first.bpm + lead = int((first.start + 1e-9) // step) # whole beats that fit before it + for k in range(lead, 0, -1): + beat_nums.append((-k) % 4 + 1) + bpms.append(first.bpm) + times.append(first.start - k * step) for i, m in enumerate(ordered): if m.bpm <= 0: continue diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py index 8c1f88d..6652fbe 100644 --- a/backend/konduktor/adapters/rekordbox/export.py +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -57,11 +57,13 @@ from pathlib import Path from sqlalchemy import text from ...core.export import ExportPayload, ExportTrack, WrittenLibrary +from ...core import waveform from . import anlz_writer as W from .beatgrid import beats_from_markers from .capabilities import capabilities_for from .cue_types import kind_for from .projection import render_key +from .store import rekordbox_probe_suppressed log = logging.getLogger(__name__) @@ -132,13 +134,19 @@ class RekordboxExporter: self._seed_registry(db, models) self._seed_device(db, payload) rows = {} - for item in payload.tracks: + total = len(payload.tracks) + for n, item in enumerate(payload.tracks, start=1): + # Each track is decoded for its waveform: the slow part. + payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})") content = self._add_track(db, item) rows[item.source_id] = content ids[item.source_id] = str(content.ID) extra += self._write_anlz(item, content, root, db) self._write_playlists(db, payload, rows) - db.commit() + # A brand-new file: a running Rekordbox cannot have it open, so its + # process-wide veto protects nothing here. + with rekordbox_probe_suppressed(): + db.commit() finally: db.close() @@ -301,13 +309,22 @@ class RekordboxExporter: content.AnalysisUpdated = 1 db.flush() - tags = [W.path_tag(str(item.destination))] + # 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))] markers = item.cues.grid_markers if item.cues else [] if markers: - duration = float(item.track.length or 0) or (markers[-1].start + 60.0) + 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()) + 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. diff --git a/backend/konduktor/adapters/rekordbox/projection.py b/backend/konduktor/adapters/rekordbox/projection.py index 27cd735..41b547c 100644 --- a/backend/konduktor/adapters/rekordbox/projection.py +++ b/backend/konduktor/adapters/rekordbox/projection.py @@ -146,7 +146,8 @@ def to_track(row, cue_kinds=()) -> Track: rating=max(0, min(5, int(getattr(row, "Rating", 0) or 0))), playcount=getattr(row, "DJPlayCount", None), length=getattr(row, "Length", None), - bitrate=getattr(row, "BitRate", None), + # kbps here; the generic model (and the table) carry bits per second. + bitrate=(getattr(row, "BitRate", None) or 0) * 1000 or None, import_date=_iso_date(getattr(row, "StockDate", None)), last_played=None, # not modelled as a date in master.db release_date=_iso_date(getattr(row, "ReleaseDate", None)), @@ -163,7 +164,7 @@ def to_track(row, cue_kinds=()) -> Track: def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) -> TrackCues: """Project a track's cues and beatgrid. - `grid` is the per-beat ``(times, bpms)`` from the ANLZ file, collapsed here + `grid` is the per-beat ``(times, bpms, beats)`` from the ANLZ file, collapsed here into the generic marker list. Rekordbox pairs nothing with a grid marker, so `companion` is always None — that is a Traktor convention. @@ -177,8 +178,7 @@ def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) """ markers: list[GridMarker] = [] if grid is not None: - times, bpms = grid - markers = beatgrid.markers_from_beats(times, bpms) + markers = beatgrid.markers_from_beats(*grid) cues: list[CuePoint] = [] for c in cue_rows: diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index ebfc700..72ed480 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -29,6 +29,7 @@ from __future__ import annotations import json import logging import uuid +from contextlib import contextmanager from datetime import datetime from pathlib import Path @@ -44,6 +45,25 @@ from .cue_types import beat_loop_size, kind_for, role_and_slot log = logging.getLogger(__name__) +@contextmanager +def rekordbox_probe_suppressed(): + """Stop `pyrekordbox.commit()` refusing because a Rekordbox process exists. + + Its check is process-wide, not per-file: it refuses to write ANY database + while Rekordbox is open — including a temp copy, or a brand-new export + Rekordbox cannot possibly have open. Neutralising the probe for the call + keeps everything else `commit()` does. SQLite's own lock still applies. + """ + from pyrekordbox.masterdb import database as rb_database + + original = rb_database.get_rekordbox_pid + rb_database.get_rekordbox_pid = lambda *a, **kw: 0 + try: + yield + finally: + rb_database.get_rekordbox_pid = original + + def _iso_stamp(value) -> str: """Rekordbox writes timestamps in the JSON mirror as ISO-8601 with a +00:00 offset and millisecond precision (e.g. 2026-09-17T20:55:13.862+00:00). @@ -59,7 +79,7 @@ class RekordboxStore: def __init__(self, path: Path): self.path = Path(path) self._mapping = PathMapping() - self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {} + self._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {} self._journal = EditJournal() # Grid edits buffered until save(): ANLZ files are written to disk, so # applying them at command time would break the save contract. @@ -234,8 +254,10 @@ class RekordboxStore: return sum(1 for p in self.playlists() if int(p.Attribute or 0) != folder) # ---- analysis files (the beatgrid) ----------------------------------- - def anlz_grid(self, track_id: str) -> tuple[list[float], list[float]] | None: - """``(times_sec, bpms)`` per beat for a track, or None if unanalysed. + def anlz_grid(self, track_id: str) -> tuple[list[float], list[float], list[int]] | None: + """``(times_sec, bpms, beat_in_bar)`` per beat for a track, or None if + unanalysed. The beat numbers matter: they say where the first DOWNBEAT + is, which a grid starting mid-bar does not put first. Parsed on demand and cached — see the module docstring for why this is not done eagerly. @@ -269,7 +291,8 @@ class RekordboxStore: # pyrekordbox 0.4.4. if tag.type == "PQTZ": try: - return [float(t) for t in tag.times], [float(b) for b in tag.bpms] + return ([float(t) for t in tag.times], [float(b) for b in tag.bpms], + [int(b) for b in tag.beats]) except Exception: # noqa: BLE001 return None return None @@ -524,10 +547,9 @@ class RekordboxStore: "Rekordbox appears to be running; saving anyway. It may overwrite " "or re-sync the library while it is open." ) - original = rb_database.get_rekordbox_pid - rb_database.get_rekordbox_pid = lambda *a, **kw: 0 try: - self._db.commit(autoinc=True) + with rekordbox_probe_suppressed(): + self._db.commit(autoinc=True) except OperationalError as ex: # Suppressing pyrekordbox's veto does not remove SQLite's own lock: # a running Rekordbox really does hold the database, and the raw @@ -538,8 +560,6 @@ class RekordboxStore: "Rekordbox has the library open, so it cannot be written right " "now. Close Rekordbox and save again — your changes are still here." ) from ex - finally: - rb_database.get_rekordbox_pid = original @property def app_running(self) -> bool: @@ -589,7 +609,7 @@ class RekordboxStore: bpm = None grid = self.anlz_grid(track_id) if grid: - times, bpms = grid + times, bpms = grid[0], grid[1] for t, b in zip(times, bpms): if t <= start_sec: bpm = b @@ -800,8 +820,7 @@ class RekordboxStore: grid = self.anlz_grid(track_id) if grid is None: return [] - times, bpms = grid - return grid_math.markers_from_beats(times, bpms) + return grid_math.markers_from_beats(*grid) def track_duration(self, track_id: str) -> float: """Seconds, for expanding markers back into beats.""" @@ -829,7 +848,7 @@ class RekordboxStore: # Buffer as the same (times, bpms) shape the reader returns, so the # projection needs no special case for an unsaved grid. self._pending_grids[str(track_id)] = (beat_nums, bpms, times) - self._grid_cache[str(track_id)] = (times, bpms) if times else None + self._grid_cache[str(track_id)] = (times, bpms, beat_nums) if times else None # TEMPO mirrors the first marker, exactly as Traktor's does — # Rekordbox will not do it for us. row = self.content(track_id) diff --git a/backend/konduktor/core/export.py b/backend/konduktor/core/export.py index 9300cc5..c73959f 100644 --- a/backend/konduktor/core/export.py +++ b/backend/konduktor/core/export.py @@ -29,7 +29,7 @@ from __future__ import annotations from dataclasses import dataclass, field from pathlib import Path -from typing import Protocol, runtime_checkable +from typing import Callable, Protocol, runtime_checkable from .capabilities import Capabilities from .model import Track, TrackCues @@ -74,6 +74,11 @@ class ExportPayload: playlists: list[ExportPlaylist] = field(default_factory=list) #: The export's name, used for the folder its playlists are nested under. name: str = "Export" + #: Called by a writer before each slow step (e.g. decoding a track for its + #: waveform) with a message for the status bar. RAISES when the user has + #: cancelled — so a writer that analyses audio stays cancellable. The runner + #: sets it; a writer may call it freely and never needs to check for None. + checkpoint: Callable[[str], None] = field(default=lambda message: None, repr=False) @dataclass diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index 3fe93a7..977d416 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -55,7 +55,7 @@ class Track(BaseModel): rating: int = 0 # 0-5 stars (derived from RANKING/51) playcount: int | None = None length: int | None = None # seconds - bitrate: int | None = None + bitrate: int | None = None # bits per second (Pioneer libraries store kbps) # ISO-8601 "YYYY-MM-DD", normalised by the adapter. import_date: str | None = None last_played: str | None = None diff --git a/backend/konduktor/core/waveform.py b/backend/konduktor/core/waveform.py new file mode 100644 index 0000000..8c2d7c9 --- /dev/null +++ b/backend/konduktor/core/waveform.py @@ -0,0 +1,66 @@ +"""Per-column loudness and brightness of a track, for drawing a waveform OVERVIEW. + +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`). + +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. + +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. +""" +from __future__ import annotations + +import logging +from dataclasses import dataclass +from pathlib import Path + +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. +_BRIGHT_HZ = 2500.0 + + +@dataclass +class Columns: + """`n` equal slices of a track, start to end.""" + + #: RMS amplitude of each slice, on the decoded signal's 0-1 full scale. + rms: np.ndarray + #: Share of each slice's spectral energy above ~2.5 kHz, 0-1. + brightness: np.ndarray + #: Decoded length in seconds. + duration: float + + +def columns(path: Path, n: int) -> Columns | None: + """Measure `n` columns of `path`, or None when it cannot be decoded.""" + 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 + log.warning("could not decode %s for a waveform: %s", path, ex) + return None + if len(y) < n: + return None + + 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) + 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) diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py index 0bdb9d0..c8b5076 100644 --- a/backend/konduktor/exporter.py +++ b/backend/konduktor/exporter.py @@ -379,10 +379,15 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: ) ) + def checkpoint(message: str) -> None: + handle.raise_if_cancelled() + handle.progress(message=message) + payload = ExportPayload( name=export_set.name, tracks=payload_tracks, playlists=built.playlists, + checkpoint=checkpoint, ) before = _files(destination) libraries: list[tuple[str, Path]] = [] diff --git a/backend/test_export_pioneer.py b/backend/test_export_pioneer.py index a0542a4..d21d4ad 100644 --- a/backend/test_export_pioneer.py +++ b/backend/test_export_pioneer.py @@ -35,6 +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 failed = False @@ -181,5 +182,152 @@ for platform, reopen in ( check("nor did the tree", len(reopened.playlist_tree()) == 1) check("and it still reports its files", len(again.all_paths) == len(written.all_paths)) +print("\n== OneLibrary cue tags are rekordbox's BYTES, not merely parseable ==") +# pyrekordbox ignores `len_header` and the constants, so an early writer with a +# 12-byte PCPT header round-tripped through our own reader perfectly while +# rekordbox showed no cues and no grid. So: read the fixture's cues with the +# reader, pack them with the writer, and demand rekordbox's exact bytes back. +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 + +ol_root = Path(__file__).resolve().parent / "fixtures" / "onelibrary" +ol = OneLibraryDriver().open(ol_root) +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) + + +def _real_cue_tags(path: Path) -> list[bytes]: + b = path.read_bytes() + off, out = struct.unpack(">I", b[4:8])[0], [] + while off < len(b): + kind, length = b[off:off + 4], struct.unpack(">I", b[off + 8:off + 12])[0] + if kind in (b"PCOB", b"PCO2"): + out.append(b[off:off + length]) + off += length + return 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")): + real = _real_cue_tags(anlz.with_suffix(suffix)) + 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]) +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", + _file_type(Path("x.stem.m4a")) == 4 and _file_type(Path("x.MP3")) == 1) +check("bitrate is written in kbps", _kbps(320_000) == 320 and _kbps(None) is None) +check("the reader hands back bits per second, as the table expects", + all((t.bitrate or 0) >= 1000 for t in ol.tracks if t.bitrate)) + +print("\n== every OneLibrary .DAT carries what rekordbox needs to show a grid ==") +# Measured by stripping tags from a rekordbox-written stick: with only PPTH + +# PQTZ + PCOB in the .DAT, rekordbox shows NO grid and NO hot cues. PVBR alone +# is not enough, nor PWAV + PWV2 alone. +import numpy as np # noqa: E402 +import soundfile as sf # noqa: E402 + +from konduktor.core import waveform # noqa: E402 + +REKORDBOX_DAT_ORDER = [b"PPTH", b"PVBR", b"PQTZ", b"PWAV", b"PWV2", b"PCOB", b"PCOB"] + + +def _tag_kinds(path: Path) -> list[bytes]: + b = path.read_bytes() + off, out = struct.unpack(">I", b[4:8])[0], [] + while off < len(b): + out.append(b[off:off + 4]) + off += struct.unpack(">I", b[off + 8:off + 12])[0] + return out + + +def _tag(path: Path, kind: bytes) -> bytes: + b = path.read_bytes() + off = struct.unpack(">I", b[4:8])[0] + while off < len(b): + tl = struct.unpack(">I", b[off + 8:off + 12])[0] + if b[off:off + 4] == kind: + return b[off:off + tl] + off += tl + raise LookupError(kind) + + +wf_root = Path(tempfile.mkdtemp()) +# Placeholder bytes nothing can decode: the grid must STILL be accepted. +dead = wf_root / "Contents" / "dead.mp3" +dead.parent.mkdir(parents=True) +dead.write_bytes(b"\0" * 4096) +# Real audio: 8 s of continuous noise, loud for the first half, quiet after. +# (Continuous: a column is 20 ms here, so sparse clicks would leave most silent.) +sr = 22050 +tone = np.random.default_rng(0).uniform(-1, 1, sr * 8).astype(np.float32) +tone[: sr * 4] *= 0.5 +tone[sr * 4:] *= 0.02 +live = wf_root / "Contents" / "live.wav" +sf.write(live, tone, sr) + +grid = TrackCues(track_id="x", cues=[], grid_markers=[GridMarker(start=0.0, bpm=125.0)]) +dead_t = cued.model_copy(update={"id": "dead", "title": "dead"}) +live_t = cued.model_copy(update={"id": "live", "title": "live", "length": 8}) +seen: list[str] = [] +wf_written = core_export.for_platform("onelibrary").write( + ExportPayload(name="WF", tracks=[ExportTrack(track=dead_t, destination=dead, cues=grid), + ExportTrack(track=live_t, destination=live, cues=grid)], + checkpoint=seen.append), + wf_root, +) +dats = [p for p in wf_written.extra if p.suffix == ".DAT"] +check("two tracks, two .DAT files", len(dats) == 2) +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)) +pvbr = _tag(dats[0], b"PVBR") +check("PVBR is 400 seek points plus a trailing length, as rekordbox writes", + len(pvbr) == 1620, len(pvbr)) +check("the writer reported each track to the status bar", + len(seen) == 2 and all("Analysing" in m for m in seen), seen) + +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", + cols is not None and cols.rms[:200].mean() > 5 * cols.rms[200:].mean()) +check("undecodable bytes are no overview, not an error", waveform.columns(dead, 400) is None) +heights = {dat: np.frombuffer(_tag(dat, b"PWAV")[20:], np.uint8) & 31 for dat in dats} +check("the undecodable file still gets a (flat) preview", any(h.max() == 0 for h in heights.values())) +check("the decodable one gets a real one, loud where the audio is loud", + any(h[:200].mean() > h[200:].mean() + 3 for h in heights.values())) + + +class _Stop(Exception): + pass + + +def _cancel_on_second(message: str, calls=[]): # noqa: B006 — deliberate counter + calls.append(message) + if len(calls) == 2: + raise _Stop() + + +try: + core_export.for_platform("onelibrary").write( + ExportPayload(name="WF", tracks=[ExportTrack(track=dead_t, destination=dead, cues=grid), + ExportTrack(track=live_t, destination=live, cues=grid)], + checkpoint=_cancel_on_second), + wf_root, + ) + check("a cancel between tracks stops the writer", False, "it finished") +except _Stop: + check("a cancel between tracks stops the writer", True) + print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) raise SystemExit(1 if failed else 0) diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index a0f4556..67299ce 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -115,6 +115,27 @@ check("expanding one marker gives a beat every 0.5s at 120 BPM", out_times == [0 check("beats are numbered 1-4 in bars", beat_nums == [1, 2, 3, 4], str(beat_nums)) check("expanding no markers gives no beats", beats_from_markers([], 10.0) == ([], [], [])) +print("== beatgrid: a grid that starts MID-BAR keeps its bar phase ==") +# Measured on a real rekordbox export: Motorola's grid opens on beat 3 at +# 0.026 s. The generic first marker is bar 1, so it must sit on the first +# DOWNBEAT — on the first beat, every bar lands two beats early. +step = 60.0 / 125.0 +mb_times = [round(0.026 + i * step, 3) for i in range(12)] +mb_beats = [(i + 2) % 4 + 1 for i in range(12)] # 3, 4, 1, 2, 3, … +mb = markers_from_beats(mb_times, [125.0] * 12, mb_beats) +check("the first marker is the first downbeat, not the first beat", + len(mb) == 1 and abs(mb[0].start - 0.986) < 1e-9, [m.start for m in mb]) +nums, _, back = beats_from_markers(mb, mb_times[-1] + step / 2) +check("expanding it restores the beats BEFORE the marker", [round(t, 3) for t in back] == mb_times, + [round(t, 3) for t in back][:4]) +check("numbered exactly as rekordbox numbered them", nums == mb_beats, nums[:6]) +check("without beat numbers the old behaviour holds", + markers_from_beats(mb_times, [125.0] * 12)[0].start == 0.026) +# A downbeat is only looked for inside the FIRST tempo run. +tc = markers_from_beats([0.0, 0.5, 1.0, 1.4], [120.0, 120.0, 150.0, 150.0], [3, 4, 1, 2]) +check("a downbeat after a tempo change does not move the first marker", + [m.start for m in tc] == [0.0, 1.0], [m.start for m in tc]) + # ---- the rest needs a real library -------------------------------------- found = discovery.detect_libraries() if not found: