diff --git a/CLAUDE.md b/CLAUDE.md index 05f9654..58d7b78 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -877,7 +877,16 @@ serialization path.** It enforces: entries renumbered) plus, after the commit, its ANLZ files and their emptied folder. Artwork is left (unmeasured: `_m`/`_s` sizes are not in `contentFile`), and a track in a table that was empty when measured (Sampler, - History, Tag List, My Tag, …) is refused with nothing changed. + History, Tag List, My Tag, …) is refused with nothing changed. And **adding + tracks** (J) on generated kick-track MP3s: a raising `checkpoint` cancels + before the library is touched; nothing reaches disk before save; afterwards + only INSERTs (plus the counter) into the tables Rekordbox writes for a new + track, the row filled from the file and stamped with the library's device, + one `contentFile` per analysis file + `artwork.jpg` whose Hash is the MD5; + a plain file gets Konduktor's grid ON the kick, a source's grid, hot cue + (pad, colour), loop and memory cue cross as themselves; and removing it + deletes its analysis files. `test_folders.py` drives the same through + `/api/folder/add` on a Rekordbox copy, and a non-addable library 422s. - `test_onelibrary_adapter.py` — the third adapter against the same contract. Unlike the Rekordbox tests it needs **nothing installed and nothing plugged in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed @@ -1217,6 +1226,26 @@ that number and nothing else — everything derives from it: `AUDIO_ID` and `LOUDNESS` are left empty — they are Traktor's own analysis outputs and cannot be computed; **verified that Traktor loads and plays such entries** and re-analyses them. + **Rekordbox implements it too** (2026-10-01; gated on `tracks.addable`, + which the folder menu, the folder header and the device Import button read + from the COLLECTION's capabilities). Unlike Traktor it must ANALYSE: a + Rekordbox grid and waveform live in the ANLZ files, without which Rekordbox + shows neither grid nor cues. So `add_tracks` decodes each file once + (`waveform.decode` → `analyse_samples` + `grid_detect`), in a first phase + that may be cancelled through `checkpoint` before the library is touched; + a file with no grid of its own gets Konduktor's (decided: arrive ready to + prep). Then `RekordboxStore.add_track` writes the row the way Rekordbox's + own add was MEASURED to (file facts, `DateCreated` from the file's birth + time, this library's device) and the grid/cues replay through + `replace_grid`/`set_cue`/`add_memory_cue` — memory cues and colours cross + as themselves, a hot cue with no free pad becomes a memory cue. Its ANLZ + files and artwork (`NewTrack.art`, else the file's embedded cover) are + held until save and written BEFORE the grids and commit, then + `contentFile` rows hash what was written (`_m`/`_s` unlisted, as + Rekordbox does); a failed save removes them. Key, mixer gain and phrases + are Rekordbox's own analysis and are not written. The row and file + builders live in `adapters/rekordbox/new_content.py`, shared with the + Rekordbox Library exporter. - **`jobs.py` + `importer.py`** — the app's first long-running operation. Thread per job, polling, cooperative cancel; deliberately not asyncio or SSE. **Ordering is the safety property**: audio copies first and the library is diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index 1ab7c70..6f7aa5d 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -251,7 +251,7 @@ class OneLibraryAdapter: def _refuse(self, what: str): raise Unsupported(self._readonly_reason(what)) - def add_tracks(self, items: list) -> list[str]: + def add_tracks(self, items: list, *, checkpoint=None) -> list[str]: self._refuse("Adding tracks") def remove_tracks(self, track_ids: list[str]) -> int: diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index e38e5d4..fa39f2b 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -27,7 +27,7 @@ from ...core.model import GridMarker, PlaylistNode, Track, TrackCues from ...core.pathmap import PathMapping, common_dir_prefix from ...core.query import TrackIndex from . import capabilities as caps -from . import palette, projection +from . import palette, projection, timebase from .store import RekordboxStore @@ -412,13 +412,84 @@ class RekordboxAdapter: if self._cloud_synced: raise Unsupported(self._readonly_reason(what)) - def add_tracks(self, items: list) -> list[str]: - # Not a refusal in principle — Rekordbox could receive imported - # tracks — but adding one means a djmdContent row, its lookup-table - # foreign keys, a USN, and an ANLZ file built from scratch, which - # is unexplored (see the export handoff). Traktor is the only - # import target for now. - self._refuse("Adding tracks") + def add_tracks(self, items: list, *, checkpoint=None) -> list[str]: + """Add tracks that came from somewhere else, with their prep. + + Rekordbox keeps the beatgrid AND the waveforms in per-track analysis + files, and shows neither grid nor cues for a track without them — so + unlike Traktor, which re-analyses on load, every file is decoded here. + A file that brings no grid gets one from Konduktor's own detector + (decided 2026-10-01: a track should arrive ready to prep). + + Two phases, and the split is the point. FIRST every file is decoded and + analysed, which is slow and may be cancelled through `checkpoint` — + before the library is touched, so a cancel leaves it as it was. THEN + each row is added and its grid and cues replayed through the ordinary + store commands (`replace_grid`, `set_cue`), so an added track inherits + their conventions and tests rather than growing a second copy. + + Nothing is lost on the way in: Rekordbox has memory cues and coloured + cues, so both cross as themselves. A hot cue whose pad is out of the + bank or already taken becomes a memory cue at the same position rather + than being dropped. + """ + from ...core import audio_tags, grid_detect, waveform + + self._require_writable("Adding tracks") + held = set(self._store.all_audio_paths()) + prepared = [] + total = len(items) + for n, item in enumerate(items, start=1): + audio = Path(item.audio_path) + if checkpoint is not None: + checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})", + step=n, of=total) + if not audio.is_file(): + raise InvalidCommand(f"No audio file at {audio}") + if str(audio) in held: + raise InvalidCommand(f"The library already holds {audio}") + held.add(str(audio)) + samples = waveform.decode(audio) + measured = waveform.analyse_samples(samples, lead=timebase.offset(audio)) + markers = list(item.cues.grid_markers) if item.cues else [] + if not markers and samples is not None: + try: + found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR) + markers = [GridMarker(start=found.anchor, bpm=found.bpm)] + except ValueError: + pass # no pulse to fit (a one-shot, silence): no grid + art = item.art or audio_tags.read_cover(audio) + prepared.append((item, audio, measured, markers, art[0] if art else None)) + + added: list[str] = [] + for item, audio, measured, markers, art in prepared: + track_id = self._store.add_track( + audio, item.track, measured=measured, with_grid=bool(markers), art=art) + self._index.add(projection.to_track(self._store.content(track_id), ())) + if markers: + self._store.replace_grid(track_id, markers) + if item.cues is not None: + self._place_imported_cues(track_id, item.cues) + self._refresh(track_id) + added.append(track_id) + return added + + def _place_imported_cues(self, track_id: str, cues) -> None: + """Hot cues on their own pads; memory cues — and a hot cue with no + free pad — as memory cues. Colour as the nearest palette swatch.""" + taken: set[int] = set() + for cue in sorted(cues.cues or [], key=lambda c: c.start): + cue_type = "loop" if getattr(cue, "length", 0) else "cue" + code, _rgb = palette.code_for(cue.color) + common = dict(start_sec=cue.start, cue_type=cue_type, + length_sec=getattr(cue, "length", 0.0) or 0.0, + name=getattr(cue, "name", None), color_code=code or None) + slot = cue.slot if cue.role == "hotcue" else None + if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken: + self._store.set_cue(track_id, slot=slot, **common) + taken.add(slot) + else: + self._store.add_memory_cue(track_id, **common) def remove_tracks(self, track_ids: list[str]) -> int: # What goes with a track was measured in Rekordbox 7 — see the store. diff --git a/backend/konduktor/adapters/rekordbox/anlz_writer.py b/backend/konduktor/adapters/rekordbox/anlz_writer.py index a0661e9..599f8d5 100644 --- a/backend/konduktor/adapters/rekordbox/anlz_writer.py +++ b/backend/konduktor/adapters/rekordbox/anlz_writer.py @@ -404,13 +404,18 @@ def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]: _FILE_HEADER_LEN = 28 -def write_anlz(path: Path, tags: list[bytes]) -> Path: - """Assemble and write an ANLZ file from built tag bytes.""" - path.parent.mkdir(parents=True, exist_ok=True) +def anlz_bytes(tags: list[bytes]) -> bytes: + """Assemble an ANLZ file from built tag bytes.""" body = b"".join(tags) header = struct.pack( ">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body), FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0, ) - path.write_bytes(header + body) + return header + body + + +def write_anlz(path: Path, tags: list[bytes]) -> Path: + """Assemble and write an ANLZ file from built tag bytes.""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(anlz_bytes(tags)) return path diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index b0a97c6..36bbb5c 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -88,6 +88,7 @@ def capabilities_for( editable_fields=sorted(editable_fields or []), media_kinds=["audio"], removable=True, + addable=True, artwork=False, artwork_note=None, ), diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py index 3368856..670a294 100644 --- a/backend/konduktor/adapters/rekordbox/export.py +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -58,8 +58,7 @@ from sqlalchemy import text from ...core.export import ExportPayload, ExportTrack, WrittenLibrary from ...core.cue_colors import effective_color -from . import anlz_writer as W -from . import artwork, palette +from . import new_content, palette from . import timebase from .beatgrid import beats_from_markers from .capabilities import capabilities_for @@ -82,15 +81,8 @@ SEED = _FIXTURES / "seed.sql" #: Rekordbox counts cue positions in frames at 150 fps, not milliseconds. FRAMES_PER_SECOND = 150 -#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving -#: five tracks of a Konduktor-written library different values and loading it -#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?" -#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here, -#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's -#: MP3/M4A tracks carry — adds two more bits that draw an extra badge, most -#: likely claiming phrase/vocal analysis this exporter does not write. So the -#: value that claims only what is written: 0x2C060E. -CONTENT_LINK = 2885134 +#: `djmdContent.ContentLink` — see `new_content`, where its bits are measured. +CONTENT_LINK = new_content.CONTENT_LINK #: Rekordbox's playlist side file, beside master.db. It lists every playlist #: node with a `Timestamp` matching the row's `updated_at` (ms); a playlist the @@ -319,27 +311,7 @@ class RekordboxExporter: @staticmethod def _lookup(db, kind: str, name: str | None): - """Find-or-create a lookup row, returning its id. - - `djmdKey` is the odd one out twice over: its name column is `ScaleName`, - not `Name`, and pyrekordbox has no `add_key`. So keys are inserted - directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI. - """ - if not name: - return None - if kind == "key": - found = db.get_key(ScaleName=name).first() - if found is not None: - return found.ID - return _insert_key(db, name) - found = {"artist": db.get_artist, "album": db.get_album, - "genre": db.get_genre, "label": db.get_label}[kind](Name=name).first() - if found is not None: - return found.ID - created = {"artist": db.add_artist, "album": db.add_album, - "genre": db.add_genre, "label": db.add_label}[kind](name) - db.flush() - return created.ID + return new_content.lookup(db, kind, name) # ---- analysis --------------------------------------------------------------- @@ -350,24 +322,15 @@ class RekordboxExporter: and the file on disk have to agree — so the same derivation is used here rather than a path of our own choosing. """ - track_uuid = str(content.UUID) - # Rekordbox derives these two levels from the track's UUID, and the - # column and the file have to agree — so the same derivation is used. - rel = f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT" + rel = new_content.anlz_rel(str(content.UUID)) content.AnalysisDataPath = rel content.Analysed = 105 # what a rekordbox-analysed track carries content.AnalysisUpdated = 1 db.flush() - # 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 = item.waveform(lead=off) - path = str(item.destination) - tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(item.destination))] + beats = None markers = item.cues.grid_markers if item.cues else [] if markers: duration = ((measured.duration if measured else 0.0) @@ -377,26 +340,18 @@ class RekordboxExporter: # 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) + beats = [(n, bpm, timebase.to_pioneer(t, off)) + for n, bpm, t in zip(nums, bpms, times)] # 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. 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])) + written = [] + for suffix, data in new_content.anlz_files(item.destination, measured, beats).items(): + target = dat.with_suffix(suffix) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + written.append(target) return written # ---- artwork ------------------------------------------------------------------ @@ -412,17 +367,14 @@ class RekordboxExporter: rooted at `share/` like `AnalysisDataPath`. All measured on a real Rekordbox 7 library. """ - if not item.art: + files = new_content.artwork_files(item.art[0] if item.art else None) + if files is None: return [] - jpegs = artwork.library_jpegs(item.art[0]) - if jpegs is None: - return [] - track_uuid = str(content.UUID) - rel = f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}" + rel = new_content.artwork_rel(str(content.UUID)) folder = root / "share" / rel.lstrip("/") folder.mkdir(parents=True, exist_ok=True) written = [] - for name, data in zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs): + for name, data in files.items(): (folder / name).write_bytes(data) written.append(folder / name) content.ImagePath = f"{rel}/artwork.jpg" @@ -462,20 +414,3 @@ class RekordboxExporter: db.add_to_playlist(playlist, content) db.flush() - -def _insert_key(db, name: str) -> str: - """A `djmdKey` row. Raw SQL for the same reason the registry row is: the - ORM's DateTime binder raises on the NULLs a real row carries.""" - from pyrekordbox.masterdb import models - - now = datetime.now().isoformat(sep=" ", timespec="milliseconds") - seq = (db.query(models.DjmdKey).count() or 0) + 1 - key_id = str(uuidlib.uuid4().int % 2_147_483_647) - db.session.execute( - text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, ' - "updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"), - {"id": key_id, "name": name, "seq": seq, - "uuid": str(uuidlib.uuid4()), "now": now}, - ) - db.flush() - return key_id diff --git a/backend/konduktor/adapters/rekordbox/new_content.py b/backend/konduktor/adapters/rekordbox/new_content.py new file mode 100644 index 0000000..f8e39c5 --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/new_content.py @@ -0,0 +1,138 @@ +"""A NEW track's rows and files in a `master.db` library. + +Shared by the two places a track is created rather than edited: the Rekordbox +Library exporter (a `master.db` from nothing) and `RekordboxStore.add_tracks` +(a track added to the user's own library). One definition, because a track +row, its lookups and its analysis files are the same thing in both, and two +copies would drift. + +What a track Rekordbox itself adds looks like was MEASURED (two files dragged +into Rekordbox 7.2's collection, 2026-10-01, every row and file diffed): a +`djmdContent` row, three ANLZ files plus a `.3EX`, the embedded cover as three +JPEGs, one `contentFile` row per file (its `Hash` the file's MD5), and its own +analysis results — key, mixer gain, phrases — which nothing here can produce. +""" +from __future__ import annotations + +import uuid as uuidlib +from datetime import datetime +from pathlib import Path + +from sqlalchemy import text + +from . import anlz_writer as W +from . import artwork + +#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving +#: five tracks of a Konduktor-written library different values and loading it +#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?" +#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here, +#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's +#: MP3/M4A tracks carry, and what Rekordbox writes for a track it analyses +#: itself — adds two more bits that draw an extra badge, most likely claiming +#: phrase/vocal analysis Konduktor does not write. So the value that claims +#: only what is written: 0x2C060E. +CONTENT_LINK = 2885134 + + +def anlz_rel(track_uuid: str) -> str: + """`djmdContent.AnalysisDataPath` for a track. Rekordbox derives it from + the track's UUID, and the column and the file have to agree.""" + return f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT" + + +def artwork_rel(track_uuid: str) -> str: + """The track's artwork FOLDER — the same UUID split as its analysis.""" + return f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}" + + +def anlz_files(audio: Path, measured, beats: list | None) -> dict[str, bytes]: + """The analysis files for a track, by suffix: `.DAT`, `.EXT`, `.2EX`. + + The same 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. `measured` is `waveform.analyse`'s result (None: flat previews). + `beats` is `(beat-in-bar, bpm, seconds)` ON REKORDBOX'S CLOCK; None writes + no `PQTZ`, and `[]` an empty one for `write_pqtz` to fill later. + """ + path = str(audio) + tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(audio))] + if beats is not None: + tags.append(W.beatgrid_tag(beats)) + 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) + out = { + ".DAT": W.anlz_bytes(tags), + ".EXT": W.anlz_bytes([W.path_tag(path), *ext_waves[:1], + *W.cue_tags([], extended=True), *ext_waves[1:]]), + } + if two_ex: + out[".2EX"] = W.anlz_bytes([W.path_tag(path), *two_ex]) + return out + + +def artwork_files(art: bytes | None) -> dict[str, bytes] | None: + """The cover as a rekordbox-managed track carries it, by file name. + + `artwork.jpg` (the cover, fit to 800 px), `artwork_m.jpg` (240) and + `artwork_s.jpg` (80), the last two letterboxed square; `djmdContent. + ImagePath` names `artwork.jpg`. All measured on a real Rekordbox 7 library. + None when there is no art or it cannot be read. + """ + if not art: + return None + jpegs = artwork.library_jpegs(art) + if jpegs is None: + return None + return dict(zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs)) + + +def lookup(db, kind: str, name: str | None): + """Find-or-create a lookup row, returning its id. + + Lookups are foreign keys; pyrekordbox's `add_*` RAISES on an existing name, + so every one is find-or-create — the same rule the in-place adapter follows. + `djmdKey` is the odd one out twice over: its name column is `ScaleName`, + not `Name`, and pyrekordbox has no `add_key`. So keys are inserted + directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI. + """ + if not name: + return None + if kind == "key": + found = db.get_key(ScaleName=name).first() + if found is not None: + return found.ID + return insert_key(db, name) + found = {"artist": db.get_artist, "album": db.get_album, + "genre": db.get_genre, "label": db.get_label}[kind](Name=name).first() + if found is not None: + return found.ID + created = {"artist": db.add_artist, "album": db.add_album, + "genre": db.add_genre, "label": db.add_label}[kind](name) + db.flush() + return created.ID + + +def insert_key(db, name: str) -> str: + """A `djmdKey` row. Raw SQL: the ORM's DateTime binder raises on the NULLs + a real row carries.""" + from pyrekordbox.masterdb import models + + now = datetime.now().isoformat(sep=" ", timespec="milliseconds") + seq = (db.query(models.DjmdKey).count() or 0) + 1 + key_id = str(uuidlib.uuid4().int % 2_147_483_647) + db.session.execute( + text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, ' + "updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"), + {"id": key_id, "name": name, "seq": seq, + "uuid": str(uuidlib.uuid4()), "now": now}, + ) + db.flush() + return key_id diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 0e50d53..e882b45 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -51,6 +51,33 @@ from .cue_types import beat_loop_size, kind_for, role_and_slot log = logging.getLogger(__name__) + +def _file_facts(audio: Path) -> dict: + """What Rekordbox reads off the file itself for a new track's row.""" + from datetime import date + + out: dict = {} + try: + st = audio.stat() + born = getattr(st, "st_birthtime", None) or st.st_mtime + out["created"] = date.fromtimestamp(born) + except OSError: + pass + try: + import mutagen + + info = mutagen.File(str(audio)).info + out["length"] = int(round(info.length)) if info.length else None + if getattr(info, "bitrate", None): + out["bitrate"] = int(round(info.bitrate / 1000)) # kbps, as Rekordbox stores it + if getattr(info, "sample_rate", None): + out["sample_rate"] = int(info.sample_rate) + if getattr(info, "bits_per_sample", None): + out["bit_depth"] = int(info.bits_per_sample) + except Exception: # noqa: BLE001 — facts are a nicety; the row stands without them + log.debug("could not read %s", audio, exc_info=True) + return out + # Where a track's analysis files live, as `contentFile.Path` spells it. _ANLZ_ROOT = "/PIONEER/USBANLZ/" @@ -97,6 +124,9 @@ class RekordboxStore: # Analysis/artwork files of removed tracks, `share`-relative, deleted # by save() AFTER the commit — a failed commit must leave them in place. self._pending_file_removals: set[str] = set() + # Files of ADDED tracks, `share`-relative path -> bytes, written by + # save() BEFORE the commit (and removed again if it fails). + self._pending_new_files: dict[str, bytes] = {} self._load() # ---- open ------------------------------------------------------------ @@ -130,6 +160,7 @@ class RekordboxStore: self._journal = EditJournal() self._pending_grids.clear() self._pending_file_removals.clear() + self._pending_new_files.clear() self._load() def close(self) -> None: @@ -532,13 +563,140 @@ class RekordboxStore: .filter(t.DjmdSongPlaylist.PlaylistID == str(node_id)) .all() ) + # NOT `remove_from_playlist`: it commits, which wrote an unsaved edit + # to disk (beyond Discard's reach) and raised while Rekordbox ran. + # The list is rebuilt from 1 below, so no renumbering is needed. for song in existing: - self._db.remove_from_playlist(playlist, song) + self._db.delete(song) + self._db.flush() for n, track_id in enumerate(track_ids, start=1): self._db.add_to_playlist(playlist, str(track_id), track_no=n) self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids)) return len(track_ids) + # ---- writes: adding tracks --------------------------------------------- + # + # MEASURED, by dragging two files into Rekordbox 7.2's collection and + # diffing (2026-10-01): see `new_content`. Rekordbox fills the row from the + # FILE (size, sample rate, bit rate, and `DateCreated` from the file's + # creation date), stamps it with this library's device, and lists every + # file it writes for the track in `contentFile` with the file's MD5. + def add_track(self, audio: Path, track, *, measured, with_grid: bool, + art: bytes | None) -> str: + """Add one track's row, return its id. Its analysis files and artwork + are held until save(); its grid and cues are the caller's to replay + through the ordinary commands. `with_grid` reserves an empty `PQTZ` + in the `.DAT` for `replace_grid` to fill.""" + from . import new_content + from .projection import render_key + + audio = Path(audio) + if not audio.is_file(): + raise InvalidCommand(f"No audio file at {audio}") + t = self._tables + if self._db.session.query(t.DjmdContent).filter_by(FolderPath=str(audio)).count(): + raise InvalidCommand(f"The library already holds {audio}") + facts = _file_facts(audio) + content = self._db.add_content( + str(audio), + Title=track.title or audio.stem, + Length=facts.get("length") or track.length, + BitRate=facts.get("bitrate") or (int(track.bitrate / 1000) if track.bitrate else None), + SampleRate=facts.get("sample_rate"), + BitDepth=facts.get("bit_depth", 16), + Rating=track.rating or 0, + Commnt=track.comment or "", + ReleaseDate=track.release_date or "", + ) + year = str(track.release_date or "")[:4] + if year.isdigit(): + content.ReleaseYear = int(year) + if facts.get("created"): + content.DateCreated = facts["created"] + content.ArtistID = new_content.lookup(self._db, "artist", track.artist) + content.AlbumID = new_content.lookup(self._db, "album", track.album) + content.GenreID = new_content.lookup(self._db, "genre", track.genre) + content.LabelID = new_content.lookup(self._db, "label", track.label) + # Rendered from the wheel, never copied: the source's notation is not + # Rekordbox's ("10m" is "Cm" here). + content.KeyID = new_content.lookup( + self._db, "key", render_key(track.key_wheel, track.key_mode)) + content.ContentLink = new_content.CONTENT_LINK + + track_uuid = str(content.UUID) + rel = new_content.anlz_rel(track_uuid) + content.AnalysisDataPath = rel + content.Analysed = 105 # what a rekordbox-analysed track carries + content.AnalysisUpdated = 1 + files = new_content.anlz_files(audio, measured, [] if with_grid else None) + for suffix, data in files.items(): + self._pending_new_files[str(Path(rel).with_suffix(suffix))] = data + art_files = new_content.artwork_files(art) + if art_files: + folder = new_content.artwork_rel(track_uuid) + for name, data in art_files.items(): + self._pending_new_files[f"{folder}/{name}"] = data + content.ImagePath = f"{folder}/artwork.jpg" + self._db.flush() + + track_id = str(content.ID) + if self._content_cache is not None and self._by_id is not None: + self._content_cache.append(content) + self._by_id[track_id] = content + self._grid_cache.pop(track_id, None) + self._journal.record("track", "add", track_id) + return track_id + + def _write_new_files(self) -> list[Path]: + """Write added tracks' files; return what was written.""" + share = self.path.parent / "share" + written: list[Path] = [] + try: + for rel, data in self._pending_new_files.items(): + path = share / rel.lstrip("/") + path.parent.mkdir(parents=True, exist_ok=True) + written.append(path) # before the write: a partial file is cleaned too + path.write_bytes(data) + except BaseException: + for path in written: + path.unlink(missing_ok=True) + raise + return written + + def _add_content_files(self, written: list[Path]) -> None: + """One `contentFile` row per file an added track carries, as Rekordbox + writes them: `Hash` is the file's MD5, and its `_m`/`_s` artwork sizes + are not listed.""" + import hashlib + from urllib.parse import quote + + t = self._tables + share = self.path.parent / "share" + by_folder = {} + for row in self.iter_content(): + for rel in (row.AnalysisDataPath, row.ImagePath): + if rel: + by_folder[str(Path(rel).parent)] = row + for path in written: + if path.name in ("artwork_m.jpg", "artwork_s.jpg"): + continue + rel = "/" + path.relative_to(share).as_posix() + row = by_folder.get(str(Path(rel).parent)) + if row is None: + continue + self._db.add(t.ContentFile( + ID=f"{row.UUID}_{quote(rel, safe='')}", + ContentID=str(row.ID), + Path=rel, + Hash=hashlib.md5(path.read_bytes()).hexdigest(), + Size=path.stat().st_size, + rb_local_path=str(path), + UUID=str(uuid.uuid4()), + created_at=datetime.now(), + updated_at=datetime.now(), + )) + self._db.flush() + # ---- writes: removing tracks ------------------------------------------- # # MEASURED, by removing a track in Rekordbox 7.2 and diffing every row and @@ -695,9 +853,19 @@ class RekordboxStore: """ summary = self._journal.summary() # Files first: if an analysis file cannot be written, nothing should have - # been committed to the database either. - self._flush_grids() - self._commit() + # been committed to the database either. An added track's files go + # before the grids, which write into them, and their `contentFile` + # rows after, which hash what was finally written. + written = self._write_new_files() + try: + self._flush_grids() + self._add_content_files(written) + self._commit() + except BaseException: + for path in written: + path.unlink(missing_ok=True) + raise + self._pending_new_files.clear() self._delete_removed_files() self._journal.clear() # Reads go through the same session, so nothing needs re-projecting from diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 42f93a8..6576cf7 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -173,7 +173,7 @@ class TraktorAdapter: return result # ---- adding tracks ---------------------------------------------------- - def add_tracks(self, items: list) -> list[str]: + def add_tracks(self, items: list, *, checkpoint=None) -> list[str]: """Add tracks that came from somewhere else, with their prep. Two steps, and the split is the point. The store creates a bare ENTRY — @@ -195,6 +195,7 @@ class TraktorAdapter: type, so a free RGB value has nowhere to go. Returns the new track ids, in the order the items were given. + `checkpoint` is unused: nothing here is slow (Traktor analyses on load). """ added: list[str] = [] for item in items: diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index b57ccd6..59dd4b0 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -62,6 +62,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: editable_fields=sorted(editable_fields), media_kinds=["audio", "stem"], removable=True, + addable=True, stem_convertible=True, # `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA, # but only on Windows, and a file added on one OS must play on both. diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 1a7d539..667bfdb 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -73,6 +73,11 @@ class NewTrack: track: Track audio_path: Path cues: TrackCues | None = None + # The cover as the SOURCE library shows it — `(bytes, mime)` from its + # `cover_art` — since a library's art is not always embedded in the file. + # For a platform that keeps its own copy of the art (Rekordbox); one that + # reads the file's tags (Traktor) ignores it. + art: tuple[bytes, str] | None = None @dataclass(frozen=True) @@ -173,7 +178,13 @@ class LibraryAdapter(Protocol): # fidelity guarantee hold. A new entry has no parsed original, so the rule # becomes "an added entry must not perturb any existing one" — which is # what `test_save_fidelity.py` checks rather than taking on trust. - def add_tracks(self, items: list["NewTrack"]) -> list[str]: ... + # + # `checkpoint(message, step, of)` is called before each slow step (a + # platform that must ANALYSE what it adds, like Rekordbox, decodes every + # file) and may raise to cancel; it is only ever called before the library + # is touched, so a cancel leaves it as it was. Gated on + # `capabilities().tracks.addable`. + def add_tracks(self, items: list["NewTrack"], *, checkpoint=None) -> list[str]: ... # Remove tracks from the library — and so from every playlist, since an # entry naming a track the library no longer has is a dangling reference. diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index 9efe1a5..85d2daa 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -63,6 +63,9 @@ class TrackCapabilities(BaseModel): # Tracks can be removed from the library (and so from its playlists). The # audio file is never touched either way. removable: bool = False + # Tracks can be added to the library (`add_tracks`): an import from a + # device, or browsed files added to the collection. + addable: bool = False # Tracks can be converted to native-instruments STEM files, which this # platform plays as stems (`apply_stem_swaps`). stem_convertible: bool = False diff --git a/backend/konduktor/core/waveform.py b/backend/konduktor/core/waveform.py index 59a430f..b38b04d 100644 --- a/backend/konduktor/core/waveform.py +++ b/backend/konduktor/core/waveform.py @@ -173,7 +173,18 @@ def _frames(y: np.ndarray, lead: float) -> Frames: 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) + return analyse_samples(decode(path), n_columns=n_columns, lead=lead) + + +def decode(path: Path) -> np.ndarray | None: + """Mono float32 at `SR` — the same samples `analyse` measures, for a caller + that needs them for something else too (grid detection runs at `SR`).""" + return _decode(path) + + +def analyse_samples(y: np.ndarray | None, *, n_columns: int = 400, + lead: float = 0.0) -> Analysis | None: + """`analyse` on samples already decoded by `decode`.""" 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)) diff --git a/backend/konduktor/importer.py b/backend/konduktor/importer.py index ccf5d5d..21448b9 100644 --- a/backend/konduktor/importer.py +++ b/backend/konduktor/importer.py @@ -340,9 +340,23 @@ def run( cues = source.track_cues(planned.track_id) except Exception: # noqa: BLE001 — prep is a bonus, not a blocker log.debug("could not read cues for %s", planned.track_id, exc_info=True) - items.append(NewTrack(track=track, audio_path=target, cues=cues)) + art = None + cover_art = getattr(source, "cover_art", None) + if cover_art is not None: + try: + art = cover_art(planned.track_id) + except Exception: # noqa: BLE001 — art is a bonus too + log.debug("could not read art for %s", planned.track_id, exc_info=True) + items.append(NewTrack(track=track, audio_path=target, cues=cues, art=art)) - new_ids = dest.add_tracks(items) + def checkpoint(message: str, *, step: int, of: int) -> None: + # A platform that analyses what it adds (Rekordbox) is slow here, + # and calls this before touching the library — so a cancel still + # leaves it untouched and the copies are cleaned up below. + handle.raise_if_cancelled() + handle.progress(done=step - 1, total=of, message=message) + + new_ids = dest.add_tracks(items, checkpoint=checkpoint) by_source = { planned.track_id: new_id for (planned, _), new_id in zip(copied, new_ids) diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index cced2a2..a24bbfe 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -1875,8 +1875,15 @@ def folder_track_stems(track_id: str) -> dict: return _stem_layout_of(_folder_track(track_id).audio_path(track_id)) +def _require_addable(dest) -> None: + caps = dest.capabilities() + if not (caps.writable and caps.tracks.addable): + raise HTTPException(422, "Tracks cannot be added to this library") + + def _folder_add_plan(body: FolderAddRequest): dest = require_adapter() + _require_addable(dest) tracks = [] for track_id in body.track_ids: track = _folder_track(track_id).track(track_id) @@ -1957,6 +1964,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus: def _import_plan(body: ImportRequest): source, dest = require_source(), require_adapter() + _require_addable(dest) destination = Path(body.destination).expanduser() return source, dest, destination, importer.plan( source, diff --git a/backend/test_folders.py b/backend/test_folders.py index 40f6086..1bccb36 100644 --- a/backend/test_folders.py +++ b/backend/test_folders.py @@ -193,6 +193,50 @@ with TestClient(main.app, raise_server_exceptions=False) as c: c.post("/api/folder/add/preview", json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404) + print("== Rekordbox: the same route adds to a master.db ==") + from konduktor.adapters.rekordbox import discovery as rb_discovery + + found = rb_discovery.detect_libraries() + if not found: + print(" (skipped: no Rekordbox library on this machine)") + else: + rb_src = Path(found[0]["path"]).parent + rb_dir = Path(tempfile.mkdtemp()) / "rekordbox" + rb_dir.mkdir() + for name in ("master.db", "masterPlaylists6.xml"): + if (rb_src / name).exists(): + shutil.copy2(rb_src / name, rb_dir / name) + if (rb_src / "share").is_dir(): + shutil.copytree(rb_src / "share", rb_dir / "share") + r = c.post("/api/library/open", json={"path": str(rb_dir / "master.db")}) + check("a Rekordbox copy opens", r.status_code == 200, r.text[:300]) + caps = c.get("/api/capabilities").json() + check("it advertises adding", caps["tracks"]["addable"] is True) + rb = main.require_adapter() + n_before = len(rb.tracks) + req = {"track_ids": [str(two)], "mode": "reference"} + job = wait(c, c.post("/api/folder/add", json=req).json()) + check("the job finishes", job["state"] == "done", str(job)) + new_ids = (job.get("result") or {}).get("track_ids") or [] + check("one track was added", len(rb.tracks) == n_before + 1 and len(new_ids) == 1) + if new_ids: + check("it points at the original file", rb.audio_path(new_ids[0]) == two) + row = rb._store.content(new_ids[0]) + dat = rb_dir / "share" / row.AnalysisDataPath.lstrip("/") + check("its analysis file was written", dat.is_file(), str(dat)) + check("and saved, not left pending", not rb.dirty) + rb.close() + + print("== a library that cannot take tracks refuses the route ==") + fixture = Path(__file__).resolve().parent / "fixtures" / "onelibrary" + r = c.post("/api/library/open", json={"path": str(fixture)}) + if r.status_code == 200: + check("the add preview is refused (422)", + c.post("/api/folder/add/preview", + json={"track_ids": [str(two)], "mode": "reference"}).status_code == 422) + else: + print(f" (skipped: fixture did not open — {r.status_code})") + print("== hidden entries ==") check("AppleDouble twins are hidden", places.is_hidden(music / "._one.flac")) check("OS housekeeping is hidden", places.is_hidden(music / ".Trashes")) diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index aa97ffe..3348bca 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -202,6 +202,52 @@ with tempfile.TemporaryDirectory() as d: changes = diff(before, dump(work)) check("an unsaved edit has written nothing to disk", not changes, describe(changes)) + # ---- D2: the same for a playlist that already has entries ------------- + # pyrekordbox's `remove_from_playlist` COMMITS, so replacing a non-empty + # list once wrote to disk at once — and raised while Rekordbox was running. + print("== D2: replacing a playlist's entries is held until save too ==") + from pyrekordbox.masterdb import database as rb_database # noqa: E402 + + clean_copy(REAL, work, closing=[adapter]) + before = dump(work) + adapter = RekordboxAdapter(work) + filled = next((p for p in adapter.playlist_tree() + if p.kind == "playlist" and len(adapter.playlist_entries(p.id) or []) > 1), + None) + if filled is None: + print(" (skipped: no playlist with two entries)") + else: + original = adapter.playlist_entries(filled.id) + edited = list(reversed(original))[:-1] # reorder AND drop one + adapter.set_playlist_entries(filled.id, edited) + check("the projection shows the new order", + adapter.playlist_entries(filled.id) == edited) + changes = diff(before, dump(work)) + check("nothing is on disk before save", not changes, describe(changes)) + adapter.reload() + check("discarding restores the original entries", + adapter.playlist_entries(filled.id) == original) + real_probe = rb_database.get_rekordbox_pid + rb_database.get_rekordbox_pid = lambda: 4242 # "Rekordbox is running" + try: + adapter.set_playlist_entries(filled.id, edited) + check("an edit while Rekordbox runs does not fail", True) + except Exception as ex: # noqa: BLE001 + check("an edit while Rekordbox runs does not fail", False, repr(ex)) + finally: + rb_database.get_rekordbox_pid = real_probe + adapter.reload() + adapter.set_playlist_entries(filled.id, edited) + adapter.save() + adapter.close() + adapter = RekordboxAdapter(work) + check("after save the new entries are on disk", + adapter.playlist_entries(filled.id) == edited) + changes = diff(before, dump(work)) + check("and nothing outside the playlist's rows and the counter changed", + {t for t, _, _, _ in changes} <= {"djmdSongPlaylist", "agentRegistry"}, + describe(changes)) + # ---- E: playlist edits ----------------------------------------------- print("== E: a playlist round-trips ==") clean_copy(REAL, work, closing=[adapter]) @@ -508,5 +554,187 @@ with tempfile.TemporaryDirectory() as d: adapter.dirty is False and adapter.track(target) is not None) adapter.close() + # ---- J: adding tracks writes what Rekordbox 7 itself writes ------------ + # Measured 2026-10-01 by dragging two files into Rekordbox and diffing: a + # djmdContent row filled from the FILE, analysis files + artwork under + # share/, and one contentFile row per file whose Hash is its MD5. A plain + # file gets Konduktor's own grid (decided 2026-10-01); one that brings a + # grid keeps it, and its cues cross as themselves. + print("== J: adding tracks writes rows and files the way Rekordbox does ==") + import hashlib # noqa: E402 + + import av # noqa: E402 + import numpy as np # noqa: E402 + from konduktor.core.adapter import InvalidCommand, NewTrack # noqa: E402 + from konduktor.core.model import CuePoint, GridMarker, Track, TrackCues # noqa: E402 + + BPM, FIRST, SR = 128.0, 0.5, 44100 + + def kick_mp3(path: Path, seconds: float = 30.0) -> Path: + """A kick every beat at BPM from FIRST — a grid with a known answer.""" + n = int(seconds * SR) + y = np.zeros(n, dtype=np.float32) + t = np.arange(int(0.12 * SR)) / SR + kick = (np.sin(2 * np.pi * 55 * t) * np.exp(-t * 30)).astype(np.float32) + beat = FIRST + while beat < seconds - 0.2: + i = int(beat * SR) + y[i:i + len(kick)] += kick[: n - i] + beat += 60.0 / BPM + x = np.vstack([y, y]) * 0.8 + with av.open(str(path), "w", format="mp3") as c: + s = c.add_stream("libmp3lame", rate=SR, layout="stereo") + s.bit_rate = 320_000 + step = s.codec_context.frame_size or 1152 + for i in range(0, n, step): + f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, i:i + step]), + format="fltp", layout="stereo") + f.sample_rate, f.pts = SR, i + for p in s.encode(f): + c.mux(p) + for p in s.encode(None): + c.mux(p) + return path + + def jpeg() -> bytes: + import io + from PIL import Image + buf = io.BytesIO() + Image.new("RGB", (300, 200), (200, 40, 90)).save(buf, "JPEG") + return buf.getvalue() + + audio_dir = Path(d) / "added" + audio_dir.mkdir() + plain = kick_mp3(audio_dir / "plain.mp3") + prepped = kick_mp3(audio_dir / "prepped.mp3") + from mutagen.id3 import APIC, ID3 # noqa: E402 + tags = ID3() + tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=jpeg())) + tags.save(str(plain)) # embedded art: read off the file + + cues = TrackCues( + grid_markers=[GridMarker(start=0.75, bpm=125.0)], # the source's own grid + cues=[ + CuePoint(role="hotcue", slot=0, start=2.0, length=0.0, color="#FF0000"), + CuePoint(role="hotcue", slot=2, start=6.0, length=4.0, name="Loop"), + CuePoint(role="memory", slot=None, start=9.0, length=0.0), + ], + ) + items = [ + NewTrack(track=Track(id="src:1", title="Konduktor Add Plain", + artist="Konduktor Add Artist", release_date="2021-03-04"), + audio_path=plain), + NewTrack(track=Track(id="src:2", title="Konduktor Add Prepped", + key_wheel=10, key_mode="minor"), + audio_path=prepped, cues=cues, art=(jpeg(), "image/jpeg")), + ] + + clean_copy(REAL, work) + before = dump(work) + share_before = {p for p in (Path(d) / "share").rglob("*") if p.is_file()} + + adapter = RekordboxAdapter(work) + calls = [] + + def cancel(message, *, step, of): + calls.append((step, of)) + if step == 2: + raise RuntimeError("cancelled") + + try: + adapter.add_tracks(items, checkpoint=cancel) + check("a raising checkpoint cancels", False) + except RuntimeError: + check("a raising checkpoint cancels", True) + check("before touching the library", adapter.dirty is False + and len(adapter.tracks) == len(before["djmdContent"]), str(calls)) + + steps = [] + ids = adapter.add_tracks(items, checkpoint=lambda m, *, step, of: steps.append((step, of))) + check("each file is a checkpoint", steps == [(1, 2), (2, 2)], str(steps)) + check("two ids come back, in order", len(ids) == 2 and all(adapter.track(i) for i in ids)) + check("the projection has them at once", + [adapter.track(i).title for i in ids] == ["Konduktor Add Plain", "Konduktor Add Prepped"]) + check("nothing is on disk before save", not diff(before, dump(work))) + check("no file is written before save", + {p for p in (Path(d) / "share").rglob("*") if p.is_file()} == share_before) + try: + adapter.add_tracks([items[0]]) + check("adding a file the library holds is refused", False) + except InvalidCommand: + check("adding a file the library holds is refused", True) + adapter.save() + + changes = diff(before, dump(work)) + new_rows = {t for t, _, kind, _ in changes if kind == "INSERT"} + check("only new rows, plus the counter", + {(t, kind) for t, _, kind, _ in changes} - {(t, "INSERT") for t in new_rows} + == {("agentRegistry", "UPDATE")}, describe(changes)) + check("into the tables Rekordbox writes for a new track", + new_rows <= {"djmdContent", "djmdCue", "contentCue", "contentFile", + "djmdArtist", "djmdKey"}, str(sorted(new_rows))) + after = dump(work) + rows = {i: after["djmdContent"][i] for i in ids} + plain_row, prepped_row = rows[ids[0]], rows[ids[1]] + check("the row is filled from the file", + plain_row["SampleRate"] == SR and plain_row["BitRate"] == 320 + and plain_row["Length"] == 30 and plain_row["FileSize"] == plain.stat().st_size, + str({k: plain_row[k] for k in ("SampleRate", "BitRate", "Length", "FileSize")})) + check("stamped with this library's device", + plain_row["DeviceID"] == next(iter(before["djmdContent"].values()))["DeviceID"]) + check("the release year is kept", plain_row["ReleaseYear"] == 2021) + check("the key is rendered, not copied", prepped_row["KeyID"] is not None) + files: dict[str, list] = {} + for r in after["contentFile"].values(): + files.setdefault(str(r["ContentID"]), []).append(r) + for tid, label in ((ids[0], "plain"), (ids[1], "prepped")): + listed = files.get(tid, []) + paths = sorted(Path(r["Path"]).name for r in listed) + check(f"{label}: contentFile lists its analysis and artwork", + paths == ["ANLZ0000.2EX", "ANLZ0000.DAT", "ANLZ0000.EXT", "artwork.jpg"], str(paths)) + on_disk = [Path(d) / "share" / r["Path"].lstrip("/") for r in listed] + check(f"{label}: each Hash is the file's MD5 and Size its size", + all(p.is_file() and r["Hash"] == hashlib.md5(p.read_bytes()).hexdigest() + and r["Size"] == p.stat().st_size for p, r in zip(on_disk, listed))) + art_dir = (Path(d) / "share" / rows[tid]["ImagePath"].lstrip("/")).parent + check(f"{label}: artwork in three sizes", + sorted(p.name for p in art_dir.iterdir()) + == ["artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"]) + adapter.close() + + reopened = RekordboxAdapter(work) + plain_cues = reopened.track_cues(ids[0]) + markers = plain_cues.grid_markers if plain_cues else [] + check("a plain file gets Konduktor's grid", len(markers) == 1 + and abs(markers[0].bpm - BPM) < 0.05, str(markers)) + if markers: + period = 60.0 / BPM + off = (markers[0].start - FIRST) % period + check("on the kick, in the decoded time base", + min(off, period - off) < 0.015, f"{markers[0].start:.4f}") + check("and its BPM column", rows[ids[0]]["BPM"] == 12800, str(rows[ids[0]]["BPM"])) + got = reopened.track_cues(ids[1]) + check("a source's grid is kept as it was", + got and [(round(m.start, 3), m.bpm) for m in got.grid_markers] == [(0.75, 125.0)], + str(got.grid_markers if got else None)) + by_role = {(c.role, c.slot): c for c in (got.cues if got else [])} + hot = by_role.get(("hotcue", 0)) + check("a hot cue keeps its pad and position", + hot is not None and abs(hot.start - 2.0) < 0.002, str(hot)) + check("and its colour, as a palette swatch", hot is not None and hot.color is not None) + loop = by_role.get(("hotcue", 2)) + check("a loop stays a loop on its pad", + loop is not None and loop.type == "loop" and abs(loop.length - 4.0) < 0.002, str(loop)) + memory = [c for c in (got.cues if got else []) if c.role == "memory"] + check("a memory cue stays a memory cue", + len(memory) == 1 and abs(memory[0].start - 9.0) < 0.002, str(memory)) + + # Removing an added track takes its analysis files with it. + dat = Path(d) / "share" / rows[ids[0]]["AnalysisDataPath"].lstrip("/") + reopened.remove_tracks([ids[0]]) + reopened.save() + check("removing it again deletes its analysis files", not dat.exists()) + reopened.close() + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f1b59e0..8c35c6c 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -863,6 +863,9 @@ export default function App() { const canClearGrids = canEdit && !viewForeign && !!capabilities.data?.grid.editable const canClearCues = canAutoCue const canRemoveTracks = canEdit && !viewForeign && !!capabilities.data?.tracks.removable + // The COLLECTION's capabilities, deliberately: adding happens while a folder + // or device is on screen, whose own capabilities are read-only. + const canAddTracks = canEdit && !!capabilities.data?.tracks.addable const exportRootId = source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null const removeItems = (ids: string[]): MenuItem[] => [ @@ -995,10 +998,17 @@ export default function App() { // added — through the add dialog, which puts them in the // collection first. ...(viewingFolder - ? [ - { label: 'Add to Collection…', onClick: () => setAdding({ ids: menu.ids, target: null }) }, - { label: 'Add to', submenu: folderAddToItems(menu.ids) }, - ] + ? canAddTracks + ? [ + { label: 'Add to Collection…', onClick: () => setAdding({ ids: menu.ids, target: null }) }, + { label: 'Add to', submenu: folderAddToItems(menu.ids) }, + ] + : [{ + label: 'Add to Collection…', + disabled: true, + title: 'Tracks cannot be added to this library', + onClick: () => {}, + }] : viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]), @@ -1197,7 +1207,7 @@ export default function App() { Not in collection - {tracks.length > 0 && ( + {tracks.length > 0 && canAddTracks && ( + } ) : ( diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 1882f3d..fcf50e4 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -247,6 +247,8 @@ export interface Capabilities { media_kinds: MediaKind[] /** Tracks can be removed from the library (audio files are never touched). */ removable: boolean + /** Tracks can be added to the library (import, add browsed files). */ + addable: boolean /** Tracks can be converted to native-instruments STEM files. */ stem_convertible: boolean /** Lower-case suffixes this library can hold — what a browsed folder lists. */