mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-28 10:32:51 +01:00
Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2784879872 | ||
|
|
702e5d86a6 | ||
|
|
d7f8768d4c | ||
|
|
5c193e0ab7 | ||
|
|
badf12b991 | ||
|
|
ecc0e4c8df | ||
|
|
ae03a93f98 | ||
|
|
c560876c02 | ||
|
|
e805635383 | ||
|
|
27471a82cd | ||
|
|
28b705173e | ||
|
|
681add852a | ||
|
|
376569ec75 | ||
|
|
b5b0fa91fe | ||
|
|
34b18893ef | ||
|
|
2c02019bb2 | ||
|
|
08c53e1150 | ||
|
|
9be2c029b2 | ||
|
|
a6f96d5943 | ||
|
|
bd35418a89 | ||
|
|
86b26e3229 | ||
|
|
bb9f6e2bd3 | ||
|
|
3a9dc90344 | ||
|
|
4b9716d47a | ||
|
|
0b909a84f4 | ||
|
|
157c2c0a04 | ||
|
|
4878d82671 | ||
|
|
c2f5191962 | ||
|
|
99d590a051 | ||
|
|
eccd352ae5 | ||
|
|
90beeef226 | ||
|
|
84947bb0bb | ||
|
|
08884ca6bd | ||
|
|
9851c3c056 | ||
|
|
17b68c40bb |
No files matched your search
@@ -0,0 +1,142 @@
|
||||
# The stem engine: a frozen torch + Demucs program, built per target and
|
||||
# published on its OWN release channel (`engine-v<version>`), separate from the
|
||||
# app's `v<version>-b<N>` releases. The app downloads the one it needs on first
|
||||
# use (see backend/konduktor/stems/engine_manager.py).
|
||||
#
|
||||
# * A tag `engine-v1.2.3` builds, tests and publishes — the tag must match
|
||||
# `konduktor_engine.VERSION`.
|
||||
# * A manual run builds and tests only (artifacts, no release).
|
||||
#
|
||||
# Releases are `prerelease: true` and `make_latest: false`: GitHub's "latest"
|
||||
# is what an app would take for itself, and the app's update check reads the
|
||||
# release list (UpdateDialog.tsx) — an engine release must never look like one.
|
||||
#
|
||||
# The weights are NOT in the engine (their licence is ambiguous): CI fetches the
|
||||
# pinned files from Hugging Face only to run the golden test.
|
||||
name: Engine
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["engine-v*"]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: engine-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- target: macos-arm64
|
||||
os: macos-latest
|
||||
torch_index: ""
|
||||
- target: windows-x64-cpu
|
||||
os: windows-latest
|
||||
torch_index: "" # PyPI's Windows torch is the CPU build
|
||||
- target: windows-x64-cuda
|
||||
os: windows-latest
|
||||
# CUDA 13: Turing (RTX 20) through Blackwell (RTX 50); needs an
|
||||
# NVIDIA driver from r580. Older cards get the CPU engine — the
|
||||
# manager checks `engine info`'s arch list before offering this.
|
||||
torch_index: "https://download.pytorch.org/whl/cu130"
|
||||
runs-on: ${{ matrix.os }}
|
||||
name: ${{ matrix.target }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
working-directory: engine
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Check the tag matches the engine version
|
||||
if: startsWith(github.ref, 'refs/tags/engine-v')
|
||||
run: |
|
||||
want="$(python -c 'import konduktor_engine as e; print(e.VERSION)')"
|
||||
[ "${GITHUB_REF_NAME#engine-v}" = "$want" ] || { echo "tag ${GITHUB_REF_NAME} != engine $want"; exit 1; }
|
||||
|
||||
- name: Install
|
||||
run: |
|
||||
python -m pip install --upgrade pip uv
|
||||
uv venv .venv --python 3.12
|
||||
PY=.venv/bin/python; [ -f .venv/Scripts/python.exe ] && PY=.venv/Scripts/python.exe
|
||||
echo "PY=$PY" >> "$GITHUB_ENV"
|
||||
if [ -n "${{ matrix.torch_index }}" ]; then
|
||||
uv pip install --python "$PY" "torch==2.14.0" --index-url "${{ matrix.torch_index }}"
|
||||
fi
|
||||
uv pip install --python "$PY" -r requirements.txt "pyinstaller==6.21.0"
|
||||
|
||||
- name: Weights (for the golden test only)
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: engine/weights
|
||||
key: htdemucs-ft-d74ac89c3a1e874fc78f152555cf4d8533f06cd4
|
||||
- run: $PY fetch_weights.py weights
|
||||
|
||||
- name: Freeze
|
||||
run: $PY -m PyInstaller --noconfirm --clean konduktor-engine.spec
|
||||
|
||||
- name: Golden test (frozen vs unfrozen, CPU)
|
||||
run: |
|
||||
EXE=dist/konduktor-engine/konduktor-engine; [ -f "$EXE.exe" ] && EXE="$EXE.exe"
|
||||
$PY test_engine.py --weights weights --frozen "$EXE"
|
||||
|
||||
- name: Package
|
||||
run: $PY package.py ${{ matrix.target }} dist out
|
||||
|
||||
- name: Paths fit Windows' limit once installed
|
||||
run: |
|
||||
# Installed under e.g. %LOCALAPPDATA%\Konduktor\engine\<ver>\<target>\
|
||||
# (~70 characters on a typical user name): the tree must stay short.
|
||||
$PY -c "import json,sys; n=json.load(open('out/${{ matrix.target }}.json'))['longest_path']; print('longest', n); sys.exit(n > 180)"
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: engine-${{ matrix.target }}
|
||||
path: engine/out/*
|
||||
if-no-files-found: error
|
||||
|
||||
release:
|
||||
needs: build
|
||||
if: startsWith(github.ref, 'refs/tags/engine-v')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
- name: Manifest
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import json, glob, os
|
||||
targets = {}
|
||||
for f in glob.glob("artifacts/*.json"):
|
||||
info = json.load(open(f))
|
||||
targets[info["target"]] = info
|
||||
version = os.environ["GITHUB_REF_NAME"].removeprefix("engine-v")
|
||||
weights = json.load(open("engine/weights.json"))
|
||||
json.dump({"version": version, "targets": targets, "weights": weights},
|
||||
open("artifacts/engine-manifest.json", "w"), indent=1)
|
||||
PY
|
||||
- uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: Konduktor stem engine ${{ github.ref_name }}
|
||||
prerelease: true
|
||||
make_latest: false
|
||||
fail_on_unmatched_files: true
|
||||
files: |
|
||||
artifacts/*.tar.gz*
|
||||
artifacts/engine-manifest.json
|
||||
body: |
|
||||
The stem engine Konduktor downloads for **Convert to Stems** — not an app release.
|
||||
Konduktor fetches the right file for your computer itself; there is nothing to install by hand.
|
||||
@@ -47,3 +47,7 @@ backend/userprefs.json
|
||||
# build_sidecar.sh are source and ARE tracked.
|
||||
backend/build/
|
||||
backend/dist/
|
||||
|
||||
# ---- Stem engine (PyInstaller onedir build) ----
|
||||
engine/build/
|
||||
engine/dist/
|
||||
@@ -47,6 +47,19 @@ Two independent apps that talk over HTTP:
|
||||
- `registry.py` — adapter selection by **`can_open()` probe**, not extension
|
||||
(Rekordbox is a `.db`, Serato is a directory).
|
||||
- `audio_tags.py`, `pathmap.py` — format-agnostic helpers.
|
||||
- `relocate.py` — **auto path remapping's search** (see `relocation.py`).
|
||||
Fixes ONE thing: a stored prefix changed and the layout under it did not
|
||||
(a collection built on Windows with the SSD as `X:`, opened on a Mac where
|
||||
it is `/Volumes/MiniSSD` — the real case, 8,359 of 8,365 found). It
|
||||
SAMPLES ~50 tracks per group against each candidate root (drives, home,
|
||||
Music), dropping leading folders at the shallowest level that hits, and
|
||||
verifies the winner over the WHOLE group — it never walks a drive. At
|
||||
least one folder must survive the drop (a bare filename at a drive root
|
||||
is a coincidence), and a runner-up resolving ≥50% of the winner's count
|
||||
makes the group **ambiguous** — a drive and its backup clone are a
|
||||
question, not a ranking. Which groups to search is the adapter's call
|
||||
(`unresolved_path_groups()`): only volumes in which **NO** track resolves,
|
||||
so a few deleted files never prompt.
|
||||
- `structure.py` + `auto_hotcues.py` — **Auto Hotcues** (the deck's ✨ Auto
|
||||
button → `AutoCueDialog` → `POST /api/tracks/cue/auto`). The user binds each
|
||||
slot to an EVENT (`first_beat`, `intro_end`, `build_n`, `drop_n`,
|
||||
@@ -89,12 +102,34 @@ Two independent apps that talk over HTTP:
|
||||
1–8 kHz attack band, and which attack is the beat from whether a kick's
|
||||
low end follows it — each band alone lost a real track to an off-beat hat
|
||||
or a syncopated bassline. Positions are in the **decoded audio's** time
|
||||
base (libsndfile = CoreAudio to the sample on MP3). **Rekordbox's grids sit
|
||||
a constant ~25 ms later on lossy files** and at 0 on WAV — a platform
|
||||
time-base difference, deliberately NOT corrected here; Traktor's is
|
||||
unmeasured. `backend/bench_grid_detect.py` scores it against any library's
|
||||
base (libsndfile = CoreAudio to the sample on MP3). **Rekordbox's and
|
||||
Traktor's clocks both differ from it, per FILE** (an MP3's header, an
|
||||
M4A's edit list), and are deliberately NOT corrected here but at each
|
||||
adapter boundary — `adapters/rekordbox/timebase.py`,
|
||||
`adapters/traktor/timebase.py`.
|
||||
`backend/bench_grid_detect.py` scores it against any library's
|
||||
single-marker grids and reports that constant separately from detection
|
||||
error (29 Rekordbox references: old 1/29 BPMs, new 27/29).
|
||||
- `stem_file.py` + `tag_copy.py` — **writing a native-instruments STEM
|
||||
file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz
|
||||
streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0,
|
||||
muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place
|
||||
(moov is last, so only two sizes change). The separation is a CALLBACK —
|
||||
the backend never imports torch; the engine (below) supplies it, the
|
||||
tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB,
|
||||
so mono is duplicated by hand; resampling does not move time; both
|
||||
encoders (`aac_at` on macOS, `aac` elsewhere) are timing-exact but decode
|
||||
up to ~2 frames LONGER, so length checks allow 0..2048 samples and the
|
||||
duration reported is the source's; AAC pre-echo fools threshold onsets,
|
||||
so alignment is checked by cross-correlation. **Two JSON literals**: the
|
||||
box exactly as the commercial files hold it and `<STEMS>` exactly as
|
||||
Traktor writes it — they differ in key order AND float digits (Traktor's
|
||||
16 digits do not round-trip the same double; both are the same float32),
|
||||
so neither is derived from the other. `tag_copy` carries every canonical
|
||||
tag (ID3 / Vorbis / MP4 -> MP4, incl. `tmpo` and freeform `initialkey`,
|
||||
the atoms the user's commercial stems use) and the cover, opening the
|
||||
target as `MP4` explicitly because the batch writes `*.konduktor-partial`
|
||||
files that `audio_tags.write_cover` would refuse by suffix.
|
||||
- `places.py` — where a person keeps things on THIS computer: the user's own
|
||||
folders (via `platformdirs` — hardcoding is wrong on every OS differently:
|
||||
`~/Videos` is `Movies` on macOS, Linux's are user-configurable localised
|
||||
@@ -123,10 +158,30 @@ Two independent apps that talk over HTTP:
|
||||
only a file a scan found is streamed, so `/api/folder/tracks/audio` cannot
|
||||
read an arbitrary path. Tagged keys are deliberately dropped (every
|
||||
notation there is). The listed suffixes are the collection's
|
||||
`tracks.audio_formats` capability.
|
||||
`tracks.audio_formats` capability. A stem file lists as
|
||||
`media_kind: "stem"` (its `stem` box, read at scan time).
|
||||
- `adapters/traktor/` — everything that knows NML exists.
|
||||
- `store.py` (`TraktorStore`) — the retained native model: owns the parsed
|
||||
dataclass NML, applies every edit, renders + saves. See "Write path".
|
||||
**`apply_stem_swaps`** is Convert to Stems' library side (generic
|
||||
`StemSwap` / `StemSwapResult` in `core/adapter.py`, gated on
|
||||
`tracks.stem_convertible`; Rekordbox/OneLibrary refuse): all swaps are
|
||||
validated before any applies. "repoint" moves the entry to the stem file
|
||||
(id changes; playlists follow as `TYPE="STEM"`); "add" deep-copies it
|
||||
(plus its pending tag fields and staged art, so Save still writes them to
|
||||
the new file). Either sets `<STEMS>` (the literal from `core/stem_file`),
|
||||
INFO bitrate/playtime/playtime_float/filesize(KB), VOLUMEID only where it
|
||||
still names the volume, and KEEPS AUDIO_ID (`_KEEP_AUDIO_ID_ON_STEM`:
|
||||
measured in Traktor 4.5 — cleared, Traktor re-analyses on load and
|
||||
re-measures a hand-set grid's BPM; kept, it touches nothing). **Every START shifts by the time-base
|
||||
difference**, the old offset read from `StemSwap.original_audio` — the
|
||||
original's bytes where they are NOW (parked, under a non-audio name, so
|
||||
`timebase.offset_ms(..., suffix=)` takes the original's suffix). Read
|
||||
from the old path it would be 0 and every cue ~51 ms late
|
||||
(`test_stem_swap.py` pins that failure). An anchor pushed below 0 moves
|
||||
forward by whole beats with its companion; a hotcue there clamps to 0 and
|
||||
is reported. The journal records scope `stem` (not `track/add`, which
|
||||
would exclude the entry from the tag sync).
|
||||
- `adapter.py` (`TraktorAdapter`) — owns the store **and** the `TrackIndex`
|
||||
built from it, so projection and native model cannot drift. Translates the
|
||||
generic cue vocabulary to Traktor's integers (the only place that mapping
|
||||
@@ -136,6 +191,21 @@ Two independent apps that talk over HTTP:
|
||||
- `driver.py`/`discovery.py` — `can_open`, default-location detection, restore.
|
||||
- `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion
|
||||
rules, LOCATION ↔ OS path conversion, and its capability set.
|
||||
- `timebase.py` — **Traktor's clock vs the decoded audio.** Traktor decodes
|
||||
MP3 naively (ignores the LAME gapless fields, decodes the Xing/Info
|
||||
header frame as audio), so on an MP3 WITH a header every stored position
|
||||
sits `samples_per_frame + encoder_delay + 529` samples (2257 = ~51 ms at
|
||||
44.1 kHz, 47 ms at 48 kHz) later than the decoded audio; header-less
|
||||
MP3s and every other format are 0. Measured in Traktor 4.5 with blinded
|
||||
cues in both directions (kit 4, in the stem-conversion discussion log).
|
||||
The store ADDS it at its four seconds→START writes (`time_offset_ms`),
|
||||
`projection.to_track_cues` SUBTRACTS it, and a read is **never clamped
|
||||
at 0**: Traktor anchors grids inside the header frame, and clamping would
|
||||
move them on the next write-back (`buildBeatGrid` keeps negative starts
|
||||
for the same reason). A file that cannot be read gets 0 and is not
|
||||
cached. The header itself is read by `core/mp3_gapless.py`, which skips
|
||||
the ID3v2 tag first — a check that did not once misread every real MP3
|
||||
as header-less.
|
||||
- `adapters/rekordbox/` — **track metadata, playlists and hot cues writable;
|
||||
the beatgrid still read-only** (milestones 2 and 3a). Also home to
|
||||
`anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format,
|
||||
@@ -184,6 +254,20 @@ Two independent apps that talk over HTTP:
|
||||
bank. Point cues AND loops both write; `cue_types` owns the translation.
|
||||
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only
|
||||
platform with them — the two-platform promotion rule).
|
||||
**Hot cue colour is writable** (`set_cue_color`, `PATCH
|
||||
/api/tracks/cue/color`) from `palette.SWATCHES` — the 15 MEASURED swatches
|
||||
of rekordbox's 16 (the teal-green is left out, not guessed); a pick must
|
||||
be an exact swatch (`swatch_code`), unlike the exporter's nearest-hue
|
||||
`code_for`. Not a breach of the promotion rule: Rekordbox, OneLibrary and
|
||||
Serato all colour cues — Traktor is the odd one out, by type only, so it
|
||||
reports `color="none"`. **The colour belongs to the PAD**: `set_cue` with
|
||||
no colour keeps the slot's existing code, so rename, type change and an
|
||||
Auto Hotcues Replace keep it; only Delete or "Default" clear it. Both
|
||||
columns go through `RekordboxStore._apply_color` (coloured: code +
|
||||
`Color=-1`; uncoloured loop: `255/0`; uncoloured cue: `-1/NULL`). An
|
||||
unknown code projects as no colour but stays on the row. Uncoloured cues
|
||||
still DRAW in Konduktor's type colours, not rekordbox's green/orange
|
||||
defaults (decided 2026-10-01: those defaults are unmeasured).
|
||||
- **Saving warns but does not block when Rekordbox is running.**
|
||||
`pyrekordbox.commit()` refuses outright, and its check is process-wide
|
||||
rather than per-file, so `RekordboxStore._commit()` suppresses that veto
|
||||
@@ -244,6 +328,18 @@ Two independent apps that talk over HTTP:
|
||||
`track_cues()`. The `PQTZ` beatgrid is the same tag as Rekordbox's, and the
|
||||
collapse rule is **shared by import** rather than copied — two definitions of
|
||||
"when does a tempo change start a marker" would drift silently.
|
||||
- **A stem file ADDED to a Traktor collection** (folder add, import, the
|
||||
Traktor exporter — all `TraktorStore.add_entry`) gets `<STEMS>` rendered
|
||||
from its OWN box by `stem_file.traktor_stems_json` (keys sorted, compact,
|
||||
whole floats as integers, else 16 significant digits) — measured to give
|
||||
Traktor's value for every local stem file and to re-render all 3,678 in the
|
||||
big collection unchanged, though every one of those is NI's default
|
||||
layout. Without it the entry read as plain audio (Type column, playlist
|
||||
`TYPE="TRACK"`) while the deck, which reads the file, played stems.
|
||||
Rekordbox and OneLibrary have no such element, so their projections take
|
||||
`media_kind` from the FILE (`stem_file.is_stem_file`, only `.m4a`/`.mp4`
|
||||
opened, ~0.7 ms each, cached per path in `RekordboxStore.is_stem`) — the
|
||||
same mismatch otherwise: Type said audio while the deck played stems.
|
||||
- `importer.py` also serves the folder add: `reference=True` adds each file
|
||||
where it is (nothing to copy or roll back), and every planned file the
|
||||
destination already points at (matched on `audio_path`, never the display
|
||||
@@ -253,7 +349,73 @@ Two independent apps that talk over HTTP:
|
||||
the view's, so browsing elsewhere cannot point it at endpoints that do not
|
||||
know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place
|
||||
that choice is made.
|
||||
- `stems/` — Convert to Stems around the file itself. `engine_manager.py`:
|
||||
the engine version THIS build needs (`engine.json`) and the pinned weights
|
||||
(`weights.json`, a copy of `engine/weights.json` a test keeps equal).
|
||||
Installs under app-data (Windows: a SHORT `%LOCALAPPDATA%\Konduktor\engine`
|
||||
for the 260-char limit); an install counts only after every part's hash,
|
||||
the archive's, AND the unpacked engine starting and naming the expected
|
||||
version (`probe`) — `installed.json` is written last. One engine at a time;
|
||||
CUDA offered only for driver r580+ and capability 7.5+ (`nvidia-smi`).
|
||||
Side-loading (offline) verifies against the release manifest, cached once
|
||||
seen. `download.py`: resumable (`Range`, restarts if ignored), SHA-verified,
|
||||
certifi TLS (a frozen macOS Python has no CA store). `engine_process.py`:
|
||||
one `serve` per batch — progress, cancel-by-message, crash reported with
|
||||
the engine's stderr tail, raw work files deleted as read, a Windows Job
|
||||
Object and `keep_awake` (caffeinate / SetThreadExecutionState). Routes:
|
||||
`GET /api/stems/engine`, `POST .../install` (a `stem-engine-install` job in
|
||||
bytes, engine + weights), `POST .../sideload`, `DELETE`.
|
||||
**`convert.py` — the batch** (`POST /api/tracks/stems/preview` and
|
||||
`/convert`, a `stem-conversion` job in `BATCH_JOBS`, exclusive with the
|
||||
engine install and import). The collection is UNTOUCHED while tracks
|
||||
convert (hours, on a big batch): each becomes a verified
|
||||
`<target>.konduktor-partial`, so edits made meanwhile carry over and Cancel
|
||||
only deletes new files. One short END STEP under `STATE.mutation` then
|
||||
publishes each (a rename that refuses to overwrite: link+unlink on POSIX),
|
||||
parks each original in Replace mode (`.<name>.<ext>.konduktor-parked`,
|
||||
same folder, hidden on Windows, retried while Windows holds it open) and
|
||||
swaps every entry at once. Skips (reported, not failed): already a stem file
|
||||
BY CONTENT, missing file, target exists (never overwritten), two sources
|
||||
onto one (case-folded) target, a target the collection names; disk space is
|
||||
preflighted per volume (both copies coexist until Save) and for the work
|
||||
folder. Replace implies repoint; destination mode mirrors the tree (full
|
||||
path, volume first, when the tracks share no folder) and may repoint or add
|
||||
(+ existing / new playlist). **`pending.py` — the ledger** of conversions
|
||||
awaiting Save (per library id, atomic): `AppState._save` COMMITS (deletes
|
||||
parked originals, retargets export sets — inside `_save`, so import and
|
||||
remap saves count too), `discard()` and opening another library RESTORE,
|
||||
and `_open` RECOVERS a crash before the missing-files check (parked
|
||||
originals would look missing): each item decided by whether the SAVED
|
||||
library names the stem file. Every step works from what is on disk, never
|
||||
the recorded state alone; only a stem file the batch PUBLISHED is ever
|
||||
deleted; an uncommitted verified stem file is kept under its partial name
|
||||
and REUSED by the next batch converting the same (unchanged) source.
|
||||
While conversions are pending or running, remap-paths, path mapping,
|
||||
relocation, import, folder add, history restore and reload answer 409
|
||||
(`_require_no_pending_stems`): each would save or drop the swap.
|
||||
`/api/state` reports `pending_stems`, `stem_job`, `stem_recovery`.
|
||||
**`stream_cache.py` — stem PLAYBACK.** A browser decodes only an MP4's
|
||||
FIRST audio stream (the mix), so each stem is served as a file of its own:
|
||||
the three audio routes (collection / `source` / `folder`) take
|
||||
`?stem=0..3`, and `/api/…/tracks/stems` report `[{name, color}]` read from
|
||||
the FILE (`stem_file.stem_layout`: the box, and enough streams — never the
|
||||
library's `<STEMS>`, which plain MP3s carry). `stem_file.extract_stream`
|
||||
COPIES packets into an `ipod` MP4 — measured bit-identical to decoding the
|
||||
stream in place, edit list and priming (1024 / 2112) intact, on commercial
|
||||
stems too, so stems stay sample-locked to the mix and the cues. Cached in
|
||||
app-data keyed by path + size + mtime, LRU under 2 GB, written partial →
|
||||
rename; ~0.1 s per stem uncached.
|
||||
- `app_state.py` — the one loaded library, and the **version-history commit**.
|
||||
**`discard()`** (`POST /api/discard`, SaveBar's "Discard changes…", the
|
||||
quit prompt's Discard) drops every unsaved edit through the adapter's own
|
||||
`reload`, NOT `open` — reopening would re-run the missing-files check and
|
||||
forget this session's relocation answers. The route stops (and WAITS for)
|
||||
running batches first, as library open does (`_stop_batches`), or a batch
|
||||
would keep writing into the reloaded library. Rekordbox's reload is a real
|
||||
discard (`RekordboxStore.discard`): session rolled back and closed with its
|
||||
engine, buffered ANLZ grids and journal cleared — before, it opened a second
|
||||
connection and stayed "dirty". A reentrant `mutation` lock serialises
|
||||
open / save / discard (and, next, a stem batch's swap step).
|
||||
History is app-level: the adapter returns the bytes it wrote plus a summary,
|
||||
and `AppState.save()` versions them. Every write path must go through it.
|
||||
- `library_id.py` — a **stable identity for a library that survives it being
|
||||
@@ -271,7 +433,10 @@ Two independent apps that talk over HTTP:
|
||||
path-derived id that `is_durable()` reports honestly. Writing beside the
|
||||
library is not a new intrusion — saves already create `backups/` there.
|
||||
- `exports.py` — **export sets**: a named, persisted slice of the library bound
|
||||
to a destination. Konduktor's OWN data, never written into the user's library
|
||||
to a destination and **one or more target platforms** (`targets`, never
|
||||
empty; a set saved with the old single `target` loads as a one-item list).
|
||||
The targets share the destination and ONE copy of the audio — their layouts
|
||||
(`collection.nml`; `PIONEER/…`; `master.db` + `share/…`) do not collide. Konduktor's OWN data, never written into the user's library
|
||||
(a Traktor collection has nowhere to put it, and it would live in a file
|
||||
Traktor rewrites). Three rules shape it: references are **LIVE** (a set
|
||||
stores playlist *ids*, resolved at export time, so `resolve()` is computed on
|
||||
@@ -283,6 +448,20 @@ Two independent apps that talk over HTTP:
|
||||
dropping it, because a gig stick quietly missing four tracks is this
|
||||
feature's worst failure. `retarget()` follows ids through a path remap, which
|
||||
`/api/library/remap-paths` calls with a before/after snapshot.
|
||||
- `relocation.py` — the **open-time missing-files check**. `AppState.open()`
|
||||
starts a `RelocationCheck` thread (after the saved mapping is applied, so
|
||||
a volume it fixes is not asked about); `GET /api/library/relocation`
|
||||
serves the proposals until `POST` answers them (no mappings = Not now),
|
||||
then serves nothing — "ask once per open" lives here, not in the UI,
|
||||
which would re-ask on every refetch. Answers are **session-only**
|
||||
(`set_session_mappings`, applied in `TraktorStore._resolve` BENEATH the
|
||||
saved mapping and only for a file not found as stored): never written to
|
||||
the library, which would change every Traktor track id, nor to prefs, so
|
||||
a reopen asks again. Only a mapping the search proposed is accepted.
|
||||
**Traktor only for now**; Rekordbox/OneLibrary return no groups.
|
||||
`RelocateDialog` always asks — found volumes ticked, ambiguous ones a
|
||||
radio with nothing preselected, missing ones "Not connected" with a
|
||||
"Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss.
|
||||
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
|
||||
dir). Last-opened collection (global AND per-platform), library column
|
||||
layout, prep-deck zoom, import destination. Best-effort.
|
||||
@@ -309,6 +488,38 @@ Two independent apps that talk over HTTP:
|
||||
OneLibrary library is a drive. `prefs` keeps last-opened **per platform**:
|
||||
offering a Rekordbox `master.db` to someone who just chose Traktor is an
|
||||
offer that cannot be taken.
|
||||
- **`engine/`** — the **stem engine**, a separate program (`konduktor_engine`,
|
||||
Python 3.12, torch 2.14 + demucs 4.1 pinned in `engine/requirements.txt`)
|
||||
that imports nothing from `konduktor`, built and released on its OWN channel.
|
||||
- `core.py` loads htdemucs_ft from a LOCAL weights folder — never online: the
|
||||
weights' licence rules out shipping them, so the app downloads them, pinned
|
||||
by revision + SHA-256 in `engine/weights.json` (`fetch_weights.py` for
|
||||
CI/dev). Seeded — and demucs draws its random shift from PYTHON's `random`,
|
||||
not torch's, so both are seeded or no two runs match.
|
||||
- `serve.py`: one process per batch, the model loaded once; JSON requests on
|
||||
stdin, JSON-line replies on a private copy of stdout (`sys.stdout` points
|
||||
at stderr, since torch prints), one lock for writes from two threads.
|
||||
A reader THREAD ends the process the moment stdin closes — the backend dies
|
||||
without killing children, and torch keeps the main thread busy. `cancel`
|
||||
raises from the progress callback and keeps the model loaded; CUDA OOM
|
||||
falls back to CPU for that track; the process lowers its own priority.
|
||||
`info` reports the CUDA card, capability and the build's arch list, which
|
||||
is how the app decides whether to offer the CUDA engine.
|
||||
- Frozen as a PyInstaller **onedir** (`konduktor-engine.spec`; onefile would
|
||||
re-extract ~500 MB per launch), `torch/include` and the HF client dropped:
|
||||
macOS arm64 = 164 MB download / 550 MB unpacked, runs after a tar round
|
||||
trip (ad-hoc signature intact). `test_engine.py` pins the protocol
|
||||
(reproducible seed, cancel, stdin-EOF exit) and, with `--frozen`, that the
|
||||
frozen build separates BIT-FOR-BIT like the unfrozen code (CPU).
|
||||
- `package.py` → tar.gz (zip loses exec bits on macOS), split under GitHub's
|
||||
2 GiB asset cap, per-part SHA-256; symlinks are archived as links and not
|
||||
double-counted. `.github/workflows/engine.yml` builds macos-arm64,
|
||||
windows-x64-cpu and windows-x64-cuda (torch cu130: Turing–Blackwell,
|
||||
driver r580+; older cards get the CPU engine), runs the golden test on CPU
|
||||
(runners have no GPU), checks Windows path length, and on an `engine-v*`
|
||||
tag publishes `prerelease` / NOT latest with an `engine-manifest.json`.
|
||||
- `backend/dev_stems.py` (dev only) converts files with the real writer
|
||||
through an unfrozen engine, and can swap them into a collection.
|
||||
- **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track
|
||||
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
|
||||
- `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**:
|
||||
@@ -383,7 +594,13 @@ Two independent apps that talk over HTTP:
|
||||
same menu and the row's hover buttons, which share one set of actions.
|
||||
A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE`
|
||||
playlist routes take a `:path` param, a folder name may not contain `/`,
|
||||
and renaming onto a sibling folder's name is refused), `SaveBar` (+ the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close /
|
||||
Cmd+Q and emits `konduktor://quit-requested`; this acks it (`quit_ack` — the
|
||||
shell quits anyway after ~2 s without one, so a hung page cannot trap the
|
||||
user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard
|
||||
· Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer;
|
||||
browser dev gets `beforeunload`), `SaveBar` (+ "Discard changes…" when
|
||||
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
`TrackTable` (**the one track list** — All Tracks, playlists, exports and
|
||||
devices. TanStack Table + **virtualized** grid; per-row play button,
|
||||
configurable columns, header sorting, inline double-click editing, and
|
||||
@@ -403,6 +620,28 @@ Two independent apps that talk over HTTP:
|
||||
flushSync-driven measurement — which is why playlists were once a separate,
|
||||
non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just
|
||||
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.)
|
||||
`ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where =
|
||||
Replace the originals (its option STATES that Save deletes them, since
|
||||
the choice is remembered and may be preselected) or Save to a folder; In
|
||||
the collection = point at the stem file / add as new tracks + playlist
|
||||
(folder mode only); a live preview from `POST /api/tracks/stems/preview`
|
||||
— N to convert, skipped ▸ with reasons, a time estimate from measured
|
||||
real-time factors, space; the engine download INLINE, offering the GPU
|
||||
engine when `nvidia` is set, which keeps running if the dialog closes
|
||||
(App shows it in the status bar). Every option persists as `stemConvert`),
|
||||
`StemReportDialog` (the Details behind a finished run's toast — every
|
||||
skipped/failed track with its reason), `StemsSettings` (Settings → Stems:
|
||||
engine status / download / install from a folder / remove, compute device
|
||||
`stemDevice`, the remembered defaults, originals awaiting Save). App
|
||||
follows a finished run's `{old: new}` ids with the deck and the selection,
|
||||
picks a running conversion back up from `/api/state.stem_job` after a
|
||||
reload, and reports `stem_recovery` once. The menu item is shown DISABLED
|
||||
with a reason (`MenuItem.title` — rendered `aria-disabled`, not
|
||||
`disabled`, since browsers show no tooltip on a disabled button) where the
|
||||
platform cannot play stem files as stems. SaveBar adds "Saving deletes N
|
||||
original files" while conversions are pending (decided: the consequence is
|
||||
shown where Save is pressed). `Toast` takes an optional `action`;
|
||||
`StatusJob.unit: 'bytes'` shows a download in MB. Every background job's status-bar entry reads label + count · a bar SPLIT horizontally when the job reports per-item progress (top = the current item's `fraction`, 0-100 %; bottom = the whole job, (done + fraction) / total, so 99 % into the first of two tracks reads ~50 %) — a single bar otherwise; two colours in one bar was tried and read as confusing · its `status` ("separating 41 %") at its natural width · the item's name LAST (the only part that truncates; full name on hover). The section is a FIXED width (560 px; the view name on the left gives way instead) and everything BEFORE the bar is fixed (count sized for its largest value, "cancelling…" as a status, not a label), so neither a long name nor a phase change moves the bar. The status deliberately has no fixed slot: it is after the bar, and a slot left a gap before the name. `Job.fraction`/`status` come from `JobHandle.progress(fraction=, status=)` and reset whenever `done` advances; a stem conversion maps decode / separate / encode onto a track's 0-1 by measured shares.
|
||||
`AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per
|
||||
slot, a per-slot Replace tick for occupied slots — never remembered, since
|
||||
overwriting is a decision about THIS track — and the template itself
|
||||
@@ -421,13 +660,33 @@ Two independent apps that talk over HTTP:
|
||||
(right-click → multi-field metadata + album-art edit), `StatusBar`,
|
||||
`RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`,
|
||||
`UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows
|
||||
even on the picker screen: on startup fetches the latest GitHub release and,
|
||||
even on the picker screen: on startup lists recent GitHub releases and takes the
|
||||
newest non-draft, non-prerelease `v…` tag — NOT `/releases/latest`, since the
|
||||
stem engine publishes `engine-v*` releases in the same repo — and,
|
||||
if its tag's **semver part** is newer than `__APP_VERSION__` — build-number
|
||||
`-b<N>` bumps don't count — shows an update dialog with the release's
|
||||
"What's Changed" bullets; Download opens the release page in the system
|
||||
browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open`
|
||||
outside Tauri; "Skip this version" persists `skippedUpdateVersion` to
|
||||
userprefs via `/api/prefs`; all failures are silent).
|
||||
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
|
||||
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
|
||||
their SUM, as Traktor's stem deck does — the mix stream is never decoded,
|
||||
which also saves a full-length buffer. `PlaybackEngine.load` takes several
|
||||
buffers: one source + gain each, all started at ONE scheduled context
|
||||
time (so they stay sample-locked through seeks and loops), mute/solo as
|
||||
ramped gains, never a restart. `ScratchEngine.loadStems` keeps ONE summed
|
||||
copy of the audible stems (not four), re-summed in slices on a mute change.
|
||||
`analyzeStems` returns the overview's three-band columns (of the sum) plus
|
||||
one amplitude lane per stem, each normalised to its own 99.5th percentile
|
||||
but never below 5% of the loudest (a silent stem stays silent).
|
||||
`MainWaveform` draws the lanes in the file's own colours with a mute
|
||||
button at each lane's left edge (click = mute, Alt/Option-click = solo);
|
||||
Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the
|
||||
mutes (every other stem muted), so each stem stays freely mutable after
|
||||
it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is
|
||||
the cost: ~140 MB per stem for 6 minutes, i.e. the same four buffers as
|
||||
the file holds streams, and no more.
|
||||
- **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it,
|
||||
in three rows. **Header**: cover, title/artist · album · genre, a Read-only
|
||||
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
|
||||
@@ -438,7 +697,12 @@ Two independent apps that talk over HTTP:
|
||||
`OverviewWaveform`, which frames the main view's visible range around the
|
||||
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER
|
||||
`HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
|
||||
(±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. Every grid control acts
|
||||
(±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. The row is a
|
||||
**container** and gives way in stages instead of overlapping: each pad
|
||||
queries its own width and drops its name below 4rem (the bank never goes
|
||||
below `PAD_MIN` per pad), then the tempo group folds into `TempoFold`'s
|
||||
portalled popover, then Grid keeps only its icon. The two row breakpoints
|
||||
are measured widths — move them if controls are added to the row. Every grid control acts
|
||||
on the marker **governing the playhead**, since a beatgrid is a marker list
|
||||
and there is no separate marker selection; see "Beatgrid" below.
|
||||
- **One size for loops AND beat jump** (`beatSize`, 1/32–32, persisted as
|
||||
@@ -457,8 +721,9 @@ Two independent apps that talk over HTTP:
|
||||
loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so
|
||||
seeking first wraps the playhead back into the old loop.
|
||||
- **Hotcue edits live on the pad's right-click menu** (type as one-click
|
||||
choices, Rename…, Delete); there is no standalone type dropdown or delete
|
||||
button. Rename re-sets the slot with its own start/type/length plus the
|
||||
choices, a colour swatch grid + Default where `cues.color` is `palette` —
|
||||
`ContextMenu`'s `swatches` item, Rename…, Delete); there is no standalone
|
||||
type dropdown or delete button. Rename re-sets the slot with its own start/type/length plus the
|
||||
new name, since `set_cue` replaces a slot. A non-editable cue gets the
|
||||
same menu disabled, not no menu.
|
||||
Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops),
|
||||
@@ -481,11 +746,12 @@ Two independent apps that talk over HTTP:
|
||||
listening, and shows a "Read-only" badge).
|
||||
- Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and
|
||||
the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown
|
||||
(`cues.types`), the rating scale (`tracks.rating_max`), the grid Lock button
|
||||
(`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`,
|
||||
(`cues.types`), the cue colour swatches (`cues.color === 'palette'` +
|
||||
`cues.palette`; a `free` platform gets no picker yet), the rating scale
|
||||
(`tracks.rating_max`), the grid Lock button (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`,
|
||||
`can_add_tracks`) gate the sidebar and the context menu's "Add to" — each on its OWN flag,
|
||||
since a platform may allow renaming but not deleting. Carried but deliberately unused until a second adapter
|
||||
exists: `slot_labels: 'letter'`, `palette`, `loops: 'separate_bank'`, and
|
||||
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`, and
|
||||
memory-cue *editing* (one-platform features stay preserved-but-uneditable).
|
||||
- `lib/trackColumns.tsx` — single source of truth for the library table's
|
||||
columns (defs, default widths/visibility/order, the Columns-menu list, the
|
||||
@@ -531,10 +797,70 @@ serialization path.** It enforces:
|
||||
real flexible grids in the collection project correctly (K); and
|
||||
**removing a track from the collection** drops its `<ENTRY>` and its
|
||||
PRIMARYKEYs from exactly the playlists that held it — the only ADDED lines are
|
||||
the `ENTRIES=` recounts, every other playlist byte-identical (L).
|
||||
the `ENTRIES=` recounts, every other playlist byte-identical (L); and a
|
||||
**path remap** rewrites locations + playlist keys localized (H1/H2), re-keys
|
||||
the entry index so earlier tag edits still reach the file (H3), and is
|
||||
**refused with nothing changed** when it would give two ENTRYs one primary key
|
||||
— onto a staying track's path, or two differently-keyed entries for one file
|
||||
— which the preview reports first, while a chain (A onto B's old path, B
|
||||
onward) and a pre-existing duplicate are allowed, each track's staged art
|
||||
and edits following the TRACK (H4).
|
||||
The guard that catches serialization regressions like the lxml reformatting bug.
|
||||
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched.
|
||||
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
|
||||
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
|
||||
in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every
|
||||
write path adding it and the projection removing it, a grid anchored inside
|
||||
the header frame reading negative and round-tripping byte for byte, and —
|
||||
when kit 4 is on the machine — Traktor's own hand-placed cues reading back
|
||||
onto the kick. Then the same for rekordbox's clock: the per-file offsets
|
||||
(MP3 header, header-less, 48 kHz, FFmpeg and Apple AAC priming, the
|
||||
unreadable fallback), negative beats dropped with bar numbering kept, and
|
||||
rekordbox's own hand-placed kit-4 cues read back from `master.db`.
|
||||
- `test_stem_file.py` — the stem writer on generated sources with a FAKE
|
||||
engine: both JSON literals byte-exact against the user's commercial files and
|
||||
collection (skipped when absent) and float32-equal; mono not 3 dB quieter;
|
||||
48 kHz resampling does not move time; MP3 and FLAC through both encoders give
|
||||
five streams with only the mix enabled, no shift (cross-correlation), the
|
||||
bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a
|
||||
shifted, truncated or box-less file; a raising checkpoint cancels.
|
||||
- `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real
|
||||
collection with a generated MP3 (with header) and a real stem file: prep
|
||||
reads back at the same decoded second while its START moves by the 2257-
|
||||
sample offset read from the PARKED file (and the 51 ms error reading the old
|
||||
path would cause); outside the ENTRY only its PRIMARYKEYs change (TYPE STEM);
|
||||
save round-trip; anchor-before-0 moves a whole beat with its companion, a
|
||||
hotcue clamps and is reported; "add" appends, keeps the original, joins a
|
||||
playlist, carries pending tag fields; clashes refused with nothing changed.
|
||||
- `test_engine_manager.py` — the engine manager and process against a LOCAL
|
||||
Range-aware server and a FAKE engine script (no network, no torch): resume,
|
||||
restart when Range is ignored, checksum refusal, cancel keeps the `.part`;
|
||||
install from split parts with byte progress and a probe; a wrong-version
|
||||
engine or corrupt part leaves nothing installed; side-load and weights
|
||||
verified; the CUDA offer's driver/capability floors; the process relays
|
||||
progress, cancels without dying, reports a crash with its reason, keeps the
|
||||
Mac awake; the routes (install job in bytes, 409 while one runs, remove).
|
||||
- `test_stems_batch.py` — the Convert to Stems batch through the routes with
|
||||
the FAKE engine (`stem_test_support.py`, shared with
|
||||
`test_engine_manager.py`), on temp collections pointed at generated MP3s:
|
||||
skips with reasons (an existing target is never overwritten); Replace parks,
|
||||
swaps at the end, leaves the saved file untouched, keeps prep in decoded time
|
||||
and 409s the blocked routes; Save deletes parked originals and retargets an
|
||||
export set; Discard and switching library restore; Cancel leaves no file;
|
||||
one bad track fails alone; destination+add mirrors into a new playlist;
|
||||
crash recovery restores (or finishes a committed save) and a re-run REUSES
|
||||
the kept stem files without calling the engine.
|
||||
- `test_stem_playback.py` — stem playback's backend half on a generated stem
|
||||
file (fake stems = distinct scalings of the mix): the layout is read from
|
||||
the FILE (an MP3 whose entry carries `<STEMS>` has none); each served stem
|
||||
is its own MP4, bit-identical to that stream in place and the RIGHT stem;
|
||||
out-of-range / non-stem requests 404; the cache reuses, follows an edited
|
||||
file, evicts LRU but never what it just wrote; the folder origin serves too
|
||||
and lists the file as a stem track; a stem file ADDED from a folder gets
|
||||
`<STEMS>` and a `TYPE="STEM"` playlist key, the MP3 beside it neither. On a
|
||||
Rekordbox copy, an added stem file projects as a stem track (also after a
|
||||
reopen) and the deck is offered its stems.
|
||||
- `test_traktor_adapter.py` — the **generic layer**: one parse per open, the
|
||||
projection refreshing after every command family, cue-type translation,
|
||||
capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity`
|
||||
@@ -549,7 +875,24 @@ serialization path.** It enforces:
|
||||
against SQLite). Asserts a no-op save changes zero rows; a one-field edit
|
||||
changes exactly two — the track and `agentRegistry.localUpdateCount` — with the
|
||||
counter up by one and the edited row stamped with it; edits are invisible on
|
||||
disk until save; and playlist create/fill/rename/delete round-trip.
|
||||
disk until save; and playlist create/fill/rename/delete round-trip. And
|
||||
**removing a track** deletes exactly the rows Rekordbox 7 deletes (measured
|
||||
2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`,
|
||||
`djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist`
|
||||
— DELETED, never `rb_local_deleted`; the playlist row untouched, later
|
||||
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. 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
|
||||
@@ -596,10 +939,9 @@ serialization path.** It enforces:
|
||||
projection AND its playlists while its audio file is untouched, removal is
|
||||
gated on `tracks.removable`, and all three are refused while a batch
|
||||
analysis runs. `remove_tracks` is the protocol's only DESTROYING verb for
|
||||
tracks; Traktor implements it, Rekordbox and OneLibrary refuse (a Rekordbox
|
||||
track spans rows in several tables plus ANLZ files, and which Rekordbox
|
||||
expects deleted together is unmeasured). The journal records it as
|
||||
`track/remove`, NOT an edit — otherwise history would read "edited 40 tracks".
|
||||
tracks; Traktor and Rekordbox implement it, OneLibrary (read-only) refuses.
|
||||
The journal records it as `track/remove`, NOT an edit — otherwise history
|
||||
would read "edited 40 tracks".
|
||||
- `test_folders.py` — the Files trees and adding loose files, through the
|
||||
routes, on generated FLACs and a temp copy of the collection: a folder lists
|
||||
only the visible audio DIRECTLY in it; the audio route refuses anything a
|
||||
@@ -636,7 +978,11 @@ serialization path.** It enforces:
|
||||
`run()` refuses a blocked plan even when called directly; a re-export replaces
|
||||
its own files and leaves the user's alone; a cancel leaves no library file and
|
||||
**no audio at all**, including the file being written; a missing source file is
|
||||
skipped rather than fatal.
|
||||
skipped rather than fatal. And the incremental re-export: an unchanged
|
||||
re-export copies and decodes NOTHING (same inodes), an edited source and a
|
||||
copy tampered with on the stick are each re-copied alone, a moved shared root
|
||||
renames kept copies instead of copying, a cancelled re-export keeps them and
|
||||
the folder stays ours, and the analysis cache round-trips exactly.
|
||||
- `test_export_pioneer.py` — the two Pioneer targets against the same contract.
|
||||
Harder than Traktor's in a way that test cannot cover: each writes a database
|
||||
PLUS per-track analysis files, so "the library" is no longer one path, and the
|
||||
@@ -646,11 +992,24 @@ serialization path.** It enforces:
|
||||
multi-tempo grid survives expansion to per-beat and collapse back. Both are read
|
||||
back with Konduktor's own adapters, which is the strongest check short of the
|
||||
hardware: the reader was written against real rekordbox output.
|
||||
- `test_relocate.py` — auto path remapping: `relocate.search` on temp folders
|
||||
(drive-letter change, clone = ambiguous, partial copy loses, bare filename is
|
||||
no match, dropped home folders), then the Traktor path through the routes on
|
||||
a collection re-homed to `X:`/`E:`: a resolving volume is never asked about,
|
||||
nothing applies before the answer and only a proposed mapping does, the
|
||||
collection and prefs are untouched, a reopen asks again, and a saved manual
|
||||
mapping's volume is left out.
|
||||
- `test_library_id.py` — the property no other suite covers: **a library that
|
||||
moves keeps its identity**. Also that two libraries in one folder stay two, a
|
||||
removable library is never written beside, an unwritable location falls back
|
||||
rather than failing, and `paths.write_json` is atomic (curated user work, so
|
||||
`prefs.py`'s best-effort "any I/O error degrades to no prefs" is NOT adequate).
|
||||
- `test_discard.py` — discarding unsaved edits through the route: the edit is
|
||||
gone, the file and version history untouched, relocation answers and the
|
||||
saved path mapping survive, the adapter object is the same (a reload, not a
|
||||
reopen), and a running batch has stopped by the time discard returns; on
|
||||
Rekordbox (temp copy, skipped when absent) the library is clean afterwards and
|
||||
a later save writes nothing that was thrown away; read-only libraries 409.
|
||||
- `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
|
||||
imports another platform's library (checked on real imports via AST, so merely
|
||||
naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately
|
||||
@@ -873,6 +1232,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
|
||||
@@ -950,7 +1329,139 @@ 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. **Rekordbox's clock runs behind the decoded
|
||||
audio by the start padding it does not trim, which depends on the FILE**:
|
||||
an MP3 with a Xing/Info header 1105 samples (~25 ms; rekordbox skips the
|
||||
header frame, unlike Traktor), a header-less MP3 0, an M4A its edit list's
|
||||
priming (1024 from FFmpeg, 2112 from Apple — rekordbox ignores the edit
|
||||
list), lossless 0. Measured with blinded cues in rekordbox 7 (kit 4,
|
||||
2026-09-30); it replaced a fixed 1105 that was 25 ms wrong on header-less
|
||||
MP3s and 22 ms on Apple AAC. The file is read (`core/mp3_gapless.py`,
|
||||
`core/mp4_edit.py`); one that cannot be read falls back to 1105. A position
|
||||
before the decoded audio (a Traktor grid anchored in the header frame)
|
||||
clamps to 0 on write, and `beats_from_markers` drops beats before 0 while
|
||||
keeping the rest's bar numbering. The OneLibrary fixture's demo MP3s are
|
||||
12-byte stubs, so the fixture tests exercise only the fallback —
|
||||
`test_timebase.py` covers the per-file rule. The generic model is
|
||||
the decoded time base, so `adapters/rekordbox/timebase.py` is applied at EVERY
|
||||
Pioneer boundary: both exporters add it, the OneLibrary reader and the
|
||||
Rekordbox adapter subtract it on read and add it on write (`set_cue`,
|
||||
`set_cue_type`, grid save). Without it every cue sat 25 ms early in rekordbox.
|
||||
**Drawn waveforms** (`.EXT` `PWV3`/`PWV5`, `.2EX` `PWV7`/`PWV6`/`PWVC`) are
|
||||
generated from one decode (`core/waveform.py`: 150 frames/s, bands split at
|
||||
200 Hz / 2.5 kHz) with constants fitted to rekordbox's own files for 12 local
|
||||
tracks and checked on 5 held-out ones (per-band correlation 0.77-0.96).
|
||||
**Every column split goes through `waveform.even_slices`, never
|
||||
`np.array_split`**: the latter gives the first `n % k` chunks an extra frame,
|
||||
so overview column k held LATER audio than its position — up to ~1.8 s by
|
||||
column 420 of 1200, back to 0 at the end. Rekordbox drew such an overview a
|
||||
bar ahead of the playhead mid-track (`test_export_pioneer.py` pins a burst
|
||||
landing in its own column).
|
||||
**rekordbox 7's SONG LIST draws `PWV6` — and only when `content.contentLink`
|
||||
is set.** Both measured by bisecting a rekordbox-written stick: removing a
|
||||
track's `PWV6` emptied its row (removing `PWV4` changed nothing), and blanking
|
||||
its `contentLink` alone turned the row plain blue with a "?" beside CUE — what
|
||||
every Konduktor-exported row showed while the exporter left it NULL. It now
|
||||
writes rekordbox's 788224 (beside `analysedBits` 41; meaning unknown).
|
||||
`masterDbId`/`masterContentId` do NOT matter, so no link to a rekordbox
|
||||
collection is claimed. `PWV4` is still written (every rekordbox file has it);
|
||||
its low/mid/high bytes cannot be matched per column (b4/b5 are sampled
|
||||
at one instant: column-to-column correlation 0.05/0.16), so each byte is a
|
||||
QUANTILE MAP fitted to rekordbox's distribution (`_PWV4_MAPS`); smoothed, it
|
||||
tracks rekordbox's at 0.5-0.99. A very loud master draws smaller than in
|
||||
rekordbox, whose PWV4 keeps some absolute level. rekordbox reads 200+ covers
|
||||
from one `Artwork/00001` folder (verified on a 207-track export). Decoding is
|
||||
**PyAV** first (FFmpeg in its wheel: AAC on every OS; measured to start on the
|
||||
same sample as librosa) with librosa as fallback. **Cue colour on export** is
|
||||
what Konduktor SHOWS (`core/cue_colors.py`, mirroring `lib/cues.ts`): a stored
|
||||
colour, else the type's — blue cue, green loop — because "unset" makes
|
||||
rekordbox draw its own defaults (green/orange). **rekordbox draws a hot cue
|
||||
from its palette CODE** (`PCP2` byte 44, before the RGB; `djmdCue.ColorTableIndex`
|
||||
in master.db), not the RGB — `adapters/rekordbox/palette.py` holds the 16-swatch
|
||||
table MEASURED from a rekordbox 7 export (one swatch, ~0x12 teal-green, still
|
||||
unmeasured). Type colours map by intent (cue -> light blue 0x05, loop -> green
|
||||
0x16), anything else to the nearest hue; the palette has NO white, so a grid
|
||||
companion is code 0 + RGB white (what rekordbox draws for it: unverified). The
|
||||
**Artwork** (`adapters/rekordbox/artwork.py`, Pillow), measured on a rekordbox 7
|
||||
export: `PIONEER/Artwork/00001/{a,b}<n>.jpg` at 80 px and `_m` at 240 px, `a`
|
||||
byte-identical to `b`, baseline JPEG q85 4:2:0, non-square art LETTERBOXED onto
|
||||
black (a crop or stretch is visibly wrong); `image.path` names the `b` file and
|
||||
`content.image_id` points at it; one image per track, never shared. The runner
|
||||
carries each cover as `ExportTrack.art` from `LibraryAdapter.cover_art` — not
|
||||
re-read from the copied file, since a library's art is not always embedded.
|
||||
The OneLibrary READER now serves `cover_art` too (the `_m` file). How rekordbox
|
||||
itself splits a large library across `Artwork/000NN` folders is unknown; one
|
||||
folder of 207 was verified to load in full.
|
||||
**The `master.db` target was opened in a real Rekordbox 7** (2026-09-27, by
|
||||
swapping an export into `~/Library/Pioneer/rekordbox` with a full backup):
|
||||
it accepts the library, keeps our tracks/cues/analysis untouched, and shows
|
||||
grids, cues and the playlist tree. Two things it needed: a
|
||||
`masterPlaylists6.xml` beside `master.db` (written as a skeleton BEFORE the DB
|
||||
is opened, so pyrekordbox registers each playlist in it), and
|
||||
`djmdContent.ContentLink` — a bit field: NULL = blue song-list preview + "?",
|
||||
any value = coloured, 0x200000 clears the "?", and the real library's
|
||||
0x3D060E adds a badge claiming analysis we do not write, so the exporter uses
|
||||
0x2C060E. **Parity with the OneLibrary target is done and verified in
|
||||
Rekordbox 7**: cue colours (palette code in `djmdCue.ColorTableIndex`,
|
||||
`Color` -1 — coloured loops included), memory cues (`store.add_memory_cue`,
|
||||
export-only: the adapter still refuses memory-cue edits), and artwork
|
||||
(`share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/artwork.jpg` fit to 800 px plus
|
||||
`_m` 240 / `_s` 80 letterboxed, `ImagePath` -> artwork.jpg). The exporter writes
|
||||
cues through `store.set_cue`/`add_memory_cue`, which share `_write_cue` with
|
||||
every adapter edit, so the `contentCue` mirror stays in step.
|
||||
**Two Rekordbox targets, named for what they are:** "Rekordbox Library"
|
||||
(`export.py`, a COMPUTER `master.db` — Rekordbox never reads one from a stick)
|
||||
and **"Rekordbox Export"** (`device_export.py`, platform `rekordbox_export`: a
|
||||
stick's legacy **Device Library**, `PIONEER/rekordbox/export.pdb` +
|
||||
`exportExt.pdb`, what Rekordbox lists as "Device Library" and pre-OneLibrary
|
||||
players read). `pdb.py` reads and writes the DeviceSQL format — no public spec;
|
||||
the layout is crate-digger's, CONFIRMED byte for byte against a real rekordbox 7
|
||||
device export (every row re-encodes identically; a data page rebuilt from its
|
||||
rows is identical). It writes from rekordbox's OWN empty device library
|
||||
(`fixtures/rekordbox/device/`, the fixed colour/column/menu tables) and follows
|
||||
rekordbox's page allocation (a table's first data page is its reserved
|
||||
candidate; further pages and the new candidate come from next-unused). The
|
||||
track row's `bitmask` is 0xC0700 = OneLibrary's `contentLink`; `u3`/`u4` are
|
||||
the halves of rekordbox's `masterDbId` and stay 0. **A table's HEADER page is
|
||||
not empty: it indexes its data** (first data page; for tracks, playlist tree
|
||||
and history an entry per data page, `page << 3 | 3` if it has room) and the
|
||||
history row counts the tracks — left as in the empty template, Rekordbox 7
|
||||
said "Device library is corrupted". It shares the stick's
|
||||
analysis files and `a<n>.jpg` artwork with the OneLibrary target — the same
|
||||
paths, and whichever target runs second REUSES what the first just wrote, so a
|
||||
two-format stick costs one decode per track. A target with no reader is listed
|
||||
by `/api/export-targets` from the exporter registry; `LibraryExporter.
|
||||
display_name` names a target where one platform has two. `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
|
||||
@@ -965,7 +1476,17 @@ that number and nothing else — everything derives from it:
|
||||
tags and the `cue` table's MPEG seek columns.
|
||||
**Step 5 done**: `exporter.py` — plan, mirrored copy, manifest, rollback — on
|
||||
`jobs.py`, plus `POST /api/exports/{id}/preview` and `/run`, and the
|
||||
`ExportRunDialog`. Three properties it is built around: audio is copied FIRST
|
||||
`ExportRunDialog`. **Multi-target** (2026-09-27): audio is copied once, then
|
||||
each target's `write()` runs in turn over it; ANY failure undoes everything,
|
||||
earlier targets' libraries included — and files a failing writer never got
|
||||
to report, via a snapshot of the destination taken before the first write.
|
||||
The manifest lists `libraries` (plural; the old `library` key is still
|
||||
cleared). Audio lives under **`Contents/`**, so a music folder with a
|
||||
top-level `PIONEER/` or a `master.db` cannot land on a library's path. An
|
||||
exporter's static `drive_root` (OneLibrary: a CDJ looks for `PIONEER/` only
|
||||
at a stick's root) surfaces as `PlatformOption.drive_root` and the preview's
|
||||
`not_drive_root` — a **warning, not a block**, since the other targets are
|
||||
valid in any folder. Three properties it is built around: audio is copied FIRST
|
||||
and the library written LAST, so a cancel leaves **no** library file and its
|
||||
absence is what marks an export unfinished; rollback registers each file
|
||||
BEFORE writing it, so the in-flight copy is cleaned up too; and the **manifest**
|
||||
@@ -975,6 +1496,26 @@ that number and nothing else — everything derives from it:
|
||||
would put the user's home directory on the stick, and relative paths make
|
||||
filename collisions impossible. A destination Konduktor did not write is
|
||||
**refused, not confirmed**: there is no "do it anyway".
|
||||
**Incremental re-export** (2026-09-28): the manifest's `audio` map records,
|
||||
per copy, the SOURCE's path/size/mtime and the COPY's size/mtime as read
|
||||
back (FAT32 rounds mtimes, so they are never assumed equal). A copy is kept
|
||||
when all four match — **no checksums**: hashing the copy means reading it
|
||||
back over USB, about the cost of copying it. Copies are matched by SOURCE
|
||||
path, since adding a track from another folder moves `common_dir_prefix`
|
||||
and every destination path with it; a kept copy that moved is RENAMED
|
||||
(two-phase via `.konduktor-moving/`, since one's new path can be another's
|
||||
old one). Order: old libraries and unkept files go, kept copies move, a
|
||||
manifest listing every path the run may leave is written (crash-safe), new
|
||||
copies land as `*.konduktor-partial` and are renamed in, libraries last. A
|
||||
failed run with kept files REWRITES the manifest around them rather than
|
||||
deleting it — else the folder would be refused as not ours. Pioneer
|
||||
waveform decoding is cached on the drive too (`core/analysis_cache.py`,
|
||||
`.konduktor-cache/`, keyed by the same source facts + the lead +
|
||||
`waveform.ANALYSIS_VERSION` — **bump that when `analyse()` changes**);
|
||||
exporters reach it through `ExportTrack.waveform()`, never
|
||||
`waveform.analyse()` directly. The Rekordbox Library target's ANLZ paths are
|
||||
a fresh UUID per export, which is why the MEASUREMENT is cached rather than
|
||||
old ANLZ files reused by path.
|
||||
**Step 4 done**: `core/export.py` (the `LibraryExporter` protocol, its own
|
||||
registry, and the strictly-generic `ExportPayload` — so a Rekordbox collection
|
||||
exports to Traktor with no exporter knowing Rekordbox exists) and
|
||||
@@ -1015,7 +1556,10 @@ diff — no COLLECTION splicing needed.
|
||||
child (`CollectionService.stem_keys`, resolved via `entries_for`), else `TRACK`.
|
||||
- **Track metadata**: `set_track_metadata(track_id, fields)` edits only the SAFE
|
||||
set — title, artist, album, genre, label, remixer, producer, mix,
|
||||
release_date, comment, rating (0–5 stars → `RANKING = stars*51`). Path, BPM and
|
||||
release_date, comment, comment2, rating (0–5 stars → `RANKING = stars*51`).
|
||||
**`comment2` is Traktor's "Comment 2", stored in `INFO@RATING`** — free
|
||||
text despite the name, unrelated to the stars — and it is collection-only:
|
||||
Traktor writes no file tag for it, so `_sync_file_tags` skips it too. Path, BPM and
|
||||
key are intentionally NOT editable via metadata (path = identity; BPM/key are
|
||||
audio/grid — BPM is edited through the grid path below). This is the set the
|
||||
Edit Tags dialog AND the inline table editing (double-click cell, click rating
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""DEV ONLY — convert audio files to stem files with an UNFROZEN engine.
|
||||
|
||||
Not shipped, not in run_tests.sh. It exists so real stem files can be made (and
|
||||
checked in Traktor) before the frozen engine and its download exist: the stem
|
||||
writer (`core/stem_file.py`) runs here in the backend venv, and the separation
|
||||
runs in any Python that has torch + demucs, through the engine's own one-shot
|
||||
CLI — the same raw-f32 exchange the batch will use.
|
||||
|
||||
python dev_stems.py --engine-python ~/demucs-venv/bin/python \\
|
||||
--weights ~/.cache/huggingface/hub/models--adefossez--HTDemucs-ft/snapshots/<rev> \\
|
||||
[--out-dir DIR] [--device auto] FILE...
|
||||
|
||||
Each FILE becomes `<name>.stem.m4a` beside it (or in --out-dir); an existing
|
||||
target is skipped, never overwritten.
|
||||
|
||||
With `--collection NML` it also does what the batch will do at its end: park
|
||||
each original (`.<name>.konduktor-parked`, beside it), repoint the collection
|
||||
entry that names it at the stem file (`apply_stem_swaps`), and SAVE — after
|
||||
copying the collection into its `backups/` folder. Traktor must be closed.
|
||||
`--keep-audio-id` keeps Traktor's analysis fingerprint on the swapped entries
|
||||
(the milestone-2 check compares kept vs cleared).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import numpy as np # noqa: E402
|
||||
|
||||
from konduktor.core import stem_file as sf # noqa: E402
|
||||
|
||||
ENGINE_DIR = Path(__file__).resolve().parents[1] / "engine"
|
||||
|
||||
|
||||
def engine_separator(python: str, weights: str, device: str):
|
||||
def separate(pcm: np.ndarray) -> list[np.ndarray]:
|
||||
with tempfile.TemporaryDirectory(prefix="konduktor-dev-stems-") as d:
|
||||
mix = Path(d) / "mix.f32"
|
||||
np.ascontiguousarray(pcm, dtype=np.float32).tofile(mix)
|
||||
cmd = [python, "-m", "konduktor_engine", "separate", "--input", str(mix),
|
||||
"--samples", str(pcm.shape[1]), "--output-dir", str(Path(d) / "out"),
|
||||
"--weights", weights, "--device", device]
|
||||
proc = subprocess.Popen(cmd, cwd=ENGINE_DIR, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL, text=True)
|
||||
last = None
|
||||
for line in proc.stdout:
|
||||
msg = json.loads(line)
|
||||
if msg["event"] == "progress":
|
||||
print(f"\r separating {msg['fraction'] * 100:5.1f} %", end="", flush=True)
|
||||
last = msg
|
||||
proc.wait()
|
||||
print()
|
||||
if not last or last["event"] != "done":
|
||||
raise sf.StemFileError(f"engine failed: {last}")
|
||||
return [np.fromfile(Path(d) / "out" / f"{name}.f32", dtype=np.float32).reshape(2, -1)
|
||||
for name in sf.DEMUCS_ORDER]
|
||||
return separate
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--engine-python", required=True)
|
||||
ap.add_argument("--weights", required=True)
|
||||
ap.add_argument("--out-dir")
|
||||
ap.add_argument("--device", default="auto")
|
||||
ap.add_argument("--collection")
|
||||
ap.add_argument("--keep-audio-id", action="store_true")
|
||||
ap.add_argument("files", nargs="+")
|
||||
args = ap.parse_args()
|
||||
separate = engine_separator(args.engine_python, args.weights, args.device)
|
||||
adapter = None
|
||||
swaps = []
|
||||
if args.collection:
|
||||
if subprocess.run(["pgrep", "-x", "Traktor"], capture_output=True).returncode == 0:
|
||||
print("Traktor is running — close it first (it rewrites the collection on exit).")
|
||||
return 1
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter
|
||||
adapter = TraktorAdapter(Path(args.collection))
|
||||
adapter.store._KEEP_AUDIO_ID_ON_STEM = args.keep_audio_id
|
||||
by_path = {str(adapter.audio_path(t.id)): t.id for t in adapter.tracks}
|
||||
for f in (Path(x).expanduser().absolute() for x in args.files):
|
||||
target = (Path(args.out_dir) if args.out_dir else f.parent) / sf.stem_target_name(f.name)
|
||||
if target.exists():
|
||||
print(f"skip (exists): {target}")
|
||||
continue
|
||||
partial = target.with_name(target.name + ".konduktor-partial")
|
||||
t0 = time.time()
|
||||
print(f"{f.name}")
|
||||
try:
|
||||
written = sf.build(f, partial, separate)
|
||||
except Exception:
|
||||
partial.unlink(missing_ok=True)
|
||||
raise
|
||||
os.replace(partial, target)
|
||||
print(f" -> {target.name} {written.duration:.0f} s, {written.bit_rate // 1000} kbps x5, "
|
||||
f"{written.size / 1e6:.1f} MB, {time.time() - t0:.0f} s")
|
||||
if adapter is not None:
|
||||
from konduktor.core.adapter import StemSwap
|
||||
tid = by_path.get(str(f))
|
||||
if tid is None:
|
||||
print(f" (not in the collection: {f})")
|
||||
continue
|
||||
parked = f.with_name(f".{f.name}.konduktor-parked")
|
||||
os.replace(f, parked)
|
||||
swaps.append(StemSwap(tid, target, "repoint", parked, written.bit_rate,
|
||||
written.duration, written.size))
|
||||
if adapter is not None and swaps:
|
||||
import shutil
|
||||
nml = Path(args.collection)
|
||||
backups = nml.parent / "backups"
|
||||
backups.mkdir(exist_ok=True)
|
||||
shutil.copy2(nml, backups / f"{nml.name}.{time.strftime('%Y%m%d-%H%M%S')}.dev-stems.bak")
|
||||
res = adapter.apply_stem_swaps(swaps)
|
||||
adapter.save()
|
||||
print(f"swapped {len(res.renamed)} entries; clamped: {res.clamped or 'none'}; saved {nml}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -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');
|
||||
@@ -0,0 +1,20 @@
|
||||
# Empty rekordbox device library (`export.pdb`, `exportExt.pdb`)
|
||||
|
||||
The legacy "Device Library" a Pioneer USB stick carries — the one Rekordbox
|
||||
lists as **Device Library** and older players (CDJ-2000NXS2, many XDJs) read —
|
||||
exactly as **Rekordbox 7.2.18 wrote it for an empty stick**: it creates both
|
||||
files the first time it mounts a drive that has none.
|
||||
|
||||
They are the starting point of the "Rekordbox Export" target
|
||||
(`adapters/rekordbox/device_export.py`), for the same reason `seed.sql` exists:
|
||||
the format has fixed tables that are the same on every stick and cannot be
|
||||
derived — the colour list (table 6), the browse columns (16), two menu tables
|
||||
(17, 18) and a history header (19) in `export.pdb`; rekordbox's default MyTag
|
||||
names in `exportExt.pdb`. Every data table (tracks, artists, albums, genres,
|
||||
labels, keys, playlists, artwork) holds only its header page, with a blank page
|
||||
reserved after it for its first rows — the allocation rule the writer follows.
|
||||
|
||||
**No user data**: the only strings are colour names, column names, the default
|
||||
MyTag names, the creation date (`2026-09-27`, rewritten on every export) and the
|
||||
database version `1000`. Pages 13-14 and 33-38 are byte-identical to the same
|
||||
pages of a real rekordbox device export of eight tracks.
|
||||
Executable
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"note": "Rows from a real rekordbox 7.2.18 device export (export.pdb), for byte-level tests. Only the Loopmasters demo tracks and generic key names; see README.md. The track row's u3/u4 (the exporting computer's rekordbox masterDbId) are zeroed.",
|
||||
"track_row_demo_track_2": "2400200000070c0044ac000000000000f6304e0011a8a6040000000000000000000000000000000001000000000000004001000000000000e02e000000000000000000000100000002000000000000000000100080002900000001000300880089008a008c008e00910092009500980099009a00a500a600a700a800d400df00fd000a010b011c0103030531053107313103074f4e074f4e030317323031382d30352d3235030303592f50494f4e4545522f555342414e4c5a2f503035332f30303031443231462f414e4c5a303030302e44415417323032362d30392d31373d547261636b73206279207777772e6c6f6f706d6173746572732e636f6d1b44656d6f20547261636b2032032344656d6f20547261636b20322e6d7033692f436f6e74656e74732f4c6f6f706d6173746572732f556e6b6e6f776e416c62756d2f44656d6f20547261636b20322e6d7033",
|
||||
"track_row_demo_track_2_fields": {
|
||||
"subtype": 36,
|
||||
"index_shift": 32,
|
||||
"bitmask": 788224,
|
||||
"sample_rate": 44100,
|
||||
"composer_id": 0,
|
||||
"file_size": 5124342,
|
||||
"u2": 78030865,
|
||||
"u3": 0,
|
||||
"u4": 0,
|
||||
"artwork_id": 0,
|
||||
"key_id": 0,
|
||||
"original_artist_id": 0,
|
||||
"label_id": 1,
|
||||
"remixer_id": 0,
|
||||
"bitrate": 320,
|
||||
"track_number": 0,
|
||||
"tempo": 12000,
|
||||
"genre_id": 0,
|
||||
"album_id": 0,
|
||||
"artist_id": 1,
|
||||
"id": 2,
|
||||
"disc_number": 0,
|
||||
"play_count": 0,
|
||||
"year": 0,
|
||||
"sample_depth": 16,
|
||||
"duration": 128,
|
||||
"u5": 41,
|
||||
"color_id": 0,
|
||||
"rating": 0,
|
||||
"u6": 1,
|
||||
"u7": 3,
|
||||
"isrc": "",
|
||||
"texter": "",
|
||||
"unknown_string_2": "1",
|
||||
"unknown_string_3": "1",
|
||||
"unknown_string_4": "11",
|
||||
"message": "",
|
||||
"kuvo_public": "ON",
|
||||
"autoload_hotcues": "ON",
|
||||
"unknown_string_5": "",
|
||||
"unknown_string_6": "",
|
||||
"date_added": "2018-05-25",
|
||||
"release_date": "",
|
||||
"mix_name": "",
|
||||
"unknown_string_7": "",
|
||||
"analyze_path": "/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT",
|
||||
"analyze_date": "2026-09-17",
|
||||
"comment": "Tracks by www.loopmasters.com",
|
||||
"title": "Demo Track 2",
|
||||
"unknown_string_8": "",
|
||||
"filename": "Demo Track 2.mp3",
|
||||
"file_path": "/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3"
|
||||
},
|
||||
"artist_row_loopmasters": "6000000001000000030a194c6f6f706d617374657273000000000000",
|
||||
"playlist_row_demos": "00000000000000000100000001000000000000000d64656d6f730000",
|
||||
"keys_page_index": 12,
|
||||
"keys_page": "000000000c0000000500000034000000140000000000000002400024b80f1800010001000000000001000000010000000941626d020000000200000007456d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000Line truncated
|
||||
}
|
||||
@@ -20,8 +20,9 @@ binaries = []
|
||||
for pkg in ("uvicorn", "xsdata", "dulwich"):
|
||||
hiddenimports += collect_submodules(pkg)
|
||||
|
||||
# Native standard extras — grab modules + shared libs + any data.
|
||||
for pkg in ("uvloop", "httptools", "websockets"):
|
||||
# Native standard extras — grab modules + shared libs + any data. PyAV (`av`)
|
||||
# carries FFmpeg's shared libraries, which the export's waveform analysis needs.
|
||||
for pkg in ("uvloop", "httptools", "websockets", "av"):
|
||||
d, b, h = collect_all(pkg)
|
||||
datas += d
|
||||
binaries += b
|
||||
@@ -35,6 +36,25 @@ 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"),
|
||||
# The "Rekordbox Export" target starts from rekordbox's own empty device library.
|
||||
("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"),
|
||||
("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"),
|
||||
]
|
||||
# Which stem engine this build needs, and the pinned weights (read at import by
|
||||
# konduktor/stems/engine_manager.py).
|
||||
datas += [
|
||||
("konduktor/stems/engine.json", "konduktor/stems"),
|
||||
("konduktor/stems/weights.json", "konduktor/stems"),
|
||||
]
|
||||
|
||||
a = Analysis(
|
||||
["sidecar.py"],
|
||||
pathex=[],
|
||||
|
||||
@@ -50,12 +50,14 @@ class OneLibraryAdapter:
|
||||
|
||||
# ---- projection maintenance -----------------------------------------
|
||||
def _rebuild(self) -> None:
|
||||
self._index.rebuild(
|
||||
[
|
||||
projection.to_track(row, self._drive_path(row))
|
||||
for row in self._store.iter_content()
|
||||
]
|
||||
)
|
||||
from ...core.stem_file import is_stem_file
|
||||
|
||||
tracks = []
|
||||
for row in self._store.iter_content():
|
||||
path = self._drive_path(row)
|
||||
tracks.append(projection.to_track(
|
||||
row, path, stem=bool(path) and is_stem_file(path)))
|
||||
self._index.rebuild(tracks)
|
||||
|
||||
def _drive_path(self, row) -> str | None:
|
||||
resolved = self._store.layout.resolve(getattr(row, "path", None))
|
||||
@@ -211,6 +213,13 @@ class OneLibraryAdapter:
|
||||
"""
|
||||
return None
|
||||
|
||||
def unresolved_path_groups(self) -> list:
|
||||
"""None, ever: a drive's paths are relative to its own mount point."""
|
||||
return []
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
return None
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
paths = self._store.all_audio_paths()
|
||||
primary = common_dir_prefix(paths)
|
||||
@@ -244,12 +253,15 @@ 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:
|
||||
self._refuse("Removing tracks")
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
self._refuse("Converting tracks to stems")
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
self._refuse("Editing track metadata")
|
||||
|
||||
@@ -257,7 +269,7 @@ class OneLibraryAdapter:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
return None
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._refuse("Creating playlists")
|
||||
@@ -280,6 +292,9 @@ class OneLibraryAdapter:
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
|
||||
self._refuse("Editing cues")
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
self._refuse("Deleting cues")
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -69,9 +69,9 @@ def capabilities_for(device_name: str | None = None, version: str | None = None)
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5, # stored 0-5 directly, as in master.db
|
||||
editable_fields=[],
|
||||
media_kinds=["audio"],
|
||||
# The drive has an `image` table and an Artwork folder, but nothing
|
||||
# is wired up to read them yet.
|
||||
media_kinds=["audio", "stem"],
|
||||
# `artwork` gates EDITING, and a drive is read-only here. Reading
|
||||
# works: `store.cover_art` follows `content.image_id` -> `image.path`.
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
|
||||
@@ -42,7 +42,9 @@ from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from ..rekordbox import anlz_writer as W
|
||||
from ..rekordbox import artwork, palette, timebase
|
||||
from ..rekordbox.beatgrid import beats_from_markers
|
||||
from ..rekordbox.projection import render_key
|
||||
from .capabilities import capabilities_for
|
||||
@@ -51,11 +53,21 @@ 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"
|
||||
#: Seen on every track of a real export; semantics undocumented, copied as-is.
|
||||
ANALYSED_BITS = 41
|
||||
#: `content.contentLink`, as rekordbox 7 writes it beside `analysedBits` 41 (a
|
||||
#: re-analysed track carried 1902336 beside 105; what the bits mean is unknown).
|
||||
#: NOT optional: measured by blanking it on one track of a rekordbox-written
|
||||
#: stick — that row's song-list preview fell back to plain blue and gained a "?"
|
||||
#: beside CUE, exactly as every row of Konduktor's exports did while it was NULL.
|
||||
#: `masterDbId`/`masterContentId` were cleared the same way and changed nothing.
|
||||
CONTENT_LINK = 788224
|
||||
|
||||
OTHER_PLAYLIST = "Other"
|
||||
|
||||
@@ -84,8 +96,11 @@ def _anlz_dir(drive_relative: str) -> str:
|
||||
|
||||
class OneLibraryExporter:
|
||||
platform = "onelibrary"
|
||||
menu_order = 10
|
||||
#: Relative to the drive root, which is what the destination folder is.
|
||||
library_filename = str(Path("PIONEER") / DB_SUBPATH)
|
||||
#: A CDJ looks for `PIONEER/` at the root of the stick and nowhere else.
|
||||
drive_root = True
|
||||
|
||||
def capabilities(self):
|
||||
"""What a drive can hold — no device, no path, no library to read.
|
||||
@@ -96,9 +111,13 @@ class OneLibraryExporter:
|
||||
yes to. Leaving the adapter's answer here would have the UI report that
|
||||
the thing it just wrote cannot be written.
|
||||
"""
|
||||
return capabilities_for().model_copy(
|
||||
update={"writable": True, "readonly_cause": None}
|
||||
)
|
||||
caps = capabilities_for()
|
||||
# An exported drive CARRIES artwork (`_write_art`); the adapter's False
|
||||
# means "cannot edit a plugged-in drive's art", a different question.
|
||||
return caps.model_copy(update={
|
||||
"writable": True, "readonly_cause": None,
|
||||
"tracks": caps.tracks.model_copy(update={"artwork": True}),
|
||||
})
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
@@ -108,8 +127,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))
|
||||
@@ -118,6 +143,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:
|
||||
@@ -128,10 +154,17 @@ class OneLibraryExporter:
|
||||
|
||||
def _fill(self, con, payload: ExportPayload, root: Path) -> list[Path]:
|
||||
lookups = {name: {} for name in ("artist", "album", "genre", "label", "key")}
|
||||
# Image ids are handed out in track order, one per track that HAS art —
|
||||
# rekordbox does not share an image between tracks, even identical ones.
|
||||
lookups["image"] = {"next": 0}
|
||||
written: list[Path] = []
|
||||
by_source: dict[str, int] = {}
|
||||
|
||||
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})", step=n, of=total)
|
||||
by_source[item.source_id] = n
|
||||
written += self._write_track(con, n, item, root, lookups)
|
||||
|
||||
@@ -170,16 +203,18 @@ class OneLibraryExporter:
|
||||
size = item.destination.stat().st_size
|
||||
except OSError:
|
||||
size = 0
|
||||
sample_rate, bit_depth = _audio_format(item.destination)
|
||||
image_id, art_files = self._write_art(con, item, root, lookups["image"])
|
||||
|
||||
con.execute(
|
||||
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
|
||||
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, "
|
||||
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, image_id, "
|
||||
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
|
||||
"fileType, bitrate, samplingRate, isHotCueAutoLoadOn, "
|
||||
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
|
||||
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
|
||||
"analysisDataFilePath, analysedBits, hasModified, cueUpdateCount, "
|
||||
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
|
||||
"analysisDataUpdateCount, informationUpdateCount) "
|
||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
content_id, track.title, (track.title or "").lower(),
|
||||
int(round((track.bpm or 0) * 100)) or None, track.length,
|
||||
@@ -193,40 +228,103 @@ class OneLibraryExporter:
|
||||
# where the deck expects "Cm". Rendered from the parsed wheel.
|
||||
self._lookup(con, "key", lookups["key"],
|
||||
render_key(track.key_wheel, track.key_mode)),
|
||||
image_id,
|
||||
track.comment, track.rating or 0, track.release_date,
|
||||
date.today().isoformat(), rel, item.destination.name, size,
|
||||
1, track.bitrate, None, 1, 1, 0, content_id,
|
||||
anlz_rel, ANALYSED_BITS, 0, 0, 0, 0,
|
||||
# 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, CONTENT_LINK, 0, 0, 0, 0,
|
||||
),
|
||||
)
|
||||
return self._write_anlz(item, rel, root / anlz_rel.lstrip("/"))
|
||||
return art_files + self._write_anlz(item, rel, root / anlz_rel.lstrip("/"))
|
||||
|
||||
# ---- artwork -------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _write_art(con, item: ExportTrack, root: Path, counter: dict) -> tuple[int | None, list[Path]]:
|
||||
"""One track's cover: four JPEGs and an `image` row, as rekordbox 7 writes.
|
||||
|
||||
`PIONEER/Artwork/00001/` holds `a<n>.jpg` / `a<n>_m.jpg` and a byte-
|
||||
identical `b<n>.jpg` / `b<n>_m.jpg` (80 and 240 px); `image.path` names the
|
||||
`b` file and `content.image_id` points at the row. rekordbox's own export
|
||||
writes both letters — the `a` pair presumably for the legacy `export.pdb`
|
||||
readers — so both are written here too.
|
||||
|
||||
Everything goes in folder `00001`. How rekordbox splits a large library
|
||||
across folders is not known (the reference export has 6 images); a single
|
||||
folder is what it demonstrably reads.
|
||||
"""
|
||||
if not item.art:
|
||||
return None, []
|
||||
jpegs = artwork.pioneer_jpegs(item.art[0])
|
||||
if jpegs is None:
|
||||
return None, []
|
||||
counter["next"] += 1
|
||||
n = counter["next"]
|
||||
folder = root / "PIONEER" / "Artwork" / "00001"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
small, medium = jpegs
|
||||
files = []
|
||||
for letter in ("a", "b"):
|
||||
for suffix, data in (("", small), ("_m", medium)):
|
||||
path = folder / f"{letter}{n}{suffix}.jpg"
|
||||
path.write_bytes(data)
|
||||
files.append(path)
|
||||
con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)",
|
||||
(n, f"/PIONEER/Artwork/00001/b{n}.jpg"))
|
||||
return n, files
|
||||
|
||||
# ---- the analysis files --------------------------------------------------
|
||||
|
||||
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
||||
"""The `.DAT` and, when there are cues beyond pad C, the `.EXT`.
|
||||
"""The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 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.
|
||||
All three, and every cue list, even for a track with no cues: rekordbox
|
||||
never produces a track without them, and `PCO2` — the complete list,
|
||||
which readers prefer — lives only in the `.EXT`.
|
||||
|
||||
**The `.DAT` must carry `PVBR` and the preview waveforms**, or rekordbox
|
||||
shows neither the grid nor the cues (see `anlz_writer`). The `.EXT` and
|
||||
`.2EX` waveforms only affect drawing: the song-list preview and the
|
||||
deck's scrolling waveform. Tag order is rekordbox's in each file:
|
||||
.DAT PPTH PVBR PQTZ PWAV PWV2 PCOB PCOB
|
||||
.EXT PPTH PWV3 PCOB PCOB PCO2 PCO2 PWV5 PWV4
|
||||
.2EX PPTH PWV7 PWV6 PWVC
|
||||
An undecodable file still gets the `.DAT` (with a flat preview) and the
|
||||
`.EXT` cue lists — its grid and cues must show — but no drawn waveforms.
|
||||
"""
|
||||
cues = self._cue_dicts(item)
|
||||
beats = self._beats(item)
|
||||
# rekordbox's clock runs ~25 ms behind the decoded audio on MP3/AAC (see
|
||||
# `timebase`): beats and cues are computed in the decoded time base and
|
||||
# shifted as they are packed, and the waveform frames are measured with
|
||||
# the same lead so they line up with the beats.
|
||||
off = timebase.offset(item.destination)
|
||||
measured = item.waveform(lead=off)
|
||||
# The DECODED length where there is one: `Track.length` is whole seconds
|
||||
# rounded down, and a grid expanded to it loses the track's last beat.
|
||||
beats = self._beats(item, measured.duration if measured else None)
|
||||
cues = self._cue_dicts(item, beats, off)
|
||||
if measured:
|
||||
previews = W.preview_tags(measured.columns.rms, measured.columns.brightness)
|
||||
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
|
||||
else:
|
||||
previews, ext_waves, two_ex = W.flat_preview_tags(), [], []
|
||||
|
||||
tags = [W.path_tag(rel)]
|
||||
tags = [W.path_tag(rel), W.vbr_tag(W.mp3_samples(item.destination))]
|
||||
if beats:
|
||||
tags.append(W.beatgrid_tag(beats))
|
||||
tags.append(W.beatgrid_tag([(n, bpm, timebase.to_pioneer(t, off))
|
||||
for n, bpm, t in beats]))
|
||||
tags += previews
|
||||
tags += W.cue_tags(cues, extended=False)
|
||||
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)])
|
||||
)
|
||||
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]]
|
||||
written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), ext)]
|
||||
if two_ex:
|
||||
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex]))
|
||||
return written
|
||||
|
||||
@staticmethod
|
||||
def _beats(item: ExportTrack) -> 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
|
||||
@@ -237,12 +335,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, off: float = 0.0) -> list[dict]:
|
||||
"""Generic cues in the shape `anlz_writer` packs.
|
||||
|
||||
Slot numbering is ANLZ's own: **dense 1-based**, 0 for a memory cue.
|
||||
@@ -253,13 +352,20 @@ class OneLibraryExporter:
|
||||
out: list[dict] = []
|
||||
for cue in (item.cues.cues if item.cues else []):
|
||||
is_loop = cue.type == "loop" or cue.length > 0
|
||||
# A hot cue carries what Konduktor SHOWS — stored colour, else the
|
||||
# type's (blue cue, green loop) — as a rekordbox palette CODE, which
|
||||
# is what rekordbox draws from; "unset" draws its own defaults. A
|
||||
# memory cue keeps rekordbox's own "unset".
|
||||
code, rgb = palette.code_for(cue.color if cue.role == "memory" else effective_color(cue))
|
||||
out.append({
|
||||
"hot_cue": 0 if cue.role == "memory" or cue.slot is None else cue.slot + 1,
|
||||
"kind": 2 if is_loop else 1,
|
||||
"time_ms": int(round(cue.start * 1000)),
|
||||
"loop_ms": int(round((cue.start + cue.length) * 1000)) if is_loop else None,
|
||||
"rgb": _rgb(cue.color),
|
||||
"beats": None,
|
||||
"time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)),
|
||||
"loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000))
|
||||
if is_loop else None),
|
||||
"rgb": rgb,
|
||||
"code": code,
|
||||
"beats": _loop_beats(cue.start, cue.length, beats or []) if is_loop else None,
|
||||
})
|
||||
return out
|
||||
|
||||
@@ -312,10 +418,51 @@ class OneLibraryExporter:
|
||||
)
|
||||
|
||||
|
||||
def _rgb(color: str | None) -> tuple[int, int, int] | None:
|
||||
if not color or not color.startswith("#") or len(color) != 7:
|
||||
#: 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:
|
||||
return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))
|
||||
except ValueError:
|
||||
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
|
||||
|
||||
@@ -54,7 +54,7 @@ def _bpm(row) -> float | None:
|
||||
return round(int(raw) / 100.0, 2)
|
||||
|
||||
|
||||
def to_track(row, drive_path: str | None = None) -> Track:
|
||||
def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track:
|
||||
"""Project one ``Content`` row.
|
||||
|
||||
**The three count fields are approximations here**, and deliberately so. Cues
|
||||
@@ -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))
|
||||
@@ -103,7 +104,8 @@ def to_track(row, drive_path: str | None = None) -> Track:
|
||||
hotcue_count=0,
|
||||
grid_marker_count=1 if (bpm and has_analysis) else 0,
|
||||
grid_locked=False, # OneLibrary has no grid lock
|
||||
media_kind="audio",
|
||||
# What the FILE is, as the deck plays it — see the Rekordbox projection.
|
||||
media_kind="stem" if stem else "audio",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ from pathlib import Path
|
||||
from ...core.adapter import LibraryNotSupported, NotFound
|
||||
from ...core.model import CuePoint
|
||||
from . import beatgrid, cues as cue_reader
|
||||
from ..rekordbox import timebase
|
||||
from .layout import DriveLayout
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -148,6 +149,30 @@ class OneLibraryStore:
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
return self.layout.resolve(getattr(self.content(track_id), "path", None))
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
"""The track's artwork: `content.image_id` -> `image.path` -> the file.
|
||||
|
||||
The row names the 80 px JPEG (`.../b<n>.jpg`); a `_m` sibling at 240 px
|
||||
sits beside it on every export seen, and is what is served — 80 px is a
|
||||
CDJ browse thumbnail, too small for anything Konduktor draws.
|
||||
"""
|
||||
image_id = getattr(self.content(track_id), "image_id", None)
|
||||
if not image_id:
|
||||
return None
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
|
||||
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
|
||||
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
|
||||
if small is None:
|
||||
return None
|
||||
medium = small.with_name(small.stem + "_m" + small.suffix)
|
||||
for path in (medium, small):
|
||||
try:
|
||||
return path.read_bytes(), "image/jpeg"
|
||||
except OSError:
|
||||
continue
|
||||
return None
|
||||
|
||||
def all_audio_paths(self) -> list[str]:
|
||||
out: list[str] = []
|
||||
for row in self.iter_content():
|
||||
@@ -185,8 +210,9 @@ class OneLibraryStore:
|
||||
return None
|
||||
return cache[key]
|
||||
|
||||
def anlz_grid(self, track_id: str) -> tuple[list[float], list[float]] | None:
|
||||
"""The per-beat ``(times, bpms)`` from the track's `PQTZ` tag.
|
||||
def anlz_grid(self, track_id: str) -> tuple[list[float], list[float], list[int]] | None:
|
||||
"""The per-beat ``(times, bpms, beat_in_bar)`` from the track's `PQTZ`
|
||||
tag, in the DECODED time base (see `rekordbox.timebase`).
|
||||
|
||||
`PQTZ` is in the `.DAT`, which is the cheap file — a grid read does not
|
||||
pay for the `.EXT`'s waveforms.
|
||||
@@ -194,7 +220,12 @@ class OneLibraryStore:
|
||||
anlz = self._anlz(track_id, extended=False)
|
||||
if anlz is None:
|
||||
return None
|
||||
return beatgrid.beats_from_pqtz(anlz)
|
||||
grid = beatgrid.beats_from_pqtz(anlz)
|
||||
if grid is None:
|
||||
return None
|
||||
off = timebase.offset(self.audio_path(track_id))
|
||||
times, bpms, beats = grid
|
||||
return [timebase.from_pioneer(t, off) for t in times], bpms, beats
|
||||
|
||||
def cues(self, track_id: str) -> list[CuePoint]:
|
||||
"""The track's cues, already generic.
|
||||
@@ -204,10 +235,15 @@ class OneLibraryStore:
|
||||
only mean anything once merged across two files, and handing that to the
|
||||
projection would put ANLZ knowledge on both sides of the boundary.
|
||||
"""
|
||||
return cue_reader.cues_from_anlz(
|
||||
cues = cue_reader.cues_from_anlz(
|
||||
self._anlz(track_id, extended=False),
|
||||
self._anlz(track_id, extended=True),
|
||||
)
|
||||
# Positions are stored on rekordbox's clock; the generic model is the
|
||||
# decoded audio's. A loop keeps its length.
|
||||
off = timebase.offset(self.audio_path(track_id))
|
||||
return [c.model_copy(update={"start": timebase.from_pioneer(c.start, off)})
|
||||
for c in cues] if off else cues
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlists(self) -> list:
|
||||
|
||||
@@ -8,6 +8,7 @@ capabilities.
|
||||
from ...core import export as core_export
|
||||
from ...core import registry
|
||||
from .driver import RekordboxDriver
|
||||
from .device_export import RekordboxDeviceExporter
|
||||
from .export import RekordboxExporter
|
||||
|
||||
REKORDBOX = RekordboxDriver()
|
||||
@@ -15,3 +16,8 @@ registry.register(REKORDBOX)
|
||||
|
||||
REKORDBOX_EXPORTER = RekordboxExporter()
|
||||
core_export.register(REKORDBOX_EXPORTER)
|
||||
|
||||
# The stick's legacy Device Library (`export.pdb`): a separate TARGET with no
|
||||
# reader of its own — Konduktor reads a stick through its OneLibrary database.
|
||||
REKORDBOX_DEVICE_EXPORTER = RekordboxDeviceExporter()
|
||||
core_export.register(REKORDBOX_DEVICE_EXPORTER)
|
||||
@@ -21,13 +21,13 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import Unsupported
|
||||
from ...core.adapter import InvalidCommand, Unsupported
|
||||
from ...core.capabilities import Capabilities
|
||||
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 projection
|
||||
from . import palette, projection, timebase
|
||||
from .store import RekordboxStore
|
||||
|
||||
|
||||
@@ -46,7 +46,8 @@ class RekordboxAdapter:
|
||||
kinds = self._store.cue_kinds()
|
||||
self._index.rebuild(
|
||||
[
|
||||
projection.to_track(row, kinds.get(str(row.ID), ()))
|
||||
projection.to_track(row, kinds.get(str(row.ID), ()),
|
||||
stem=self._store.is_stem(str(row.ID)))
|
||||
for row in self._store.iter_content()
|
||||
]
|
||||
)
|
||||
@@ -68,7 +69,8 @@ class RekordboxAdapter:
|
||||
"""
|
||||
kinds = self._store.cue_kinds()
|
||||
row = self._store.content(track_id)
|
||||
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ())))
|
||||
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ()),
|
||||
stem=self._store.is_stem(str(row.ID))))
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the database connection.
|
||||
@@ -80,7 +82,9 @@ class RekordboxAdapter:
|
||||
self._store.close()
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
"""Re-read the library from disk, DISCARDING unsaved edits (see
|
||||
`RekordboxStore.discard` for why a plain re-open is not enough)."""
|
||||
self._store.discard()
|
||||
self._cloud_synced = self._store.cloud_synced
|
||||
self._rebuild()
|
||||
|
||||
@@ -124,7 +128,8 @@ class RekordboxAdapter:
|
||||
if self._index.get(track_id) is None:
|
||||
return None
|
||||
cues = projection.to_track_cues(
|
||||
self._store.cues(track_id), self._store.anlz_grid(track_id)
|
||||
self._store.cues(track_id), self._store.anlz_grid(track_id),
|
||||
self._store.time_offset(track_id),
|
||||
)
|
||||
# The track projection carries an APPROXIMATE grid_marker_count until the
|
||||
# grid is actually read (see projection.to_track). This is that moment —
|
||||
@@ -199,6 +204,16 @@ class RekordboxAdapter:
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
# The FILE decides a track's media kind, and the mapping moves files.
|
||||
self._rebuild()
|
||||
|
||||
def unresolved_path_groups(self) -> list:
|
||||
"""Not checked yet: the open-time missing-files check is Traktor-only
|
||||
for now. Rekordbox's `FolderPath` is absolute too, so it will qualify."""
|
||||
return []
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
return None
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
paths = self._store.all_audio_paths()
|
||||
@@ -288,6 +303,18 @@ class RekordboxAdapter:
|
||||
self._store.set_cue_type(track_id, slot, cue_type)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
code = None
|
||||
if color is not None:
|
||||
code = palette.swatch_code(color)
|
||||
if code is None:
|
||||
raise InvalidCommand(
|
||||
f"{color!r} is not one of Rekordbox's hot cue colours"
|
||||
)
|
||||
self._store.set_cue_color(track_id, slot, code)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
self._require_writable("Deleting cues")
|
||||
self._store.delete_cue(track_id, slot)
|
||||
@@ -389,19 +416,97 @@ 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), (),
|
||||
stem=self._store.is_stem(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:
|
||||
# Same shape as adding: a track is a djmdContent row plus its cues,
|
||||
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and
|
||||
# which of those Rekordbox expects to be deleted together is unmeasured.
|
||||
self._refuse("Removing tracks")
|
||||
# What goes with a track was measured in Rekordbox 7 — see the store.
|
||||
self._require_writable("Removing tracks")
|
||||
n = self._store.remove_tracks(track_ids)
|
||||
if n:
|
||||
self._rebuild()
|
||||
return n
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
# Rekordbox does not play native-instruments stem files as stems.
|
||||
self._refuse("Converting tracks to stems")
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
@@ -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.
|
||||
@@ -37,6 +52,8 @@ from pathlib import Path
|
||||
from construct import Container, ListContainer
|
||||
from pyrekordbox.anlz import structs
|
||||
|
||||
from ...core.waveform import even_slices
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
NO_LOOP = 0xFFFFFFFF
|
||||
@@ -54,7 +71,9 @@ _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,
|
||||
"PWV3": 24, "PWV5": 24, "PWV4": 24, "PWV7": 24, "PWV6": 20, "PWVC": 14}
|
||||
|
||||
|
||||
def _wrap(kind: str, body: bytes) -> bytes:
|
||||
@@ -92,85 +111,311 @@ 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),
|
||||
]
|
||||
|
||||
|
||||
# ---- the detail and 3-band waveforms (`.EXT` / `.2EX`) -------------------------
|
||||
#
|
||||
# These only affect DRAWING — rekordbox shows the grid and cues without them — but
|
||||
# without them its song list has no preview and its deck draws a flat blue line,
|
||||
# and it warns the device was "analyzed by an older version". All constants are
|
||||
# fitted against rekordbox 7's own files for 12 local tracks, measured through
|
||||
# `core.waveform` exactly as the exporter measures (per-band mean error ~8 on the
|
||||
# 0-127 scale). rekordbox 7's song list draws `PWV6` — but ONLY for a track
|
||||
# whose `content.contentLink` is set (see the OneLibrary exporter); with it NULL
|
||||
# the row is plain blue whatever the files hold. `PWV4` is written by
|
||||
# distribution matching, not per-column fitting (see `_PWV4_MAPS`).
|
||||
|
||||
#: PWV7 byte per band = top * (energy / its 99.5th percentile) ** gamma.
|
||||
_PWV7 = ((88, 0.6), (92, 0.9), (68, 1.7)) # low, mid, high
|
||||
#: PWV6: the same, over 1200 overview columns (column = mean of its frames).
|
||||
_PWV6 = ((40, 0.5), (34, 0.5), (34, 0.5))
|
||||
#: PWVC: a per-band gain, = C / (the band's 99.5th percentile), floored at 80 —
|
||||
#: rekordbox's own values follow this to about +/-20%. What rekordbox does with
|
||||
#: it is not known; it is reproduced rather than invented.
|
||||
_PWVC_C, _PWVC_FLOOR = (20763.0, 15220.0, 12571.0), 80
|
||||
#: PWV3/PWV5 height (5 bits) from overall energy: 28 * x ** 1.5.
|
||||
_HEIGHT = (28, 1.5)
|
||||
#: PWV5 colour (3 bits each) from each band's SHARE of the frame's energy.
|
||||
_RGB = ((8.47, 0.54), (7.60, 0.47), (13.78, 1.83)) # red<-low, green<-mid, blue<-high
|
||||
_OVERVIEW_COLUMNS = 1200
|
||||
|
||||
#: PWV4 — the 6-byte colour overview. NOT what rekordbox 7's song list draws
|
||||
#: (that is PWV6: removing PWV6 from a rekordbox-written track left its row
|
||||
#: empty, removing PWV4 changed nothing); written because every rekordbox file
|
||||
#: carries it and its RGB mode and older players may read it. Per column: b0 overall level, b1 a
|
||||
#: companion of b0, b2 the height, b3/b4/b5 the low/mid/high (red/green/blue)
|
||||
#: levels. Two measured facts shape it: b4 and b5 are sampled at ONE instant per
|
||||
#: column (their column-to-column correlation is 0.05 and 0.16, against ~0.6 for
|
||||
#: the rest), and rekordbox's per-column bytes are too jumpy to reproduce one by
|
||||
#: one — so each byte is a QUANTILE MAP, (normalised measurement knots, byte
|
||||
#: knots), fitted on 12 tracks so the distribution matches rekordbox's (held-out
|
||||
#: medians within a few levels, the same spiky top end). b2 and b1 follow from
|
||||
#: the others by linear fits on rekordbox's own bytes (mean error 10 and 12).
|
||||
_PWV4_MAPS = {
|
||||
"b0": ((0.0, 0.1027, 0.1843, 0.3094, 0.3971, 0.4832, 0.5759, 0.6569, 0.731, 0.8102, 0.8973, 0.9419, 0.971, 1.1784),
|
||||
(0, 17, 28, 45, 56, 62, 65, 69, 74, 115, 127, 127, 127, 127)),
|
||||
"b3": ((0.0, 0.0135, 0.0473, 0.1407, 0.26, 0.3841, 0.5027, 0.5911, 0.6686, 0.7617, 0.8646, 0.9209, 0.9645, 1.1825),
|
||||
(0, 1, 4, 15, 24.7, 37, 44, 54, 62, 68, 89, 107, 120, 127)),
|
||||
"b4": ((0.0, 0.0305, 0.0654, 0.1307, 0.1855, 0.2325, 0.2819, 0.3342, 0.3977, 0.4809, 0.6036, 0.708, 0.8719, 1.2804),
|
||||
(0, 2, 7, 12, 17, 21, 25, 30, 35, 43, 62, 109, 127, 127)),
|
||||
"b5": ((0.0, 0.0077, 0.0223, 0.0511, 0.09, 0.1298, 0.1809, 0.2427, 0.3167, 0.4143, 0.5749, 0.7209, 0.863, 1.4313),
|
||||
(0, 1, 4, 7, 10, 12, 16, 20, 24, 31, 60, 127, 127, 127)),
|
||||
}
|
||||
|
||||
|
||||
def _pwv4(bands) -> bytes:
|
||||
import numpy as np
|
||||
|
||||
full = np.sqrt((bands ** 2).sum(axis=1))
|
||||
x = np.column_stack([bands, full]) # low, mid, high, full
|
||||
cols = [np.arange(len(x))[s] for s in even_slices(len(x), _OVERVIEW_COLUMNS)]
|
||||
mean = np.array([x[i].mean(axis=0) if len(i) else np.zeros(4) for i in cols])
|
||||
instant = np.array([x[i[len(i) // 2]] if len(i) else np.zeros(4) for i in cols])
|
||||
|
||||
def mapped(values, key):
|
||||
ref = float(np.percentile(values, 99.5)) or 1.0
|
||||
knots_x, knots_y = _PWV4_MAPS[key]
|
||||
return np.clip(np.round(np.interp(values / ref, knots_x, knots_y)), 0, 127).astype(int)
|
||||
|
||||
b0, b3 = mapped(mean[:, 3], "b0"), mapped(mean[:, 0], "b3")
|
||||
b4, b5 = mapped(instant[:, 1], "b4"), mapped(instant[:, 2], "b5")
|
||||
b2 = np.clip(np.round(0.83 * np.maximum(b3, np.maximum(b4, b5)) + 11.6), 0, 127).astype(int)
|
||||
b1 = np.clip(np.round(235.2 - 0.77 * b0), 0, 255).astype(int)
|
||||
return np.column_stack([b0, b1, b2, b3, b4, b5]).astype(np.uint8).tobytes()
|
||||
|
||||
|
||||
def _norm(x, top: float, gamma: float, cap: int):
|
||||
import numpy as np
|
||||
|
||||
ref = float(np.percentile(x, 99.5)) or 1.0
|
||||
return np.clip(np.round(top * np.clip(x / ref, 0, None) ** gamma), 0, cap).astype(int)
|
||||
|
||||
|
||||
def waveform_tags(bands) -> tuple[list[bytes], list[bytes]]:
|
||||
"""(`.EXT` tags, `.2EX` tags) from 150-per-second low/mid/high band energy.
|
||||
|
||||
`.EXT`: `PWV3` (detail, 1 byte: whiteness << 5 | height), `PWV5` (detail
|
||||
colour, 2 bytes: rrr ggg bbb hhhhh 00) and `PWV4` (the RGB-mode colour
|
||||
overview, 1200 x 6 bytes — see `_PWV4_MAPS`). `.2EX`: `PWV7` (3-band detail, one
|
||||
byte per band), `PWV6` (3-band overview, 1200 columns) and `PWVC`. The frames
|
||||
must already be on rekordbox's clock (`waveform.analyse(lead=offset)`).
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
bands = np.asarray(bands, dtype=float)
|
||||
n = len(bands)
|
||||
full = np.sqrt((bands ** 2).sum(axis=1))
|
||||
share = bands / (bands.sum(axis=1, keepdims=True) + 1e-12)
|
||||
|
||||
height = _norm(full, *_HEIGHT, 31)
|
||||
white = np.clip(np.round(2.5 + 10.0 * share[:, 2]), 0, 7).astype(int)
|
||||
pwv3 = bytes(int((w << 5) | h) for w, h in zip(white, height))
|
||||
rgb = [np.clip(np.round(k * share[:, i] + c), 0, 7).astype(int)
|
||||
for i, (k, c) in enumerate(_RGB)]
|
||||
pwv5 = b"".join(struct.pack(">H", (int(r) << 13) | (int(g) << 10) | (int(b) << 7) | (int(h) << 2))
|
||||
for r, g, b, h in zip(*rgb, height))
|
||||
|
||||
pwv7 = np.stack([_norm(bands[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV7)], axis=1)
|
||||
cols = np.array([bands[s].mean(axis=0) if n else np.zeros(3)
|
||||
for s in even_slices(n, _OVERVIEW_COLUMNS)])
|
||||
pwv6 = np.stack([_norm(cols[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV6)], axis=1)
|
||||
gains = [max(_PWVC_FLOOR, int(round(c / (float(np.percentile(bands[:, i], 99.5)) or 1.0))))
|
||||
for i, c in enumerate(_PWVC_C)]
|
||||
|
||||
ext = [
|
||||
_wrap("PWV3", struct.pack(">III", 1, n, 0x00960000) + pwv3),
|
||||
_wrap("PWV5", struct.pack(">III", 2, n, 0x00960305) + pwv5),
|
||||
_wrap("PWV4", struct.pack(">III", 6, _OVERVIEW_COLUMNS, 0) + _pwv4(bands)),
|
||||
]
|
||||
two_ex = [
|
||||
_wrap("PWV7", struct.pack(">III", 3, n, 0x00960000) + pwv7.astype(np.uint8).tobytes()),
|
||||
_wrap("PWV6", struct.pack(">II", 3, _OVERVIEW_COLUMNS) + pwv6.astype(np.uint8).tobytes()),
|
||||
_wrap("PWVC", struct.pack(">H", 0) + struct.pack(">HHH", *[min(g, 0xFFFF) for g in gains])),
|
||||
]
|
||||
return ext, two_ex
|
||||
|
||||
|
||||
def flat_preview_tags() -> list[bytes]:
|
||||
"""Empty previews, for a file nothing could decode, so the grid and cues can
|
||||
still show. That an all-zero preview satisfies rekordbox is an assumption,
|
||||
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:
|
||||
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> bytes:
|
||||
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
|
||||
|
||||
Two constants in here are rekordbox's, not the documented struct's: the
|
||||
`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),
|
||||
) + comment + struct.pack(">4B", 0, red, green, blue) + bytes(
|
||||
0, 1, beats or 0, 1 if beats else 0, len(comment),
|
||||
# The colour is the palette CODE, then RGB: rekordbox draws from the code
|
||||
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
|
||||
) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
|
||||
PCP2_ENTRY_LEN - 48 - len(comment)
|
||||
)
|
||||
|
||||
|
||||
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"),
|
||||
code=c.get("code", 0))
|
||||
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.
|
||||
_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
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Cover art the way a Pioneer library stores it: two small square JPEGs.
|
||||
|
||||
Measured on a rekordbox 7 USB export rather than assumed:
|
||||
|
||||
* two sizes per image — **80 x 80** (`<n>.jpg`) and **240 x 240** (`<n>_m.jpg`);
|
||||
* **baseline JPEG at quality 85, 4:2:0** — its quantisation table is libjpeg's
|
||||
standard table scaled to exactly 85, with no EXIF and a plain JFIF header;
|
||||
* a non-square cover is **letterboxed onto black**, aspect kept and centred.
|
||||
Motorola's 4112 x 1112 art matches rekordbox's own to a mean of 1.8 levels
|
||||
that way; a centre crop is off by 26, a stretch by 19.5.
|
||||
|
||||
Where the files go and how the database points at them is the target's business
|
||||
(a OneLibrary drive: `PIONEER/Artwork/00001/`, see its exporter).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SMALL, MEDIUM = 80, 240
|
||||
#: A master.db library also keeps a LARGE copy: the cover itself, aspect kept,
|
||||
#: scaled down to fit 800 px (never up) — Motorola's 4112 x 1112 art is stored
|
||||
#: 800 x 216, a 640 or 300 px cover unchanged.
|
||||
LARGE = 800
|
||||
_QUALITY = 85
|
||||
|
||||
|
||||
def _square(image, size: int):
|
||||
from PIL import Image
|
||||
|
||||
fitted = image.copy()
|
||||
fitted.thumbnail((size, size), Image.BICUBIC) # the closest of Pillow's filters
|
||||
canvas = Image.new("RGB", (size, size), (0, 0, 0))
|
||||
canvas.paste(fitted, ((size - fitted.width) // 2, (size - fitted.height) // 2))
|
||||
return canvas
|
||||
|
||||
|
||||
def _jpeg(image) -> bytes:
|
||||
out = io.BytesIO()
|
||||
# subsampling=2 is 4:2:0; progressive/optimize off = the baseline rekordbox writes.
|
||||
image.save(out, format="JPEG", quality=_QUALITY, subsampling=2,
|
||||
progressive=False, optimize=False)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _open(data: bytes):
|
||||
from PIL import Image
|
||||
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as src:
|
||||
src.load()
|
||||
return src.convert("RGB") # PNG alpha / palette / CMYK -> RGB
|
||||
except Exception as ex: # noqa: BLE001 — any unreadable image
|
||||
log.warning("could not read cover art (%s); exporting without it", ex)
|
||||
return None
|
||||
|
||||
|
||||
def library_jpegs(data: bytes) -> tuple[bytes, bytes, bytes] | None:
|
||||
"""(large, 240 px, 80 px) for a `master.db` library — `artwork.jpg`,
|
||||
`artwork_m.jpg`, `artwork_s.jpg` — or None when the image cannot be read."""
|
||||
from PIL import Image
|
||||
|
||||
rgb = _open(data)
|
||||
if rgb is None:
|
||||
return None
|
||||
large = rgb.copy()
|
||||
large.thumbnail((LARGE, LARGE), Image.BICUBIC)
|
||||
return _jpeg(large), _jpeg(_square(rgb, MEDIUM)), _jpeg(_square(rgb, SMALL))
|
||||
|
||||
|
||||
def pioneer_jpegs(data: bytes) -> tuple[bytes, bytes] | None:
|
||||
"""(80 px JPEG, 240 px JPEG) from any image the source library holds, or None
|
||||
when it cannot be read — a bad cover costs the artwork, not the export."""
|
||||
try:
|
||||
from PIL import Image
|
||||
|
||||
with Image.open(io.BytesIO(data)) as src:
|
||||
src.load()
|
||||
rgb = src.convert("RGB") # PNG alpha / palette / CMYK -> RGB
|
||||
except Exception as ex: # noqa: BLE001 — any unreadable image
|
||||
log.warning("could not read cover art (%s); exporting without it", ex)
|
||||
return None
|
||||
return _jpeg(_square(rgb, SMALL)), _jpeg(_square(rgb, MEDIUM))
|
||||
@@ -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
|
||||
@@ -72,9 +99,15 @@ def beats_from_markers(
|
||||
n = 1
|
||||
# Guard against a zero/negative span producing an endless loop.
|
||||
while t < end - 1e-9 and step > 0:
|
||||
beat_nums.append(n)
|
||||
bpms.append(m.bpm)
|
||||
times.append(t)
|
||||
# A beat before the audio starts is skipped but still COUNTED, so the
|
||||
# next one keeps its place in the bar. The generic model can hold one
|
||||
# (a Traktor grid anchored inside an MP3's header frame reads
|
||||
# negative); rekordbox stores no negative times, and clamping it to 0
|
||||
# would invent a beat there.
|
||||
if t >= 0.0:
|
||||
beat_nums.append(n)
|
||||
bpms.append(m.bpm)
|
||||
times.append(t)
|
||||
n = n % 4 + 1
|
||||
t += step
|
||||
return beat_nums, bpms, times
|
||||
|
||||
@@ -30,6 +30,7 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from . import palette
|
||||
from .cue_types import WRITABLE_CUE_TYPES
|
||||
|
||||
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
|
||||
@@ -68,8 +69,10 @@ def capabilities_for(
|
||||
max_memory_cues=None, # unlimited
|
||||
# Both cue types write; Rekordbox has no fade/load types.
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
# A hot cue's colour is one of rekordbox's swatches (the 15 that
|
||||
# were measured, see `palette`), offered in rekordbox's own order.
|
||||
color="palette",
|
||||
palette=[], # TODO milestone 2: the built-in cue colour table
|
||||
palette=[palette.hex_for(code) for code in palette.SWATCHES],
|
||||
named=True, # djmdCue.Comment
|
||||
loops="cue_type",
|
||||
),
|
||||
@@ -83,7 +86,11 @@ def capabilities_for(
|
||||
# column (its Composer is a different field), so they are absent
|
||||
# rather than mapped onto something approximate.
|
||||
editable_fields=sorted(editable_fields or []),
|
||||
media_kinds=["audio"],
|
||||
# A stem file is held (and played by Rekordbox as its mix);
|
||||
# Konduktor's deck plays its stems.
|
||||
media_kinds=["audio", "stem"],
|
||||
removable=True,
|
||||
addable=True,
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
"""The "Rekordbox Export" target: a USB stick's legacy Device Library (`export.pdb`).
|
||||
|
||||
What Rekordbox lists as a stick's **Device Library**, and what pre-OneLibrary
|
||||
players (CDJ-2000NXS2, many XDJs) read. Not to be confused with the "Rekordbox
|
||||
Library" target (`export.py`), which writes a COMPUTER library (`master.db`)
|
||||
that Rekordbox never reads from a stick.
|
||||
|
||||
## Shared with the OneLibrary target — deliberately
|
||||
|
||||
Rekordbox's own device export writes `export.pdb` AND `exportLibrary.db`, both
|
||||
pointing at ONE set of audio, analysis files and artwork. This target does the
|
||||
same: the analysis files are written by the OneLibrary exporter's own
|
||||
`_write_anlz`, at the same paths (`PIONEER/USBANLZ/P0xx/xxxxxxxx/`), and the
|
||||
artwork is the `a<n>.jpg` pair the OneLibrary target also writes (rekordbox's
|
||||
`a` files are the ones `export.pdb` names; OneLibrary's `image` table names the
|
||||
byte-identical `b` files). When both targets are ticked, whichever runs second
|
||||
finds the analysis already on the stick — written moments ago by the first, as
|
||||
the runner clears the previous export before copying — and reuses it rather
|
||||
than decoding every track again.
|
||||
|
||||
## The database
|
||||
|
||||
`pdb.PdbWriter` fills rekordbox's own empty device library (a template) with
|
||||
rows; see `pdb.py` for the format and why a template. Values follow a real
|
||||
rekordbox 7 device export:
|
||||
|
||||
* `bitmask` 0xC0700 — the same value as OneLibrary's `content.contentLink`,
|
||||
which is what makes rekordbox draw a track's song-list preview there;
|
||||
* `u2` = the track id + 0x600 (rekordbox: masterContentId + 0x600);
|
||||
* `u3`/`u4` = 0: they are the halves of rekordbox's `masterDbId`, the link to a
|
||||
computer's collection, which a Konduktor export does not claim;
|
||||
* `u5` 0x29 (= `analysedBits` 41), `u6` the file type, `u7` 3;
|
||||
* strings "ON" for kuvo_public / autoload_hotcues; the three unnamed strings
|
||||
rekordbox fills from its phrase analysis are left EMPTY — this exporter
|
||||
writes no phrases, and whether players care is what the device test checks.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from . import artwork, pdb
|
||||
from .projection import render_key
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
PDB_DIR = Path("PIONEER") / "rekordbox"
|
||||
OTHER_PLAYLIST = "Other"
|
||||
BITMASK = 0xC0700
|
||||
ANALYSED = 0x29
|
||||
|
||||
|
||||
class RekordboxDeviceExporter:
|
||||
platform = "rekordbox_export"
|
||||
menu_order = 30
|
||||
display_name = "Rekordbox Export"
|
||||
library_filename = str(PDB_DIR / "export.pdb")
|
||||
#: A player looks for `PIONEER/` at the root of the stick.
|
||||
drive_root = True
|
||||
|
||||
def capabilities(self):
|
||||
"""What a stick's device library can hold — the OneLibrary target's
|
||||
answer, since both describe the same drive and its analysis files."""
|
||||
from ..onelibrary.export import OneLibraryExporter
|
||||
|
||||
return OneLibraryExporter().capabilities()
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
# Imported here, not at module level: the OneLibrary package imports this
|
||||
# package's modules, and a module-level import would be circular.
|
||||
from ..onelibrary.export import (
|
||||
OneLibraryExporter, _anlz_dir, _audio_format, _drive_relative, _file_type, _kbps,
|
||||
)
|
||||
|
||||
root = Path(destination)
|
||||
(root / PDB_DIR).mkdir(parents=True, exist_ok=True)
|
||||
today = date.today().isoformat()
|
||||
drive = OneLibraryExporter()
|
||||
extra: list[Path] = []
|
||||
|
||||
ids = {name: {} for name in ("artist", "album", "genre", "label", "key")}
|
||||
rows = {t: [] for t in (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES,
|
||||
pdb.LABELS, pdb.KEYS, pdb.ARTWORK)}
|
||||
builders = {"artist": (pdb.ARTISTS, pdb.artist_row), "album": (pdb.ALBUMS, pdb.album_row),
|
||||
"genre": (pdb.GENRES, pdb.id_string_row), "label": (pdb.LABELS, pdb.id_string_row),
|
||||
"key": (pdb.KEYS, pdb.key_row)}
|
||||
|
||||
def lookup(kind: str, name: str | None) -> int:
|
||||
if not name:
|
||||
return 0
|
||||
table = ids[kind]
|
||||
if name not in table:
|
||||
table[name] = len(table) + 1
|
||||
t, build = builders[kind]
|
||||
rows[t].append(build(table[name], name))
|
||||
return table[name]
|
||||
|
||||
by_source: dict[str, int] = {}
|
||||
art_n = 0
|
||||
total = len(payload.tracks)
|
||||
for n, item in enumerate(payload.tracks, start=1):
|
||||
payload.checkpoint(f"Writing the device library: {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
|
||||
track = item.track
|
||||
by_source[item.source_id] = n
|
||||
rel = _drive_relative(item.destination, root)
|
||||
anlz_rel = f"{_anlz_dir(rel)}/ANLZ0000.DAT"
|
||||
dat = root / anlz_rel.lstrip("/")
|
||||
extra += self._analysis(drive, item, rel, dat)
|
||||
|
||||
artwork_id = 0
|
||||
art = self._art(item, root, art_n + 1)
|
||||
if art:
|
||||
art_n += 1
|
||||
artwork_id = art_n
|
||||
extra += art
|
||||
rows[pdb.ARTWORK].append(pdb.id_string_row(art_n, f"/PIONEER/Artwork/00001/a{art_n}.jpg"))
|
||||
|
||||
sample_rate, bit_depth = _audio_format(item.destination)
|
||||
try:
|
||||
size = item.destination.stat().st_size
|
||||
except OSError:
|
||||
size = 0
|
||||
year = int(track.release_date[:4]) if (track.release_date or "")[:4].isdigit() else 0
|
||||
rows[pdb.TRACKS].append(pdb.track_row(
|
||||
{
|
||||
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": sample_rate or 0,
|
||||
"file_size": size, "u2": n + 0x600,
|
||||
"artwork_id": artwork_id,
|
||||
"key_id": lookup("key", render_key(track.key_wheel, track.key_mode)),
|
||||
"label_id": lookup("label", track.label),
|
||||
"bitrate": _kbps(track.bitrate) or 0,
|
||||
"tempo": int(round((track.bpm or 0) * 100)),
|
||||
"genre_id": lookup("genre", track.genre),
|
||||
"album_id": lookup("album", track.album),
|
||||
"artist_id": lookup("artist", track.artist),
|
||||
"id": n, "year": year, "sample_depth": bit_depth or 0,
|
||||
"duration": min(int(track.length or 0), 0xFFFF),
|
||||
"u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))),
|
||||
"u6": _file_type(item.destination), "u7": 3,
|
||||
},
|
||||
{
|
||||
"kuvo_public": "ON", "autoload_hotcues": "ON",
|
||||
"date_added": today, "release_date": track.release_date or "",
|
||||
"mix_name": track.mix or "", "analyze_path": anlz_rel,
|
||||
"analyze_date": today, "comment": track.comment or "",
|
||||
"title": track.title or item.destination.stem,
|
||||
"filename": item.destination.name, "file_path": rel,
|
||||
},
|
||||
))
|
||||
|
||||
tree, entries = self._playlists(payload, by_source)
|
||||
writer = pdb.PdbWriter(pdb.template("export.pdb"))
|
||||
for table in (pdb.TRACKS, pdb.GENRES, pdb.ARTISTS, pdb.ALBUMS, pdb.LABELS, pdb.KEYS, pdb.ARTWORK):
|
||||
writer.fill(table, rows[table])
|
||||
writer.fill(pdb.PLAYLIST_TREE, tree)
|
||||
writer.fill(pdb.PLAYLIST_ENTRIES, entries)
|
||||
writer.stamp_history_date(date.today())
|
||||
writer.stamp_track_count(len(rows[pdb.TRACKS]))
|
||||
|
||||
library = root / self.library_filename
|
||||
library.write_bytes(writer.render())
|
||||
ext = root / PDB_DIR / "exportExt.pdb"
|
||||
ext.write_bytes(pdb.template("exportExt.pdb"))
|
||||
return WrittenLibrary(library=library, extra=[ext, *extra])
|
||||
|
||||
# ---- shared drive files ---------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _analysis(drive, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
||||
"""This track's analysis files — reused when the OneLibrary target has
|
||||
just written them in this same export, else written the same way."""
|
||||
existing = [dat.with_suffix(s) for s in (".DAT", ".EXT", ".2EX") if dat.with_suffix(s).exists()]
|
||||
if dat.exists() and dat.with_suffix(".EXT").exists():
|
||||
return existing
|
||||
return drive._write_anlz(item, rel, dat)
|
||||
|
||||
@staticmethod
|
||||
def _art(item: ExportTrack, root: Path, n: int) -> list[Path]:
|
||||
"""`a<n>.jpg` / `a<n>_m.jpg` — the pair export.pdb's artwork table names,
|
||||
numbered in track order exactly as the OneLibrary target numbers them."""
|
||||
if not item.art:
|
||||
return []
|
||||
folder = root / "PIONEER" / "Artwork" / "00001"
|
||||
small, medium = folder / f"a{n}.jpg", folder / f"a{n}_m.jpg"
|
||||
if small.exists() and medium.exists():
|
||||
return [small, medium]
|
||||
jpegs = artwork.pioneer_jpegs(item.art[0])
|
||||
if jpegs is None:
|
||||
return []
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
small.write_bytes(jpegs[0])
|
||||
medium.write_bytes(jpegs[1])
|
||||
return [small, medium]
|
||||
|
||||
# ---- playlists ------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
|
||||
"""The tree under one folder named after the export, as the other
|
||||
targets build it. `sort_order` is a node's position among its siblings."""
|
||||
tree: list[bytes] = []
|
||||
entries: list[bytes] = []
|
||||
next_id = [0]
|
||||
siblings: dict[int, int] = {}
|
||||
|
||||
def add(name: str, parent: int, *, folder: bool) -> int:
|
||||
next_id[0] += 1
|
||||
order = siblings.get(parent, 0)
|
||||
siblings[parent] = order + 1
|
||||
tree.append(pdb.playlist_tree_row(next_id[0], parent, order, name, folder=folder))
|
||||
return next_id[0]
|
||||
|
||||
def fill(playlist_id: int, source_ids: list[str]) -> None:
|
||||
index = 0
|
||||
for source_id in source_ids:
|
||||
track_id = by_source.get(source_id)
|
||||
if track_id is not None:
|
||||
index += 1
|
||||
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
|
||||
|
||||
root = add(payload.name, 0, folder=True)
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
for depth in range(1, len(playlist.folders) + 1):
|
||||
branch = tuple(playlist.folders[:depth])
|
||||
if branch not in folders:
|
||||
folders[branch] = add(branch[-1], folders[branch[:-1]], folder=True)
|
||||
parent = folders[branch]
|
||||
fill(add(playlist.name, parent, folder=False), playlist.track_ids)
|
||||
claimed = {t for p in payload.playlists for t in p.track_ids}
|
||||
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
|
||||
if loose:
|
||||
fill(add(OTHER_PLAYLIST, root, folder=False), loose)
|
||||
return tree, entries
|
||||
@@ -57,11 +57,14 @@ from pathlib import Path
|
||||
from sqlalchemy import text
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from . import anlz_writer as W
|
||||
from ...core.cue_colors import effective_color
|
||||
from . import new_content, palette
|
||||
from . import timebase
|
||||
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__)
|
||||
|
||||
@@ -77,12 +80,35 @@ SEED = _FIXTURES / "seed.sql"
|
||||
|
||||
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
|
||||
FRAMES_PER_SECOND = 150
|
||||
|
||||
#: `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
|
||||
#: file does not vouch for is not shown. The skeleton is a real Rekordbox 7
|
||||
#: file's, minus its nodes — pyrekordbox adds ours as it creates them.
|
||||
PLAYLISTS_XML = "masterPlaylists6.xml"
|
||||
PLAYLISTS_XML_SKELETON = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n\n'
|
||||
'<MASTER_PLAYLIST Version="3.0.0" AutomaticSync="0">\n'
|
||||
' <PRODUCT Name="rekordbox" Version="7.2.18" Company="Pioneer DJ"/>\n'
|
||||
' <PLAYLISTS>\n </PLAYLISTS>\n'
|
||||
'</MASTER_PLAYLIST>\n'
|
||||
)
|
||||
OTHER_PLAYLIST = "Other"
|
||||
|
||||
|
||||
class RekordboxExporter:
|
||||
platform = "rekordbox"
|
||||
menu_order = 40
|
||||
#: A COMPUTER library (master.db), which Rekordbox never reads from a stick —
|
||||
#: named so, beside "Rekordbox Export" (the stick's Device Library).
|
||||
display_name = "Rekordbox Library"
|
||||
#: Rekordbox opens a master.db only from its own library folder.
|
||||
computer_only = True
|
||||
library_filename = "master.db"
|
||||
drive_root = False
|
||||
|
||||
def capabilities(self):
|
||||
"""What a Rekordbox library can hold, with no library to read.
|
||||
@@ -124,20 +150,35 @@ class RekordboxExporter:
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
# BEFORE the database is opened: pyrekordbox keeps masterPlaylists6.xml
|
||||
# in step with every playlist it creates — but only if the file exists
|
||||
# at open time. Without it Rekordbox opened the library, generated its
|
||||
# own file listing our playlists with Timestamp 0, and showed NONE of
|
||||
# them (measured by swapping an export into a real Rekordbox 7).
|
||||
playlists_xml = root / PLAYLISTS_XML
|
||||
playlists_xml.write_text(PLAYLISTS_XML_SKELETON, encoding="utf-8")
|
||||
|
||||
db = MasterDatabase(path=str(library), key=key)
|
||||
extra: list[Path] = []
|
||||
extra: list[Path] = [playlists_xml]
|
||||
ids: dict[str, str] = {}
|
||||
try:
|
||||
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})", step=n, of=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)
|
||||
extra += self._write_art(item, content, root)
|
||||
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()
|
||||
|
||||
@@ -146,7 +187,7 @@ class RekordboxExporter:
|
||||
|
||||
@staticmethod
|
||||
def _replay_cues(library: Path, payload: ExportPayload, ids: dict) -> None:
|
||||
"""Write the cues through the ORDINARY adapter, not by hand.
|
||||
"""Write the cues through the ORDINARY cue-row code, not by hand.
|
||||
|
||||
Same reason the Traktor exporter replays commands: `set_cue` already
|
||||
owns every convention a cue row needs — the sparse `Kind` bank, frames
|
||||
@@ -158,24 +199,33 @@ class RekordboxExporter:
|
||||
from .adapter import RekordboxAdapter
|
||||
|
||||
adapter = RekordboxAdapter(library)
|
||||
# The store, not the adapter's commands: the adapter refuses memory cues
|
||||
# (editing them in a user's library is off-limits) and takes no colour.
|
||||
# Building a NEW library is neither an edit nor lossy by choice, so the
|
||||
# exporter writes both — through the same `_write_cue` every edit uses.
|
||||
store = adapter._store
|
||||
try:
|
||||
for item in payload.tracks:
|
||||
track_id = ids.get(item.source_id)
|
||||
if track_id is None or not item.cues:
|
||||
continue
|
||||
for cue in item.cues.cues:
|
||||
# Memory cues are a Rekordbox-only concept the generic model
|
||||
# preserves but never writes; a cue with no slot has no pad
|
||||
# to land on.
|
||||
if cue.role != "hotcue" or cue.slot is None:
|
||||
if cue.role == "memory" or cue.slot is None:
|
||||
# rekordbox's own "unset" for a memory cue with no colour.
|
||||
code, _rgb = palette.code_for(cue.color)
|
||||
store.add_memory_cue(
|
||||
track_id, start_sec=cue.start, cue_type=cue.type,
|
||||
length_sec=cue.length, name=cue.name, color_code=code or None,
|
||||
)
|
||||
continue
|
||||
adapter.set_cue(
|
||||
track_id,
|
||||
slot=cue.slot,
|
||||
start_sec=cue.start,
|
||||
cue_type=cue.type,
|
||||
length_sec=cue.length,
|
||||
name=cue.name,
|
||||
# What Konduktor SHOWS — stored colour, else the type's (blue
|
||||
# cue, green loop) — as a palette code, which is what
|
||||
# rekordbox draws from. White (a grid companion) has no swatch:
|
||||
# code 0, i.e. uncoloured.
|
||||
code, _rgb = palette.code_for(effective_color(cue))
|
||||
store.set_cue(
|
||||
track_id, slot=cue.slot, start_sec=cue.start, cue_type=cue.type,
|
||||
length_sec=cue.length, name=cue.name, color_code=code or None,
|
||||
)
|
||||
adapter.save()
|
||||
finally:
|
||||
@@ -255,32 +305,13 @@ class RekordboxExporter:
|
||||
# NOT `track.key`: that is the SOURCE platform's notation, so a Traktor
|
||||
# export would put "10m" where Rekordbox shows "Cm".
|
||||
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
|
||||
content.ContentLink = CONTENT_LINK
|
||||
db.flush()
|
||||
return content
|
||||
|
||||
@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 ---------------------------------------------------------------
|
||||
|
||||
@@ -291,26 +322,63 @@ 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()
|
||||
|
||||
tags = [W.path_tag(str(item.destination))]
|
||||
off = timebase.offset(item.destination)
|
||||
measured = item.waveform(lead=off)
|
||||
beats = None
|
||||
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))))
|
||||
# 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.
|
||||
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.
|
||||
return [W.write_anlz(root / "share" / rel.lstrip("/"), tags)]
|
||||
dat = root / "share" / rel.lstrip("/")
|
||||
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 ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _write_art(item: ExportTrack, content, root: Path) -> list[Path]:
|
||||
"""The cover, as a rekordbox-managed track carries it.
|
||||
|
||||
Three JPEGs under `share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/` — the
|
||||
same UUID split as the analysis folder — named `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`,
|
||||
rooted at `share/` like `AnalysisDataPath`. All measured on a real
|
||||
Rekordbox 7 library.
|
||||
"""
|
||||
files = new_content.artwork_files(item.art[0] if item.art else None)
|
||||
if files is None:
|
||||
return []
|
||||
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 files.items():
|
||||
(folder / name).write_bytes(data)
|
||||
written.append(folder / name)
|
||||
content.ImagePath = f"{rel}/artwork.jpg"
|
||||
return written
|
||||
|
||||
# ---- playlists ---------------------------------------------------------------
|
||||
|
||||
@@ -346,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
|
||||
@@ -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
|
||||
@@ -0,0 +1,118 @@
|
||||
"""rekordbox's hot-cue colour palette: a generic `#RRGGBB` -> (palette code, RGB).
|
||||
|
||||
**rekordbox draws a hot cue from its palette CODE, not from its RGB bytes.** An
|
||||
export that wrote only RGB (code 0) had every cue drawn in rekordbox's defaults
|
||||
— green cues, orange loops. The code is `PCP2`'s colour byte (offset 44, before
|
||||
the RGB triple) in the ANLZ `.EXT`, and `djmdCue.ColorTableIndex` in `master.db`.
|
||||
|
||||
The table was MEASURED, not recalled: 16 hot cues coloured through rekordbox 7's
|
||||
own palette, one colour per pad, exported to a stick, and read back. Rekordbox
|
||||
writes the palette's exact RGB beside each code.
|
||||
|
||||
* One palette colour went unmeasured — the teal-green between 0x0E and 0x16
|
||||
(probably code 0x12); a cue that should be it maps to its nearest neighbour.
|
||||
* 0x2B (#FF0017) was observed on a real export though it is not one of the 16
|
||||
swatches; it is kept so such a colour survives a round trip exactly.
|
||||
* **The palette has no white or grey.** A colourless (white/grey) cue — above
|
||||
all Traktor's white grid-marker companion — gets code 0 with its RGB. rekordbox
|
||||
produces that state itself (the reference fixture's cues are code 0 + RGB);
|
||||
what rekordbox DRAWS for it is not yet verified.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import colorsys
|
||||
|
||||
#: code -> RGB, exactly as rekordbox 7 writes them.
|
||||
PALETTE: dict[int, tuple[int, int, int]] = {
|
||||
0x31: (0xFF, 0x00, 0xA1), # magenta
|
||||
0x38: (0xB3, 0x00, 0xFF), # purple
|
||||
0x3C: (0x4D, 0x00, 0xFF), # violet
|
||||
0x3E: (0x1A, 0x00, 0xFF), # blue-violet
|
||||
0x01: (0x00, 0x00, 0xFF), # blue
|
||||
0x05: (0x00, 0x70, 0xFF), # light blue
|
||||
0x09: (0x00, 0xE0, 0xFF), # cyan
|
||||
0x0E: (0x00, 0xFF, 0xA3), # teal
|
||||
0x16: (0x1A, 0xFF, 0x00), # green
|
||||
0x1A: (0x80, 0xFF, 0x00), # lime
|
||||
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
|
||||
0x20: (0xFF, 0xE8, 0x00), # yellow
|
||||
0x26: (0xFF, 0x5E, 0x00), # orange
|
||||
0x2A: (0xFF, 0x00, 0x00), # red
|
||||
0x2B: (0xFF, 0x00, 0x17), # red (observed, not a swatch)
|
||||
0x2D: (0xFF, 0x00, 0x45), # pink-red
|
||||
}
|
||||
|
||||
#: Konduktor's TYPE colours (`core.cue_colors`) -> the swatch a DJ would call by
|
||||
#: the same name. Nearest-hue alone sends the mint loop green to TEAL, and a
|
||||
#: Traktor user reads a loop as green; so the type colours are pinned by intent.
|
||||
_BY_INTENT: dict[str, int] = {
|
||||
"#4D94FF": 0x05, # cue -> light blue
|
||||
"#3DDC84": 0x16, # loop -> green
|
||||
"#FF9A3D": 0x26, # fade -> orange
|
||||
"#FFD23D": 0x20, # load -> yellow
|
||||
}
|
||||
|
||||
#: Below this saturation a colour is white/grey, which the palette cannot show.
|
||||
_GREY = 0.2
|
||||
|
||||
|
||||
def _parse(color: str) -> tuple[int, int, int] | None:
|
||||
c = (color or "").strip().lstrip("#")
|
||||
if len(c) != 6:
|
||||
return None
|
||||
try:
|
||||
return int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
|
||||
"""(palette code, RGB to store) for a generic `#RRGGBB`; (0, black) for none.
|
||||
|
||||
An exact palette RGB keeps its code; a type colour maps by intent; a
|
||||
white/grey keeps its RGB with code 0; anything else takes the swatch of the
|
||||
nearest hue, and stores THAT swatch's RGB so code and colour agree.
|
||||
"""
|
||||
rgb = _parse(color) if color else None
|
||||
if rgb is None:
|
||||
return 0, (0, 0, 0)
|
||||
for code, value in PALETTE.items():
|
||||
if value == rgb:
|
||||
return code, value
|
||||
intent = _BY_INTENT.get(f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}")
|
||||
if intent is not None:
|
||||
return intent, PALETTE[intent]
|
||||
h, _l, s = colorsys.rgb_to_hls(*(v / 255 for v in rgb))
|
||||
if s < _GREY or max(rgb) - min(rgb) < 40:
|
||||
return 0, rgb
|
||||
def hue_gap(code: int) -> float:
|
||||
ph = colorsys.rgb_to_hls(*(v / 255 for v in PALETTE[code]))[0]
|
||||
d = abs(ph - h)
|
||||
return min(d, 1 - d)
|
||||
best = min((c for c in PALETTE if c != 0x2B), key=hue_gap)
|
||||
return best, PALETTE[best]
|
||||
|
||||
|
||||
#: The swatches a user can pick, in rekordbox's own order — what
|
||||
#: `capabilities.cues.palette` offers. 15 of rekordbox's 16: the unmeasured
|
||||
#: teal-green is left out rather than offered with a guessed RGB, and 0x2B is
|
||||
#: not a swatch at all (see the module note).
|
||||
SWATCHES: list[int] = [code for code in PALETTE if code != 0x2B]
|
||||
|
||||
|
||||
def hex_for(code: int | None) -> str | None:
|
||||
"""`#RRGGBB` for a stored palette code; None for uncoloured or unknown.
|
||||
|
||||
An unknown code (the unmeasured teal-green) projects as no colour rather
|
||||
than a guessed one; it is still kept on the row, since editing a cue's
|
||||
position, type or name never rewrites its colour.
|
||||
"""
|
||||
rgb = PALETTE.get(code) if code else None
|
||||
return None if rgb is None else f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
|
||||
|
||||
|
||||
def swatch_code(color: str) -> int | None:
|
||||
"""The code of an EXACT palette colour, else None — for a user's pick, which
|
||||
must be a swatch, unlike `code_for`'s nearest-hue mapping for exports."""
|
||||
rgb = _parse(color)
|
||||
return next((code for code, value in PALETTE.items() if value == rgb), None)
|
||||
@@ -0,0 +1,432 @@
|
||||
"""The legacy rekordbox device library: `export.pdb` (DeviceSQL), read and written.
|
||||
|
||||
What Rekordbox lists as a stick's **Device Library** and what pre-OneLibrary
|
||||
players (CDJ-2000NXS2, many XDJs) read. Rekordbox writes it beside the
|
||||
OneLibrary `exportLibrary.db`; both point at the same audio, analysis files and
|
||||
artwork.
|
||||
|
||||
## The format
|
||||
|
||||
There is no public specification. The layout used here is the one Deep
|
||||
Symmetry's crate-digger documents, CONFIRMED byte for byte against a real
|
||||
rekordbox 7 device export of eight tracks (every row of every table decodes, and
|
||||
the page arithmetic below reproduces rekordbox's header fields exactly):
|
||||
|
||||
* the file is 4096-byte pages; page 0 is a header listing 20 tables, each a
|
||||
chain of pages `first -> ... -> last -> empty_candidate` (the candidate is a
|
||||
reserved page, possibly beyond the end of the file);
|
||||
* every table starts with a HEADER page that holds no rows (flags 0x64) but
|
||||
DOES hold an index: the table's first data page, and for tracks, the
|
||||
playlist tree and history an entry per data page (`page << 3 | flag`, 3 =
|
||||
has room). A first Konduktor export left these pointing nowhere and
|
||||
rekordbox 7 called the device library corrupted; rows live in DATA pages
|
||||
(flags 0x34 for tracks and the playlist tree, else 0x24);
|
||||
* a data page is a 0x28-byte header, a heap of rows (each 4-byte aligned) from
|
||||
the top, and a row index growing from the bottom in groups of 16: per group
|
||||
16 u16 heap offsets, a u16 "present" bitmask and a u16 bitmask of the last
|
||||
row written;
|
||||
* strings are DeviceSQL strings: short ASCII `((len+1)<<1)|1` + bytes, long
|
||||
ASCII `0x40` + u16 length + pad, or UTF-16LE `0x90` + u16 length + pad.
|
||||
|
||||
## Writing
|
||||
|
||||
**From a template, not from nothing** (`fixtures/rekordbox/device/`): the empty
|
||||
library rekordbox itself writes for a new stick. It carries the tables that are
|
||||
the same on every stick and cannot be derived (colours, browse columns, menus,
|
||||
the history header), and reserves a blank page after each data table's header
|
||||
page. Filling a table follows rekordbox's own allocation, read off a real
|
||||
export: the first data page is the table's reserved candidate, further pages and
|
||||
the new candidate come from the file header's next-unused counter, and any
|
||||
reserved page left inside the file stays blank.
|
||||
|
||||
Data pages are written the way a rekordbox EXPORT writes them (rows appended
|
||||
one by one): `u5` = 1, `num_rows_large` = rows - 1, and each index group's
|
||||
"last written" mask names its final row.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
PAGE = 4096
|
||||
_HEADER = 0x28
|
||||
_GROUP = 0x24 # one row-index group: 16 offsets + present + last-written
|
||||
|
||||
TRACKS, GENRES, ARTISTS, ALBUMS, LABELS, KEYS, COLORS = 0, 1, 2, 3, 4, 5, 6
|
||||
PLAYLIST_TREE, PLAYLIST_ENTRIES, ARTWORK, HISTORY = 7, 8, 13, 19
|
||||
|
||||
#: Data-page flags per table, as rekordbox writes them.
|
||||
_PAGE_FLAGS = {TRACKS: 0x34, PLAYLIST_TREE: 0x34}
|
||||
_DEFAULT_FLAGS = 0x24
|
||||
_HEADER_PAGE = 0x40 # bit set on header / non-data pages
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).resolve().parents[3] / "fixtures" / "rekordbox" / "device"
|
||||
|
||||
|
||||
# ---- strings -------------------------------------------------------------------
|
||||
|
||||
|
||||
def dsql(text: str | None) -> bytes:
|
||||
"""A DeviceSQL string."""
|
||||
text = text or ""
|
||||
try:
|
||||
raw = text.encode("ascii")
|
||||
except UnicodeEncodeError:
|
||||
wide = text.encode("utf-16-le")
|
||||
return struct.pack("<BHB", 0x90, len(wide) + 4, 0) + wide
|
||||
if len(raw) <= 126:
|
||||
return bytes([((len(raw) + 1) << 1) | 1]) + raw
|
||||
return struct.pack("<BHB", 0x40, len(raw) + 4, 0) + raw
|
||||
|
||||
|
||||
def read_dsql(buf: bytes, off: int) -> str:
|
||||
head = buf[off]
|
||||
if head & 1:
|
||||
n = (head >> 1) - 1
|
||||
return buf[off + 1:off + 1 + n].decode("ascii", "replace")
|
||||
n = struct.unpack_from("<H", buf, off + 1)[0]
|
||||
body = buf[off + 4:off + n]
|
||||
return body.decode("utf-16-le" if head == 0x90 else "ascii", "replace")
|
||||
|
||||
|
||||
def _pad4(row: bytes) -> bytes:
|
||||
return row + bytes(-len(row) % 4)
|
||||
|
||||
|
||||
# ---- rows ----------------------------------------------------------------------
|
||||
|
||||
#: The track row's fixed part, in order: 94 bytes.
|
||||
_TRACK_FIELDS = (
|
||||
("subtype", "H"), ("index_shift", "H"), ("bitmask", "I"), ("sample_rate", "I"),
|
||||
("composer_id", "I"), ("file_size", "I"), ("u2", "I"), ("u3", "H"), ("u4", "H"),
|
||||
("artwork_id", "I"), ("key_id", "I"), ("original_artist_id", "I"), ("label_id", "I"),
|
||||
("remixer_id", "I"), ("bitrate", "I"), ("track_number", "I"), ("tempo", "I"),
|
||||
("genre_id", "I"), ("album_id", "I"), ("artist_id", "I"), ("id", "I"),
|
||||
("disc_number", "H"), ("play_count", "H"), ("year", "H"), ("sample_depth", "H"),
|
||||
("duration", "H"), ("u5", "H"), ("color_id", "B"), ("rating", "B"), ("u6", "H"), ("u7", "H"),
|
||||
)
|
||||
_TRACK_FMT = "<" + "".join(f for _, f in _TRACK_FIELDS)
|
||||
_TRACK_FIXED = struct.calcsize(_TRACK_FMT) # 94
|
||||
#: The 21 string slots, in the order their offsets follow the fixed part.
|
||||
TRACK_STRINGS = (
|
||||
"isrc", "texter", "unknown_string_2", "unknown_string_3", "unknown_string_4",
|
||||
"message", "kuvo_public", "autoload_hotcues", "unknown_string_5", "unknown_string_6",
|
||||
"date_added", "release_date", "mix_name", "unknown_string_7", "analyze_path",
|
||||
"analyze_date", "comment", "title", "unknown_string_8", "filename", "file_path",
|
||||
)
|
||||
_INDEX_SHIFT_AT = 2 # tracks, artists and albums carry their slot << 5 here
|
||||
#: Tables whose header page indexes every data page (the rest only point at the
|
||||
#: first). History (19) is already indexed in the template.
|
||||
_INDEXED = (TRACKS, PLAYLIST_TREE)
|
||||
_NONE = 0x1FFF
|
||||
|
||||
|
||||
def track_row(fields: dict, strings: dict) -> bytes:
|
||||
"""A tracks-table row. `fields` fills the fixed part (missing = 0);
|
||||
`strings` the string slots (missing = empty)."""
|
||||
values = [fields.get(name, 0) for name, _ in _TRACK_FIELDS]
|
||||
fixed = struct.pack(_TRACK_FMT, *values)
|
||||
offsets, heap = [], b""
|
||||
base = _TRACK_FIXED + 2 * len(TRACK_STRINGS)
|
||||
for name in TRACK_STRINGS:
|
||||
offsets.append(base + len(heap))
|
||||
heap += dsql(strings.get(name))
|
||||
return _pad4(fixed + struct.pack(f"<{len(offsets)}H", *offsets) + heap)
|
||||
|
||||
|
||||
def id_string_row(row_id: int, text: str) -> bytes:
|
||||
"""Genres, labels and artwork: u32 id + string."""
|
||||
return _pad4(struct.pack("<I", row_id) + dsql(text))
|
||||
|
||||
|
||||
def key_row(row_id: int, name: str) -> bytes:
|
||||
"""Keys store their id twice."""
|
||||
return _pad4(struct.pack("<II", row_id, row_id) + dsql(name))
|
||||
|
||||
|
||||
def artist_row(row_id: int, name: str) -> bytes:
|
||||
"""Subtype 0x60: the name starts at a fixed offset of 10."""
|
||||
return _pad4(struct.pack("<HHIBB", 0x60, 0, row_id, 0x03, 10) + dsql(name))
|
||||
|
||||
|
||||
def album_row(row_id: int, name: str, artist_id: int = 0) -> bytes:
|
||||
"""Subtype 0x80: the name starts at 22. rekordbox's own export leaves the
|
||||
album's artist 0 even when the track has one, so the default follows it."""
|
||||
return _pad4(struct.pack("<HHIIIIBB", 0x80, 0, 0, artist_id, row_id, 0, 0x03, 22) + dsql(name))
|
||||
|
||||
|
||||
def playlist_tree_row(row_id: int, parent_id: int, sort_order: int, name: str, *, folder: bool) -> bytes:
|
||||
return _pad4(struct.pack("<IIIII", parent_id, 0, sort_order, row_id, 1 if folder else 0) + dsql(name))
|
||||
|
||||
|
||||
def playlist_entry_row(entry_index: int, track_id: int, playlist_id: int) -> bytes:
|
||||
return struct.pack("<III", entry_index, track_id, playlist_id)
|
||||
|
||||
|
||||
# ---- pages ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _index_space(n: int) -> int:
|
||||
"""Bytes the row index occupies at the bottom of a page holding `n` rows."""
|
||||
return ((n + 15) // 16) * _GROUP
|
||||
|
||||
|
||||
def _chunk(rows: list[bytes]) -> list[list[bytes]]:
|
||||
"""Greedy: as many rows per page as fit beside their index."""
|
||||
pages, cur, used = [], [], 0
|
||||
for row in rows:
|
||||
if cur and _HEADER + used + len(row) + _index_space(len(cur) + 1) > PAGE:
|
||||
pages.append(cur)
|
||||
cur, used = [], 0
|
||||
if _HEADER + len(row) + _index_space(1) > PAGE:
|
||||
raise ValueError(f"a {len(row)}-byte row cannot fit in a page")
|
||||
cur.append(row)
|
||||
used += len(row)
|
||||
if cur:
|
||||
pages.append(cur)
|
||||
return pages
|
||||
|
||||
|
||||
def _data_page(index: int, table: int, next_page: int, rows: list[bytes], sequence: int,
|
||||
*, shift_at: int | None, fill: tuple[int, int] | None = None) -> bytes:
|
||||
page = bytearray(PAGE)
|
||||
heap = bytearray()
|
||||
offsets = []
|
||||
for slot, row in enumerate(rows):
|
||||
row = bytearray(row)
|
||||
if shift_at is not None:
|
||||
struct.pack_into("<H", row, shift_at, slot << 5)
|
||||
offsets.append(len(heap))
|
||||
heap += row
|
||||
n = len(rows)
|
||||
groups = (n + 15) // 16
|
||||
page[_HEADER:_HEADER + len(heap)] = heap
|
||||
for g in range(groups):
|
||||
base = PAGE - g * _GROUP
|
||||
k = min(16, n - 16 * g)
|
||||
struct.pack_into("<H", page, base - 4, (1 << k) - 1) # present
|
||||
struct.pack_into("<H", page, base - 2, 1 << (k - 1)) # last written
|
||||
for r in range(k):
|
||||
struct.pack_into("<H", page, base - 6 - 2 * r, offsets[16 * g + r])
|
||||
used = len(heap)
|
||||
free = PAGE - _HEADER - used - (2 * n + 4 * groups)
|
||||
struct.pack_into("<6I", page, 0, 0, index, table, next_page, sequence, 0)
|
||||
page[0x18] = n & 0xFF
|
||||
page[0x19] = ((n >> 8) & 0x1F) | ((n & 0x07) << 5)
|
||||
page[0x1A] = (n >> 3) & 0xFF
|
||||
page[0x1B] = _PAGE_FLAGS.get(table, _DEFAULT_FLAGS)
|
||||
u5, nrl = fill if fill is not None else (1, n - 1)
|
||||
struct.pack_into("<6H", page, 0x1C, free, used, u5, nrl, 0, 0)
|
||||
return bytes(page)
|
||||
|
||||
|
||||
# ---- the writer ----------------------------------------------------------------
|
||||
|
||||
|
||||
class PdbWriter:
|
||||
"""Fills an empty rekordbox device library (the template) with rows."""
|
||||
|
||||
def __init__(self, template: bytes):
|
||||
self.buf = bytearray(template)
|
||||
self.pages: dict[int, bytes] = {}
|
||||
n_tables = struct.unpack_from("<I", self.buf, 8)[0]
|
||||
self.next_unused = struct.unpack_from("<I", self.buf, 12)[0]
|
||||
self.sequence = struct.unpack_from("<I", self.buf, 20)[0]
|
||||
self.tables = {}
|
||||
self.pages_with_room = 0
|
||||
for i in range(n_tables):
|
||||
t, empty, first, last = struct.unpack_from("<4I", self.buf, 28 + 16 * i)
|
||||
self.tables[t] = [i, empty, first, last]
|
||||
|
||||
def _alloc(self) -> int:
|
||||
page = self.next_unused
|
||||
self.next_unused += 1
|
||||
return page
|
||||
|
||||
def fill(self, table: int, rows: list[bytes]) -> None:
|
||||
"""Write `rows` into `table`, which must still be empty (header page only)."""
|
||||
if not rows:
|
||||
return
|
||||
slot, empty, first, last = self.tables[table]
|
||||
if first != last:
|
||||
raise ValueError(f"table {table} already has data pages")
|
||||
chunks = _chunk(rows)
|
||||
indices = [empty] + [self._alloc() for _ in chunks[1:]]
|
||||
candidate = self._alloc()
|
||||
shift_at = _INDEX_SHIFT_AT if table in (TRACKS, ARTISTS, ALBUMS) else None
|
||||
indexed = table in _INDEXED
|
||||
for i, chunk in enumerate(chunks):
|
||||
nxt = indices[i + 1] if i + 1 < len(indices) else candidate
|
||||
last_page = i + 1 == len(chunks)
|
||||
# Indexed tables mark a full page 0x1FFF/0x1FFF and a page with room
|
||||
# rows+1 / 0 — as a real export's tracks and playlist pages do.
|
||||
fill = None
|
||||
if indexed:
|
||||
fill = (len(chunk) + 1, 0) if last_page else (_NONE, _NONE)
|
||||
self.sequence += 1
|
||||
self.pages[indices[i]] = _data_page(indices[i], table, nxt, chunk, self.sequence,
|
||||
shift_at=shift_at, fill=fill)
|
||||
self._index(first, indices, indexed=indexed)
|
||||
self.tables[table] = [slot, candidate, first, indices[-1]]
|
||||
|
||||
def _index(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None:
|
||||
"""Point the table's HEADER page at its data.
|
||||
|
||||
A header page is not empty: past its 0x28-byte header it holds an index —
|
||||
its own number, the FIRST DATA PAGE, 0x03FFFFFF, 0, a u16 entry count,
|
||||
0x1FFF, then entries `page << 3 | flag` padded with 0x1FFFFFF8. Every
|
||||
table with data points at its first data page (left at 0x03FFFFFF,
|
||||
rekordbox calls the library corrupted); the indexed tables (tracks, the
|
||||
playlist tree, history) also list every data page — flag 3 for a page
|
||||
with room, 0 for a full one — and the header's u7 is that count, u5 the
|
||||
number of pages with room and num_rows_large the first of them.
|
||||
"""
|
||||
o = header_page * PAGE
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 4, data_pages[0])
|
||||
if not indexed:
|
||||
return
|
||||
flags = [3 if i + 1 == len(data_pages) else 0 for i in range(len(data_pages))]
|
||||
struct.pack_into("<HH", self.buf, o + _HEADER + 16, len(data_pages), 0x1FFF)
|
||||
for k, (page, flag) in enumerate(zip(data_pages, flags)):
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, (page << 3) | flag)
|
||||
room = [k for k, flag in enumerate(flags) if flag == 3]
|
||||
struct.pack_into("<HH", self.buf, o + 0x20, len(room) or _NONE, room[0] if room else _NONE)
|
||||
struct.pack_into("<H", self.buf, o + 0x26, len(data_pages))
|
||||
self.pages_with_room += len(room)
|
||||
|
||||
def stamp_track_count(self, n: int) -> None:
|
||||
"""The history header row counts the library's tracks (and flags that
|
||||
it has any): 8 on a real 8-track export, 0 in the empty template."""
|
||||
_, _, first, last = self.tables[HISTORY]
|
||||
for _header, row in _rows(bytes(self.buf), first, last):
|
||||
if row is not None:
|
||||
self.buf[row + 3] = 1 if n else 0
|
||||
struct.pack_into("<I", self.buf, row + 4, n)
|
||||
break
|
||||
if n:
|
||||
# A library with tracks also INDEXES its history page — entry
|
||||
# `page << 3 | 0`, count 1, u7 1 — which the empty template does not.
|
||||
o = first * PAGE
|
||||
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 1, 0x1FFF)
|
||||
struct.pack_into("<I", self.buf, o + _HEADER + 20, last << 3)
|
||||
struct.pack_into("<H", self.buf, o + 0x26, 1)
|
||||
|
||||
def stamp_history_date(self, when: date) -> None:
|
||||
"""The history header row records the library's creation date."""
|
||||
_, _, first, last = self.tables[HISTORY]
|
||||
o = last * PAGE
|
||||
page = self.buf[o:o + PAGE]
|
||||
m = re.search(rb"\d{4}-\d{2}-\d{2}", page[_HEADER:])
|
||||
if m:
|
||||
at = o + _HEADER + m.start()
|
||||
self.buf[at:at + 10] = when.isoformat().encode("ascii")
|
||||
|
||||
def render(self) -> bytes:
|
||||
for t, (slot, empty, first, last) in self.tables.items():
|
||||
struct.pack_into("<4I", self.buf, 28 + 16 * slot, t, empty, first, last)
|
||||
struct.pack_into("<I", self.buf, 12, self.next_unused)
|
||||
# 1 in the empty template, 4 on a real export whose index lists three
|
||||
# pages with room: 1 + that count fits both. The least certain field here.
|
||||
struct.pack_into("<I", self.buf, 16, 1 + self.pages_with_room)
|
||||
struct.pack_into("<I", self.buf, 20, self.sequence + 1)
|
||||
top = max([len(self.buf) // PAGE - 1, *self.pages])
|
||||
out = bytearray(self.buf) + bytes((top + 1) * PAGE - len(self.buf))
|
||||
for index, page in self.pages.items():
|
||||
out[index * PAGE:(index + 1) * PAGE] = page
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def template(name: str = "export.pdb") -> bytes:
|
||||
return (TEMPLATE_DIR / name).read_bytes()
|
||||
|
||||
|
||||
# ---- the reader ----------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class Library:
|
||||
"""What a device library holds, decoded — for tests and diagnostics."""
|
||||
|
||||
tracks: list[dict] = field(default_factory=list)
|
||||
genres: dict[int, str] = field(default_factory=dict)
|
||||
artists: dict[int, str] = field(default_factory=dict)
|
||||
albums: dict[int, str] = field(default_factory=dict)
|
||||
labels: dict[int, str] = field(default_factory=dict)
|
||||
keys: dict[int, str] = field(default_factory=dict)
|
||||
artwork: dict[int, str] = field(default_factory=dict)
|
||||
playlists: list[dict] = field(default_factory=list)
|
||||
entries: list[tuple[int, int, int]] = field(default_factory=list)
|
||||
pages: dict[int, list[dict]] = field(default_factory=dict) # table -> page headers
|
||||
|
||||
|
||||
def _rows(buf: bytes, first: int, last: int):
|
||||
"""(page header dict, row offset) for every present row of a table."""
|
||||
p, seen = first, 0
|
||||
while True:
|
||||
o = p * PAGE
|
||||
if o + PAGE > len(buf):
|
||||
return
|
||||
flags = buf[o + 0x1B]
|
||||
n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3)
|
||||
header = {"index": p, "flags": flags, "rows": n,
|
||||
"next": struct.unpack_from("<I", buf, o + 12)[0],
|
||||
"free": struct.unpack_from("<H", buf, o + 0x1C)[0],
|
||||
"used": struct.unpack_from("<H", buf, o + 0x1E)[0]}
|
||||
yield header, None
|
||||
if not flags & _HEADER_PAGE:
|
||||
for g in range((n + 15) // 16):
|
||||
base = o + PAGE - g * _GROUP
|
||||
present = struct.unpack_from("<H", buf, base - 4)[0]
|
||||
for r in range(16):
|
||||
if present & (1 << r):
|
||||
yield header, o + _HEADER + struct.unpack_from("<H", buf, base - 6 - 2 * r)[0]
|
||||
if p == last or seen > 10000:
|
||||
return
|
||||
p, seen = header["next"], seen + 1
|
||||
|
||||
|
||||
def read(buf: bytes) -> Library:
|
||||
lib = Library()
|
||||
n_tables = struct.unpack_from("<I", buf, 8)[0]
|
||||
for i in range(n_tables):
|
||||
t, _empty, first, last = struct.unpack_from("<4I", buf, 28 + 16 * i)
|
||||
for header, row in _rows(buf, first, last):
|
||||
if row is None:
|
||||
lib.pages.setdefault(t, []).append(header)
|
||||
continue
|
||||
if t == TRACKS:
|
||||
values = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, buf, row)))
|
||||
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", buf, row + _TRACK_FIXED)
|
||||
values.update({name: read_dsql(buf, row + o) for name, o in zip(TRACK_STRINGS, offs)})
|
||||
lib.tracks.append(values)
|
||||
elif t in (GENRES, LABELS, ARTWORK):
|
||||
target = {GENRES: lib.genres, LABELS: lib.labels, ARTWORK: lib.artwork}[t]
|
||||
target[struct.unpack_from("<I", buf, row)[0]] = read_dsql(buf, row + 4)
|
||||
elif t == KEYS:
|
||||
lib.keys[struct.unpack_from("<I", buf, row)[0]] = read_dsql(buf, row + 8)
|
||||
elif t == ARTISTS:
|
||||
sub, _shift, rid, _b, ofs = struct.unpack_from("<HHIBB", buf, row)
|
||||
if sub == 0x64:
|
||||
ofs = struct.unpack_from("<H", buf, row + 10)[0]
|
||||
lib.artists[rid] = read_dsql(buf, row + ofs)
|
||||
elif t == ALBUMS:
|
||||
sub, _shift, _u, artist, rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", buf, row)
|
||||
lib.albums[rid] = read_dsql(buf, row + ofs)
|
||||
elif t == PLAYLIST_TREE:
|
||||
parent, _u, sort, rid, folder = struct.unpack_from("<5I", buf, row)
|
||||
lib.playlists.append({"id": rid, "parent": parent, "sort": sort,
|
||||
"folder": bool(folder), "name": read_dsql(buf, row + 20)})
|
||||
elif t == PLAYLIST_ENTRIES:
|
||||
lib.entries.append(struct.unpack_from("<3I", buf, row))
|
||||
return lib
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ALBUMS", "ARTISTS", "ARTWORK", "GENRES", "KEYS", "LABELS", "Library", "PAGE",
|
||||
"PLAYLIST_ENTRIES", "PLAYLIST_TREE", "PdbWriter", "TRACKS", "TRACK_STRINGS",
|
||||
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
|
||||
"playlist_tree_row", "read", "read_dsql", "template", "track_row",
|
||||
]
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
import re
|
||||
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid
|
||||
from . import beatgrid, palette, timebase
|
||||
from .cue_types import cue_type, role_and_slot
|
||||
|
||||
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
|
||||
@@ -97,10 +97,10 @@ def _name_of(related) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def to_track(row, cue_kinds=()) -> Track:
|
||||
def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
|
||||
"""Project one ``DjmdContent`` row.
|
||||
|
||||
`cue_kinds` is this track's ``(Kind, OutMsec)`` pairs from the store's single
|
||||
`cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single
|
||||
query — passed in rather than read off the row, which would be a per-track
|
||||
round trip. "Is this a hot cue, and on which pad?" is `role_and_slot`, the
|
||||
same definition `to_track_cues` uses, so the table's count and dots agree
|
||||
@@ -118,12 +118,11 @@ def to_track(row, cue_kinds=()) -> Track:
|
||||
BPM are precisely the 22 with no grid.
|
||||
"""
|
||||
chips: list[HotcueChip] = []
|
||||
for kind, out_msec in cue_kinds:
|
||||
for kind, out_msec, color_code in cue_kinds:
|
||||
role, slot = role_and_slot(kind)
|
||||
if role == "hotcue" and slot is not None:
|
||||
# Rekordbox's colour is a palette index nobody has decoded yet (see
|
||||
# `_cue_color`), so no colour is claimed and the UI uses the type's.
|
||||
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec), color=None))
|
||||
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec),
|
||||
color=palette.hex_for(color_code)))
|
||||
chips.sort(key=lambda chip: chip.slot)
|
||||
key_name = _name_of(getattr(row, "Key", None))
|
||||
wheel, mode = parse_key(key_name)
|
||||
@@ -146,7 +145,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)),
|
||||
@@ -156,14 +156,17 @@ def to_track(row, cue_kinds=()) -> Track:
|
||||
hotcues=chips,
|
||||
grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0,
|
||||
grid_locked=False, # Rekordbox has no per-track grid lock
|
||||
media_kind="audio",
|
||||
# What the FILE is (`store.is_stem`): Rekordbox itself plays a stem
|
||||
# file's mix, but Konduktor's deck plays its stems, and the Type column
|
||||
# must not disagree with the deck.
|
||||
media_kind="stem" if stem else "audio",
|
||||
)
|
||||
|
||||
|
||||
def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) -> TrackCues:
|
||||
def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0) -> TrackCues:
|
||||
"""Project a track's cues and beatgrid.
|
||||
|
||||
`grid` is the per-beat ``(times, bpms)`` 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 +180,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:
|
||||
@@ -195,7 +197,9 @@ def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None)
|
||||
name=(getattr(c, "Comment", None) or None),
|
||||
type=kind,
|
||||
role=role,
|
||||
start=in_msec / 1000.0,
|
||||
# rekordbox's clock -> the decoded audio's (see `timebase`); the
|
||||
# grid arrives already converted by the store.
|
||||
start=timebase.from_pioneer(in_msec / 1000.0, time_offset),
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_cue_color(c),
|
||||
@@ -208,11 +212,6 @@ def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None)
|
||||
|
||||
|
||||
def _cue_color(row) -> str | None:
|
||||
"""Rekordbox stores a PALETTE INDEX, not an RGB value.
|
||||
|
||||
The generic model carries ``#RRGGBB``, and the built-in palette that index
|
||||
refers to is not yet known, so no colour is claimed rather than a wrong one
|
||||
being invented. `capabilities.cues.color` already says "palette", so the UI
|
||||
knows not to offer a free colour picker.
|
||||
"""
|
||||
return None
|
||||
"""Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value;
|
||||
`Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
|
||||
return palette.hex_for(getattr(row, "ColorTableIndex", None))
|
||||
@@ -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
|
||||
|
||||
@@ -36,14 +37,70 @@ from sqlalchemy import func, select, text
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
|
||||
from ...core.adapter import (
|
||||
InvalidCommand,
|
||||
LibraryNotSupported,
|
||||
NotFound,
|
||||
SaveOutcome,
|
||||
Unsupported,
|
||||
)
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import PathMapping
|
||||
from . import timebase
|
||||
from .cue_types import beat_loop_size, kind_for, role_and_slot
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
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/"
|
||||
|
||||
|
||||
@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,11 +116,17 @@ 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.
|
||||
self._pending_grids: dict[str, tuple[list, list, list]] = {}
|
||||
# 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 ------------------------------------------------------------
|
||||
@@ -77,9 +140,30 @@ class RekordboxStore:
|
||||
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
|
||||
raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex
|
||||
self._grid_cache.clear()
|
||||
self._stem_cache: dict[str, bool] = {}
|
||||
self._content_cache: list | None = None
|
||||
self._by_id: dict[str, object] | None = None
|
||||
|
||||
def discard(self) -> None:
|
||||
"""Drop every unsaved edit and re-open the library as it is on disk.
|
||||
|
||||
Three things hold edits here, and all three must go: the SQLAlchemy
|
||||
session (rolled back, then closed with its engine — `_load()` alone
|
||||
would open a SECOND connection and leak the first), the buffered grid
|
||||
writes (which the next save would otherwise still write to ANLZ files),
|
||||
and the journal (else the library keeps reporting unsaved changes).
|
||||
"""
|
||||
try:
|
||||
self._db.session.rollback()
|
||||
except Exception: # noqa: BLE001 — discarding must not fail halfway
|
||||
pass
|
||||
self.close()
|
||||
self._journal = EditJournal()
|
||||
self._pending_grids.clear()
|
||||
self._pending_file_removals.clear()
|
||||
self._pending_new_files.clear()
|
||||
self._load()
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the session AND the pooled connection.
|
||||
|
||||
@@ -171,8 +255,9 @@ class RekordboxStore:
|
||||
raise NotFound(f"No track {track_id!r}")
|
||||
return row
|
||||
|
||||
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None]]]:
|
||||
"""``{track_id: [(Kind, OutMsec), ...]}`` for every live cue, in one query.
|
||||
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None, int | None]]]:
|
||||
"""``{track_id: [(Kind, OutMsec, ColorTableIndex), ...]}`` for every live
|
||||
cue, in one query.
|
||||
|
||||
Just enough per cue for the library table's count and hotcue dots,
|
||||
without a per-track round trip. What a ``Kind`` means is decided in the
|
||||
@@ -181,12 +266,13 @@ class RekordboxStore:
|
||||
"""
|
||||
t = self._tables
|
||||
rows = self._db.session.execute(
|
||||
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec)
|
||||
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec,
|
||||
t.DjmdCue.ColorTableIndex)
|
||||
.where(t.DjmdCue.rb_local_deleted == 0)
|
||||
).all()
|
||||
out: dict[str, list[tuple[int | None, int | None]]] = {}
|
||||
for content_id, kind, out_msec in rows:
|
||||
out.setdefault(str(content_id), []).append((kind, out_msec))
|
||||
out: dict[str, list[tuple[int | None, int | None, int | None]]] = {}
|
||||
for content_id, kind, out_msec, color_code in rows:
|
||||
out.setdefault(str(content_id), []).append((kind, out_msec, color_code))
|
||||
return out
|
||||
|
||||
def cues(self, track_id: str) -> list:
|
||||
@@ -234,8 +320,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.
|
||||
@@ -244,6 +332,10 @@ class RekordboxStore:
|
||||
if key in self._grid_cache:
|
||||
return self._grid_cache[key]
|
||||
result = self._read_anlz_grid(key)
|
||||
if result is not None:
|
||||
off = self.time_offset(key)
|
||||
times, bpms, beats = result
|
||||
result = ([timebase.from_pioneer(t, off) for t in times], bpms, beats)
|
||||
self._grid_cache[key] = result
|
||||
return result
|
||||
|
||||
@@ -269,7 +361,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
|
||||
@@ -281,6 +374,20 @@ class RekordboxStore:
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._mapping = mapping or PathMapping()
|
||||
|
||||
def is_stem(self, track_id: str) -> bool:
|
||||
"""Whether the track's FILE is a native-instruments stem file — read
|
||||
from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and
|
||||
cached per path, since the projection asks for every track at open."""
|
||||
from ...core.stem_file import is_stem_file
|
||||
|
||||
path = self.audio_path(track_id)
|
||||
if path is None:
|
||||
return False
|
||||
key = str(path)
|
||||
if key not in self._stem_cache:
|
||||
self._stem_cache[key] = is_stem_file(path)
|
||||
return self._stem_cache[key]
|
||||
|
||||
@property
|
||||
def path_mapping(self) -> PathMapping:
|
||||
return self._mapping
|
||||
@@ -292,6 +399,14 @@ class RekordboxStore:
|
||||
return None
|
||||
return self._mapping.apply(Path(str(folder)))
|
||||
|
||||
def time_offset(self, track_id: str) -> float:
|
||||
"""Seconds rekordbox's clock runs behind the decoded audio for this
|
||||
track — per FILE (an MP3's header, an M4A's edit list; 0 lossless).
|
||||
Added on every position written, subtracted on every position read —
|
||||
see `timebase`. Read from the file as it resolves here (path mapping
|
||||
applied); a file that is offline falls back to its format's default."""
|
||||
return timebase.offset(self.audio_path(track_id))
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
"""The art embedded in the audio file, else Rekordbox's own copy.
|
||||
|
||||
@@ -463,13 +578,274 @@ 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
|
||||
# every file under `share/` (Demo Track 2, 2026-10-01): Rekordbox DELETES
|
||||
# the rows — it does not set `rb_local_deleted` — from these tables, leaves
|
||||
# the playlist row itself alone, and deletes the files `contentFile` lists
|
||||
# (there, the four ANLZ files) together with their emptied folders. That
|
||||
# track had no artwork, and an Artwork folder holds `_m`/`_s` sizes that
|
||||
# `contentFile` does not list, so artwork is left in place: an orphaned
|
||||
# image is harmless, a guessed deletion is not.
|
||||
_REMOVED_WITH_TRACK = ("DjmdCue", "ContentCue", "ContentFile", "DjmdMixerParam",
|
||||
"DjmdSongPlaylist")
|
||||
# Also keyed by ContentID, but empty in the measured library, so what
|
||||
# Rekordbox does with them is unknown. A track that appears in one is
|
||||
# refused rather than guessed at.
|
||||
_UNMEASURED_LINKS = {
|
||||
"djmdSongHistory": "a History list",
|
||||
"djmdSongSampler": "the Sampler",
|
||||
"djmdSongTagList": "the Tag List",
|
||||
"djmdSongMyTag": "My Tag",
|
||||
"djmdSongHotCueBanklist": "a Hot Cue Bank List",
|
||||
"djmdSongRelatedTracks": "Related Tracks",
|
||||
"djmdSongRequestList": "a request list",
|
||||
"djmdActiveCensor": "an Active Censor",
|
||||
"contentActiveCensor": "an Active Censor",
|
||||
"djmdCloudExportSongPlaylist": "a cloud export",
|
||||
}
|
||||
|
||||
def _unmeasured_links(self, ids: list[str]) -> list[tuple[str, str]]:
|
||||
"""``(track_id, where)`` for each track named by an unmeasured table."""
|
||||
params = {f"i{n}": tid for n, tid in enumerate(ids)}
|
||||
marks = ", ".join(f":{k}" for k in params)
|
||||
found: list[tuple[str, str]] = []
|
||||
for table, where in self._UNMEASURED_LINKS.items():
|
||||
try:
|
||||
rows = self._db.session.execute(
|
||||
text(f'SELECT DISTINCT ContentID FROM "{table}" '
|
||||
f"WHERE ContentID IN ({marks})"), params
|
||||
).all()
|
||||
except Exception: # noqa: BLE001 — table absent in this schema version
|
||||
continue
|
||||
found += [(str(r[0]), where) for r in rows]
|
||||
return found
|
||||
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
"""Remove tracks from the library and every playlist; return how many.
|
||||
|
||||
Validated as a whole first, so a refused batch changes nothing. The
|
||||
audio files are never touched; the analysis files go at save().
|
||||
"""
|
||||
t = self._tables
|
||||
self.iter_content()
|
||||
assert self._by_id is not None
|
||||
ids = [str(tid) for tid in dict.fromkeys(track_ids) if str(tid) in self._by_id]
|
||||
if not ids:
|
||||
return 0
|
||||
blocked = self._unmeasured_links(ids)
|
||||
if blocked:
|
||||
tid, where = blocked[0]
|
||||
title = self._by_id[tid].Title or tid
|
||||
more = f" (and {len(blocked) - 1} more)" if len(blocked) > 1 else ""
|
||||
raise Unsupported(
|
||||
f"“{title}” is in {where} in Rekordbox{more}, and Konduktor does not "
|
||||
"yet know how Rekordbox removes a track from there. Remove it in "
|
||||
"Rekordbox instead — nothing was changed."
|
||||
)
|
||||
|
||||
playlists: set[str] = set()
|
||||
for tid in ids:
|
||||
for name in self._REMOVED_WITH_TRACK:
|
||||
table = getattr(t, name)
|
||||
for row in self._db.session.query(table).filter(table.ContentID == tid):
|
||||
if name == "ContentFile" and str(row.Path or "").startswith(_ANLZ_ROOT):
|
||||
self._pending_file_removals.add(str(row.Path))
|
||||
elif name == "DjmdSongPlaylist":
|
||||
playlists.add(str(row.PlaylistID))
|
||||
self._db.delete(row)
|
||||
self._db.delete(self._by_id[tid])
|
||||
self._pending_grids.pop(tid, None)
|
||||
self._grid_cache.pop(tid, None)
|
||||
self._journal.record("track", "remove", tid)
|
||||
self._db.flush()
|
||||
for playlist_id in playlists:
|
||||
self._renumber(playlist_id)
|
||||
self._content_cache = None
|
||||
self._by_id = None
|
||||
return len(ids)
|
||||
|
||||
def _renumber(self, playlist_id: str) -> None:
|
||||
"""Close the gaps removed entries left in a playlist's `TrackNo`s, as
|
||||
`pyrekordbox.remove_from_playlist` does — one 'move' for the registry,
|
||||
not an update per row."""
|
||||
t = self._tables
|
||||
moved = []
|
||||
now = datetime.now()
|
||||
rows = (
|
||||
self._db.session.query(t.DjmdSongPlaylist)
|
||||
.filter(t.DjmdSongPlaylist.PlaylistID == playlist_id)
|
||||
.order_by(t.DjmdSongPlaylist.TrackNo)
|
||||
)
|
||||
with self._db.registry.disabled():
|
||||
for n, row in enumerate(rows, start=1):
|
||||
if row.TrackNo != n:
|
||||
row.TrackNo = n
|
||||
row.updated_at = now
|
||||
moved.append(row)
|
||||
if moved:
|
||||
self._db.registry.on_move(moved)
|
||||
|
||||
def _delete_removed_files(self) -> None:
|
||||
"""Delete removed tracks' analysis/artwork files, then their emptied
|
||||
folders. Called after the commit; a file another track still lists is
|
||||
kept, and a failure only leaves an orphan behind, so it is logged."""
|
||||
t = self._tables
|
||||
share = (self.path.parent / "share").resolve()
|
||||
still_listed = {str(p) for (p,) in self._db.session.query(t.ContentFile.Path)}
|
||||
for rel in sorted(self._pending_file_removals - still_listed):
|
||||
parts = Path(rel.lstrip("/\\")).parts
|
||||
path = (share / Path(*parts)).resolve()
|
||||
# Folders below e.g. `PIONEER/USBANLZ` are the track's own; that
|
||||
# level and above are Rekordbox's and stay even when emptied.
|
||||
keep = (share / Path(*parts[:2])).resolve()
|
||||
if len(parts) < 3 or keep not in path.parents:
|
||||
continue
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
folder = path.parent
|
||||
while folder != keep and not any(folder.iterdir()):
|
||||
folder.rmdir()
|
||||
folder = folder.parent
|
||||
except OSError as ex:
|
||||
log.warning("Could not delete %s: %s", path, ex)
|
||||
self._pending_file_removals.clear()
|
||||
|
||||
# ---- save --------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
@@ -492,9 +868,20 @@ 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
|
||||
# scratch — but the grid cache is keyed by track and survives a save.
|
||||
@@ -524,10 +911,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 +924,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 +973,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
|
||||
@@ -614,21 +998,62 @@ class RekordboxStore:
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
color_code: int | None = None,
|
||||
) -> None:
|
||||
"""Create or replace the cue in `slot`. A loop is a cue with a length."""
|
||||
if start_sec < 0:
|
||||
raise InvalidCommand("A cue cannot be before the start of the track")
|
||||
"""Create or replace the cue in `slot`. A loop is a cue with a length.
|
||||
|
||||
`color_code` is a rekordbox palette code (`palette.PALETTE`). None KEEPS
|
||||
the colour of the cue already in the slot — the colour belongs to the
|
||||
pad, so a rename, a type change or an Auto Hotcues Replace leaves it as
|
||||
the user set it — and a new cue is uncoloured. Only `set_cue_color`
|
||||
clears one.
|
||||
"""
|
||||
if int(slot) < 0:
|
||||
raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}")
|
||||
row = self.content(track_id)
|
||||
in_ms = int(round(start_sec * 1000))
|
||||
is_loop = cue_type == "loop" and length_sec > 0
|
||||
out_ms = int(round((start_sec + length_sec) * 1000)) if is_loop else -1
|
||||
|
||||
kind = kind_for("hotcue", slot)
|
||||
existing = self._cue_row(track_id, slot)
|
||||
op = "add" if existing is None else "modify"
|
||||
cue = existing
|
||||
if color_code is None and existing is not None:
|
||||
color_code = existing.ColorTableIndex or None
|
||||
self._write_cue(
|
||||
track_id, existing, kind=kind_for("hotcue", slot), start_sec=start_sec,
|
||||
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
|
||||
)
|
||||
self._journal.record("cue", "add" if existing is None else "modify", track_id, f"slot:{slot}")
|
||||
|
||||
def add_memory_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
start_sec: float,
|
||||
cue_type: str = "cue",
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
color_code: int | None = None,
|
||||
) -> None:
|
||||
"""Add a MEMORY cue (`Kind` 0) — for the exporter building a new library.
|
||||
|
||||
The adapter never calls this: editing memory cues in a user's library
|
||||
stays refused under the two-platform promotion rule. A new export is not
|
||||
an edit, and dropping the source's memory cues would lose prep.
|
||||
"""
|
||||
self._write_cue(
|
||||
track_id, None, kind=kind_for("memory", None), start_sec=start_sec,
|
||||
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
|
||||
)
|
||||
self._journal.record("cue", "add", track_id, "memory")
|
||||
|
||||
def _write_cue(self, track_id: str, cue, *, kind: int, start_sec: float, cue_type: str,
|
||||
length_sec: float, name: str | None, color_code: int | None) -> None:
|
||||
"""Fill one `djmdCue` row (a new one when `cue` is None) and resync the
|
||||
`contentCue` mirror — the single definition of a cue row's fields."""
|
||||
if start_sec < 0:
|
||||
raise InvalidCommand("A cue cannot be before the start of the track")
|
||||
row = self.content(track_id)
|
||||
off = self.time_offset(track_id)
|
||||
in_ms = int(round(timebase.to_pioneer(start_sec, off) * 1000))
|
||||
is_loop = cue_type == "loop" and length_sec > 0
|
||||
out_ms = (int(round(timebase.to_pioneer(start_sec + length_sec, off) * 1000))
|
||||
if is_loop else -1)
|
||||
|
||||
if cue is None:
|
||||
t = self._tables
|
||||
cue = t.DjmdCue.create(
|
||||
@@ -660,25 +1085,50 @@ class RekordboxStore:
|
||||
cue.BeatLoopSize = beat_loop_size(beats) if beats else None
|
||||
cue.ActiveLoop = 0
|
||||
cue.CueMicrosec = 0
|
||||
cue.Color = 255
|
||||
cue.ColorTableIndex = 0
|
||||
else:
|
||||
cue.BeatLoopSize = None
|
||||
cue.ActiveLoop = None
|
||||
cue.CueMicrosec = None
|
||||
cue.Color = -1
|
||||
cue.ColorTableIndex = None
|
||||
self._apply_color(cue, color_code, is_loop)
|
||||
cue.Comment = name or None
|
||||
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
self._journal.record("cue", op, track_id, f"slot:{slot}")
|
||||
|
||||
@staticmethod
|
||||
def _apply_color(cue, color_code: int | None, is_loop: bool) -> None:
|
||||
"""A row's two colour columns — the one definition of both conventions."""
|
||||
if color_code:
|
||||
# A palette-coloured cue, as the real library stores one: the code in
|
||||
# ColorTableIndex (22 = green), Color -1. Coloured loops store the
|
||||
# same; verified in Rekordbox 7 through the master.db export.
|
||||
cue.ColorTableIndex = int(color_code)
|
||||
cue.Color = -1
|
||||
elif is_loop:
|
||||
# What Rekordbox writes on the loops and auto-cues it creates.
|
||||
cue.Color = 255
|
||||
cue.ColorTableIndex = 0
|
||||
else:
|
||||
cue.Color = -1
|
||||
cue.ColorTableIndex = None
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
|
||||
"""Recolour the cue in `slot`; None makes it uncoloured. Touches only the
|
||||
colour columns, so the position does not take a time-base round trip."""
|
||||
cue = self._cue_row(track_id, slot)
|
||||
if cue is None:
|
||||
raise NotFound(f"No cue in slot {slot}")
|
||||
self._apply_color(cue, color_code, (cue.OutMsec or 0) > 0)
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
self._journal.record("cue", "modify", track_id, f"slot:{slot}")
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None:
|
||||
cue = self._cue_row(track_id, slot)
|
||||
if cue is None:
|
||||
raise NotFound(f"No cue in slot {slot}")
|
||||
start = (cue.InMsec or 0) / 1000.0
|
||||
# Back to the decoded time base: set_cue re-applies the offset.
|
||||
start = timebase.from_pioneer((cue.InMsec or 0) / 1000.0, self.time_offset(track_id))
|
||||
length = 0.0
|
||||
if cue_type == "loop":
|
||||
if cue.OutMsec and cue.OutMsec > 0:
|
||||
@@ -800,8 +1250,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 +1278,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 <TEMPO> does —
|
||||
# Rekordbox will not do it for us.
|
||||
row = self.content(track_id)
|
||||
@@ -901,5 +1350,7 @@ class RekordboxStore:
|
||||
path = self.path.parent / "share" / str(rel).lstrip("/\\")
|
||||
if not path.is_file():
|
||||
raise InvalidCommand(f"Analysis file is missing: {path}")
|
||||
grid_math.write_pqtz(path, beat_nums, bpms, times)
|
||||
off = self.time_offset(track_id)
|
||||
grid_math.write_pqtz(path, beat_nums, bpms,
|
||||
[timebase.to_pioneer(t, off) for t in times])
|
||||
self._pending_grids.clear()
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Pioneer's clock vs the decoded audio's — one rule, used at every boundary.
|
||||
|
||||
**rekordbox's time 0 is not always the decoded audio's time 0**, and by how much
|
||||
depends on the FILE, not just its format. rekordbox does not trim the start
|
||||
padding a gapless decoder removes, so every position it stores — beats, cues,
|
||||
loops — sits LATER than the same moment in the decoded audio by exactly that
|
||||
padding:
|
||||
|
||||
* **MP3 with a Xing/Info header**: the header's encoder delay + 529 decoder
|
||||
delay — 1105 samples (~25 ms at 44.1 kHz) for LAME's usual 576. rekordbox
|
||||
SKIPS the header frame (Traktor does not — see `adapters/traktor/timebase.py`),
|
||||
it just does not trim.
|
||||
* **MP3 without a header**: 0. No decoder knows the delay, so none trims it.
|
||||
* **AAC / M4A** (incl. a Traktor `.stem.m4a`): the edit list's priming, which
|
||||
rekordbox ignores — 1024 samples from FFmpeg's encoder, 2112 from Apple's.
|
||||
* **Lossless**: 0.
|
||||
|
||||
Measured 2026-09-30 in rekordbox 7 with kit 4 (see the stem-conversion discussion
|
||||
log): blinded hotcues Konduktor wrote on a synthetic kick landed on it only at
|
||||
these offsets, hot cues placed by hand read back at them to rekordbox's 1 ms
|
||||
resolution, and rekordbox's own grids agree. It replaced a fixed 1105 samples
|
||||
for every lossy file, fitted to a library of MP3s that all had headers and
|
||||
FFmpeg-encoded M4As — right for those, 25 ms wrong on a header-less MP3 and
|
||||
22 ms wrong on Apple-encoded AAC.
|
||||
|
||||
Derived, not measured: an MP3 header whose delay field a decoder does not trust
|
||||
(no LAME/Lavf/Lavc tag, or VBRI) — nothing is trimmed, so 0.
|
||||
|
||||
A file that cannot be READ (offline, or a path that does not resolve) falls back
|
||||
to the old 1105 samples for a lossy suffix: the overwhelmingly common case, and
|
||||
what every position written before this rule assumed.
|
||||
|
||||
The generic model is in the DECODED time base — what Konduktor's deck plays and
|
||||
the grid detector measures. So a Pioneer adapter ADDS the offset on every write
|
||||
and SUBTRACTS it on every read. Get it wrong and nothing fails: every cue and
|
||||
beat is simply early in rekordbox (as the first OneLibrary exports were), or
|
||||
late in Konduktor.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from ...core import mp3_gapless, mp4_edit
|
||||
|
||||
#: The fallback for a lossy file that cannot be read: MP3's classic codec delay.
|
||||
CODEC_DELAY_SAMPLES = 1105
|
||||
#: Formats that carry a start padding. `.stem.m4a` (a Traktor STEM) is AAC.
|
||||
LOSSY = frozenset({".mp3", ".m4a", ".mp4", ".aac"})
|
||||
_MP4 = frozenset({".m4a", ".mp4"})
|
||||
_DEFAULT_RATE = 44100
|
||||
|
||||
|
||||
@lru_cache(maxsize=4096)
|
||||
def _sample_rate(path: str) -> int:
|
||||
try:
|
||||
import mutagen
|
||||
|
||||
rate = getattr(getattr(mutagen.File(path), "info", None), "sample_rate", None)
|
||||
return int(rate) if rate else _DEFAULT_RATE
|
||||
except Exception: # an unreadable header: assume the overwhelmingly common rate
|
||||
return _DEFAULT_RATE
|
||||
|
||||
|
||||
def _measured(p: Path) -> float | None:
|
||||
"""The per-file offset, or None when the file cannot be read."""
|
||||
suffix = p.suffix.lower()
|
||||
if suffix == ".mp3":
|
||||
start = mp3_gapless.read(p)
|
||||
if start is None:
|
||||
return None
|
||||
return start.trimmed / start.sample_rate if start.header_frame else 0.0
|
||||
if suffix in _MP4:
|
||||
return mp4_edit.priming_seconds(p)
|
||||
return None # raw ADTS .aac: nothing to read, keep the fallback
|
||||
|
||||
|
||||
def offset(path: Path | str | None) -> float:
|
||||
"""Seconds to ADD to a decoded-audio time to get rekordbox's; 0 if lossless.
|
||||
|
||||
A missing path (a track whose audio cannot be located) gets 0: there is no
|
||||
file to say which format it is, and guessing lossy would move a lossless
|
||||
track's cues. A path to a lossy file that cannot be read gets the fallback.
|
||||
"""
|
||||
if not path:
|
||||
return 0.0
|
||||
p = Path(path)
|
||||
if p.suffix.lower() not in LOSSY:
|
||||
return 0.0
|
||||
measured = _measured(p)
|
||||
if measured is not None:
|
||||
return measured
|
||||
return CODEC_DELAY_SAMPLES / _sample_rate(str(p))
|
||||
|
||||
|
||||
def to_pioneer(seconds: float, off: float) -> float:
|
||||
"""A decoded-audio time -> rekordbox's, never before its own time 0: the
|
||||
generic model can hold a position before the decoded audio starts (a
|
||||
Traktor grid anchored inside an MP3's header frame), which no Pioneer field
|
||||
can store."""
|
||||
return max(0.0, seconds + off)
|
||||
|
||||
|
||||
def from_pioneer(seconds: float, off: float) -> float:
|
||||
"""Back to the decoded time base, never before the start of the track: a
|
||||
rekordbox position inside the codec delay is the track's first sample."""
|
||||
return max(0.0, seconds - off)
|
||||
@@ -20,6 +20,7 @@ from ...core.capabilities import Capabilities
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.query import TrackIndex
|
||||
from ...core.relocate import PathGroup
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from .cue_types import CUE_TYPE_TO_NATIVE
|
||||
@@ -49,7 +50,7 @@ class TraktorAdapter:
|
||||
if entry is None:
|
||||
return TrackCues()
|
||||
self._index.replace(projection.to_track(entry))
|
||||
return projection.to_track_cues(entry)
|
||||
return projection.to_track_cues(entry, self._store.time_offset_ms(entry))
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@property
|
||||
@@ -74,7 +75,9 @@ class TraktorAdapter:
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
entry = self._store.model_entry(track_id)
|
||||
return projection.to_track_cues(entry) if entry is not None else None
|
||||
if entry is None:
|
||||
return None
|
||||
return projection.to_track_cues(entry, self._store.time_offset_ms(entry))
|
||||
|
||||
# ---- transitional shims --------------------------------------------
|
||||
# main.py still drives the store directly and calls replace_track after each
|
||||
@@ -160,8 +163,17 @@ class TraktorAdapter:
|
||||
self._rebuild()
|
||||
return n
|
||||
|
||||
# ---- stem conversion --------------------------------------------------
|
||||
def apply_stem_swaps(self, swaps: list, *, add_to_playlist: str | None = None):
|
||||
with _translate():
|
||||
result = self._store.apply_stem_swaps(swaps, add_to_playlist=add_to_playlist)
|
||||
# One rebuild for the whole batch: ids changed (repoint) or appeared
|
||||
# (add), and `TrackIndex` has no per-id remove.
|
||||
self._rebuild()
|
||||
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 —
|
||||
@@ -183,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:
|
||||
@@ -286,6 +299,10 @@ class TraktorAdapter:
|
||||
self._store.set_hotcue_type(track_id, slot, self._native_cue_type(cue_type))
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
|
||||
# Traktor colours a cue by its type (capabilities.cues.color = "none").
|
||||
raise Unsupported("Traktor colours cues by their type")
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_hotcue(track_id, slot)
|
||||
@@ -363,6 +380,12 @@ class TraktorAdapter:
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
self._store.set_session_mappings(mappings)
|
||||
|
||||
def unresolved_path_groups(self) -> list[PathGroup]:
|
||||
return self._store.unresolved_path_groups()
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
return self._store.path_prefix_suggestions()
|
||||
|
||||
|
||||
@@ -49,7 +49,9 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
# Traktor has no memory cues — every cue occupies a bank slot.
|
||||
memory_cues=False,
|
||||
types=CUE_TYPES,
|
||||
color="free",
|
||||
# Traktor colours a cue by its TYPE; the only COLOR it stores is a
|
||||
# grid marker's white companion, so there is nothing to pick.
|
||||
color="none",
|
||||
named=True,
|
||||
# A saved loop is a cue TYPE in Traktor, not a separate bank.
|
||||
loops="cue_type",
|
||||
@@ -60,6 +62,8 @@ 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.
|
||||
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
|
||||
|
||||
@@ -63,7 +63,9 @@ OTHER_PLAYLIST = "Other"
|
||||
|
||||
class TraktorExporter:
|
||||
platform = "traktor"
|
||||
menu_order = 20
|
||||
library_filename = "collection.nml"
|
||||
drive_root = False
|
||||
|
||||
def capabilities(self):
|
||||
"""What a Traktor library can hold — answered with no library to read.
|
||||
@@ -75,7 +77,7 @@ class TraktorExporter:
|
||||
Path(self.library_filename),
|
||||
[
|
||||
"title", "artist", "album", "genre", "label", "remixer",
|
||||
"producer", "mix", "release_date", "comment", "rating",
|
||||
"producer", "mix", "release_date", "comment", "comment2", "rating",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
import re
|
||||
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid
|
||||
from . import beatgrid, timebase
|
||||
from .cue_types import NATIVE_TO_CUE_TYPE
|
||||
|
||||
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
|
||||
@@ -17,6 +17,9 @@ from .cue_types import NATIVE_TO_CUE_TYPE
|
||||
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
|
||||
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
|
||||
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$")
|
||||
# "YYYY", "YYYY-MM" or "YYYY-MM-DD", optionally followed by a time (a
|
||||
# timestamp's date part is the date).
|
||||
_ISO_DATE = re.compile(r"^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:[T ].*)?$")
|
||||
|
||||
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
@@ -50,6 +53,28 @@ def iso_date(value: str | None) -> str | None:
|
||||
return f"{y}-{int(mo):02d}-{int(d):02d}"
|
||||
|
||||
|
||||
def traktor_date(value: str | None) -> str | None:
|
||||
"""The inverse of `iso_date`: an ISO-8601 date as Traktor writes it.
|
||||
|
||||
Traktor's form is unpadded "YYYY/M/D" — every one of the 16,000-odd dates
|
||||
in the real collection. A year alone becomes "YYYY/1/1", as Traktor itself
|
||||
records a year-only release date (2,094 of 2,122 there). Anything that is
|
||||
neither ISO nor already Traktor's form passes through unchanged, as
|
||||
`iso_date` does in the other direction: losing a date is worse than
|
||||
carrying one Traktor may not parse.
|
||||
"""
|
||||
if not value:
|
||||
return None
|
||||
s = value.strip()
|
||||
if m := _DATE.match(s):
|
||||
y, mo, d = m.groups()
|
||||
return f"{y}/{int(mo)}/{int(d)}"
|
||||
if m := _ISO_DATE.match(s):
|
||||
y, mo, d = m.groups()
|
||||
return f"{y}/{int(mo or 1)}/{int(d or 1)}"
|
||||
return value
|
||||
|
||||
|
||||
def primary_key(location) -> str:
|
||||
"""Reconstruct the Traktor primary key used by playlist entries."""
|
||||
vol = location.volume or ""
|
||||
@@ -109,6 +134,8 @@ def to_track(e) -> Track:
|
||||
producer=info.producer if info else None,
|
||||
mix=info.mix if info else None,
|
||||
comment=info.comment if info else None,
|
||||
# Traktor's "Comment 2" is stored in INFO@RATING (stars are RANKING).
|
||||
comment2=info.rating if info else None,
|
||||
bpm=beatgrid.effective_bpm(e),
|
||||
key=info.key if info else None,
|
||||
key_wheel=wheel,
|
||||
@@ -130,9 +157,13 @@ def to_track(e) -> Track:
|
||||
)
|
||||
|
||||
|
||||
def to_track_cues(entry) -> TrackCues:
|
||||
def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
|
||||
"""Project an ENTRY's beatgrid + cues.
|
||||
|
||||
`offset_ms` is how far the entry's positions sit behind the decoded audio
|
||||
(`TraktorStore.time_offset_ms`, see `timebase`); positions come out in the
|
||||
decoded time base, unclamped.
|
||||
|
||||
The beatgrid is the FULL ordered marker list — a constant grid is a list of
|
||||
length one. Grid markers themselves are not cues; their companion cues are,
|
||||
because they occupy real hotcue slots. Each is tagged with the marker it sits
|
||||
@@ -144,7 +175,7 @@ def to_track_cues(entry) -> TrackCues:
|
||||
marker_of = {id(c): i for i, c in comps.items()}
|
||||
grid_markers = [
|
||||
GridMarker(
|
||||
start=(m.start or 0.0) / 1000.0, # Traktor stores START in ms
|
||||
start=timebase.from_traktor_ms(m.start or 0.0, offset_ms), # START is ms
|
||||
bpm=m.grid.bpm if m.grid and m.grid.bpm else 0.0,
|
||||
name=m.name,
|
||||
companion=comps[i].hotcue if i in comps else None,
|
||||
@@ -165,7 +196,7 @@ def to_track_cues(entry) -> TrackCues:
|
||||
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
|
||||
# Every Traktor cue lives in the hotcue bank.
|
||||
role="hotcue",
|
||||
start=(c.start or 0.0) / 1000.0,
|
||||
start=timebase.from_traktor_ms(c.start or 0.0, offset_ms),
|
||||
length=(c.len or 0.0) / 1000.0,
|
||||
slot=slot,
|
||||
color=c.color,
|
||||
|
||||
@@ -18,6 +18,8 @@ Playlists are identified by their stable UUID; folders by a synthetic path id
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import math
|
||||
import threading
|
||||
import uuid as uuidlib
|
||||
from dataclasses import dataclass
|
||||
@@ -38,18 +40,22 @@ from traktor_nml_utils.models.collection import (
|
||||
Nodetype,
|
||||
Playlisttype,
|
||||
Primarykeytype,
|
||||
Stemstype,
|
||||
Subnodestype,
|
||||
Tempotype,
|
||||
)
|
||||
from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
|
||||
from ...core.adapter import InvalidCommand, SaveOutcome
|
||||
from ...core.adapter import InvalidCommand, SaveOutcome, StemSwapResult
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import common_dir_prefix
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.relocate import PathGroup
|
||||
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
|
||||
from ...schemas import PlaylistNode
|
||||
from . import beatgrid
|
||||
from . import beatgrid, timebase
|
||||
from .locations import os_path_to_location, resolve_path
|
||||
from .projection import iso_date, traktor_date
|
||||
|
||||
# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under
|
||||
# this email is what makes the stars show up in Traktor itself.
|
||||
@@ -81,6 +87,9 @@ class TraktorStore:
|
||||
self.dirty = False
|
||||
# Active OS-path prefix remapping (empty = identity). Survives _load().
|
||||
self._path_mapping = PathMapping()
|
||||
# Mappings the user confirmed in the open-time missing-files check.
|
||||
# Session-only: never saved, re-derived on every open.
|
||||
self._session_mappings: list[PathMapping] = []
|
||||
self._load()
|
||||
|
||||
# ---- load ----------------------------------------------------------
|
||||
@@ -362,7 +371,10 @@ class TraktorStore:
|
||||
# (it's the primary key), bpm/key (audio/grid territory), and read-only info
|
||||
# like bitrate/playcount.
|
||||
_INFO_FIELDS = {"genre", "label", "remixer", "producer", "comment", "mix", "release_date"}
|
||||
EDITABLE_FIELDS = {"title", "artist", "album", "rating"} | _INFO_FIELDS
|
||||
EDITABLE_FIELDS = {"title", "artist", "album", "rating", "comment2"} | _INFO_FIELDS
|
||||
# Fields that live only in the collection: Traktor itself writes no file tag
|
||||
# for "Comment 2" (verified on an m4a it had just edited), so neither do we.
|
||||
_COLLECTION_ONLY_FIELDS = {"comment2"}
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
||||
with self._lock:
|
||||
@@ -378,8 +390,16 @@ class TraktorStore:
|
||||
if entry.album is None:
|
||||
entry.album = Albumtype()
|
||||
entry.album.title = v or None
|
||||
elif k == "release_date":
|
||||
# Edited as ISO (that is what the projection shows); stored
|
||||
# as Traktor's "YYYY/M/D".
|
||||
entry.info.release_date = traktor_date(v)
|
||||
elif k in self._INFO_FIELDS:
|
||||
setattr(entry.info, k, v or None)
|
||||
elif k == "comment2":
|
||||
# Traktor's "Comment 2" is INFO@RATING — a free-text
|
||||
# attribute, unrelated to the star rating (RANKING).
|
||||
entry.info.rating = v or None
|
||||
elif k == "rating":
|
||||
stars = max(0, min(5, int(v))) if v is not None else 0
|
||||
# Traktor RANKING = stars * 51; unrated has no RANKING attr.
|
||||
@@ -409,7 +429,14 @@ class TraktorStore:
|
||||
and ``loudness``. Both are outputs of Traktor's own analysis and cannot
|
||||
be computed here; Traktor re-analyses a track that has none. Writing a
|
||||
plausible-looking fingerprint would be inventing data.
|
||||
|
||||
A stem FILE gets ``<STEMS>``, rendered from its own ``stem`` box as
|
||||
Traktor renders it: that element is what makes the entry a stem track
|
||||
(its playlist keys ``TYPE="STEM"``, the Type column), and without it a
|
||||
stem file added here read as plain audio.
|
||||
"""
|
||||
# Read before the lock: it opens the file.
|
||||
stems = nml_stems_for(audio_path)
|
||||
with self._lock:
|
||||
volume, dir_, file = os_path_to_location(Path(audio_path))
|
||||
key = f"{volume}{dir_}{file}"
|
||||
@@ -422,14 +449,16 @@ class TraktorStore:
|
||||
genre=getattr(track, "genre", None) or None,
|
||||
label=getattr(track, "label", None) or None,
|
||||
comment=getattr(track, "comment", None) or None,
|
||||
rating=getattr(track, "comment2", None) or None, # "Comment 2"
|
||||
remixer=getattr(track, "remixer", None) or None,
|
||||
producer=getattr(track, "producer", None) or None,
|
||||
mix=getattr(track, "mix", None) or None,
|
||||
key=getattr(track, "key", None) or None,
|
||||
bitrate=getattr(track, "bitrate", None) or None,
|
||||
playcount=getattr(track, "playcount", None) or None,
|
||||
release_date=getattr(track, "release_date", None) or None,
|
||||
import_date=getattr(track, "import_date", None) or None,
|
||||
# The generic model carries ISO dates; Traktor writes "YYYY/M/D".
|
||||
release_date=traktor_date(getattr(track, "release_date", None)),
|
||||
import_date=traktor_date(getattr(track, "import_date", None)),
|
||||
# Traktor's RANKING is stars x 51; an unrated track has no
|
||||
# attribute at all rather than a zero.
|
||||
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
|
||||
@@ -451,6 +480,7 @@ class TraktorStore:
|
||||
# `replace_grid` overwrites it from the markers when they land.
|
||||
tempo=Tempotype(bpm=float(bpm)) if bpm else None,
|
||||
cue_v2=[],
|
||||
stems=Stemstype(stems=stems) if stems else None,
|
||||
)
|
||||
self._nml.collection.entry.append(entry)
|
||||
self._entry_by_key[key] = entry
|
||||
@@ -585,7 +615,9 @@ class TraktorStore:
|
||||
raise PlaylistError(f"Unsupported cue type: {cue_type}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START/LEN in ms
|
||||
# Traktor stores START/LEN in ms, on its own clock (see `timebase`).
|
||||
# A length is a duration, so the offset does not apply to it.
|
||||
start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
|
||||
len_ms = max(0.0, length_sec * 1000.0)
|
||||
existing = next(
|
||||
(c for c in (entry.cue_v2 or []) if c.hotcue == slot), None
|
||||
@@ -740,7 +772,7 @@ class TraktorStore:
|
||||
raise PlaylistError(f"BPM must be positive: {bpm}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
start_ms = max(0.0, start_sec * 1000.0)
|
||||
start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
|
||||
markers = beatgrid.grid_markers(entry)
|
||||
for m in markers:
|
||||
if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS:
|
||||
@@ -800,7 +832,7 @@ class TraktorStore:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
markers, marker = self._markers_or_raise(entry, index)
|
||||
start_ms = max(0.0, start_sec * 1000.0)
|
||||
start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
|
||||
if index > 0:
|
||||
lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS
|
||||
start_ms = max(start_ms, lo)
|
||||
@@ -864,6 +896,7 @@ class TraktorStore:
|
||||
raise PlaylistError(f"BPM must be positive: {bpm}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
off_ms = self.time_offset_ms(entry)
|
||||
self._drop_grid(entry)
|
||||
if entry.cue_v2 is None:
|
||||
entry.cue_v2 = []
|
||||
@@ -875,7 +908,7 @@ class TraktorStore:
|
||||
name="AutoGrid" if i == 0 else "n.n.",
|
||||
displ_order=0,
|
||||
type=4,
|
||||
start=max(0.0, start_sec * 1000.0),
|
||||
start=timebase.to_traktor_ms(start_sec, off_ms),
|
||||
len=0.0,
|
||||
repeats=-1,
|
||||
hotcue=-1,
|
||||
@@ -965,23 +998,61 @@ class TraktorStore:
|
||||
with self._lock:
|
||||
self._path_mapping = mapping
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
"""Set the mappings confirmed for this session (applied at resolve time)."""
|
||||
with self._lock:
|
||||
self._session_mappings = [m for m in mappings if not m.empty]
|
||||
|
||||
def _resolve(self, loc) -> "Path | None":
|
||||
"""Resolve a LOCATION to an OS path, applying the active path mapping.
|
||||
"""Resolve a LOCATION to an OS path, applying the active path mappings.
|
||||
|
||||
The single FS chokepoint: LOCATION -> `resolve_path` -> prefix remap.
|
||||
Falls back to the un-remapped path when the remapped target doesn't
|
||||
exist, so a misconfigured mapping never makes a present file unreachable.
|
||||
The saved mapping is tried first, then — only for a file still not
|
||||
found — the session's. Falls back to the un-remapped path when no
|
||||
remapped target exists, so a misconfigured mapping never makes a
|
||||
present file unreachable.
|
||||
"""
|
||||
|
||||
if loc is None:
|
||||
return None
|
||||
base = resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if self._path_mapping.empty:
|
||||
return base
|
||||
remapped = self._path_mapping.apply(base)
|
||||
if remapped == base:
|
||||
return base
|
||||
return remapped if remapped.exists() else base
|
||||
if not self._path_mapping.empty:
|
||||
remapped = self._path_mapping.apply(base)
|
||||
if remapped != base and remapped.exists():
|
||||
return remapped
|
||||
if self._session_mappings and not base.exists():
|
||||
for mapping in self._session_mappings:
|
||||
remapped = mapping.apply(base)
|
||||
if remapped != base and remapped.exists():
|
||||
return remapped
|
||||
return base
|
||||
|
||||
def unresolved_path_groups(self) -> list[PathGroup]:
|
||||
"""Each stored VOLUME in which not one track resolves, with its tracks'
|
||||
stored paths — the input to the open-time missing-files search.
|
||||
|
||||
"Not one" is the threshold: a volume missing a few deleted files is a
|
||||
library with a few deleted files, not a library that needs remapping.
|
||||
The stats happen outside the lock; checking stops at a volume's first
|
||||
present file, and a missing path fails fast, so this is cheap either way.
|
||||
"""
|
||||
with self._lock:
|
||||
by_volume: dict[str, list] = {}
|
||||
for e in self._nml.collection.entry:
|
||||
if e.location is not None and e.location.file:
|
||||
by_volume.setdefault(e.location.volume or "", []).append(e.location)
|
||||
groups = []
|
||||
for volume, locs in by_volume.items():
|
||||
if any(self._resolve(loc).exists() for loc in locs):
|
||||
continue
|
||||
groups.append(
|
||||
PathGroup(
|
||||
label=volume,
|
||||
root=str(resolve_path(volume, "/:", "")),
|
||||
paths=[str(resolve_path(l.volume, l.dir, l.file)) for l in locs],
|
||||
)
|
||||
)
|
||||
return groups
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
"""Staged replacement if present, else the file's current embedded art."""
|
||||
@@ -996,6 +1067,12 @@ class TraktorStore:
|
||||
path = self._resolve(entry.location)
|
||||
return file_tags.read_cover(path) if path else None
|
||||
|
||||
def time_offset_ms(self, entry: Entrytype) -> float:
|
||||
"""How far this entry's positions sit behind the decoded audio, in ms
|
||||
(see `timebase`). Every seconds <-> START conversion goes through it:
|
||||
the four writes here and `projection.to_track_cues` on the way out."""
|
||||
return timebase.offset_ms(self._resolve(entry.location) if entry.location else None)
|
||||
|
||||
def audio_path(self, track_id: str) -> "Path | None":
|
||||
"""Resolve a track's audio file to an OS path (for playback streaming)."""
|
||||
with self._lock:
|
||||
@@ -1032,10 +1109,51 @@ class TraktorStore:
|
||||
ranked = [g for g in ranked if g["prefix"]]
|
||||
return {"primary": ranked[0]["prefix"] if ranked else "", "groups": ranked[:5]}
|
||||
|
||||
def _plan_remap(self, mapping: PathMapping):
|
||||
"""Where a mapping would move each matching entry, and what that clashes
|
||||
with — computed before anything changes. Caller holds the lock.
|
||||
|
||||
Returns ``(moves, clashes)``: ``moves`` is ``[(entry, old_key, new_key,
|
||||
(volume, dir, file))]`` for every entry whose key would change, and
|
||||
``clashes`` maps each clashing NEW key to the old keys landing on it.
|
||||
|
||||
A key is a Traktor primary key, so two ENTRYs sharing one is a corrupt
|
||||
collection (`add_entry` refuses the same thing). A new key clashes when
|
||||
tracks with DIFFERENT old keys land on it, or when it is the key of an
|
||||
entry that stays where it is. A chain or swap — A onto B's old path
|
||||
while B moves on — is fine, and so is a duplicate the collection already
|
||||
had: two entries sharing one key move together, no worse than before.
|
||||
"""
|
||||
moves = []
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
base = resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if not mapping.matches(base):
|
||||
continue
|
||||
volume, dir_, file = os_path_to_location(mapping.apply(base))
|
||||
old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
new_key = f"{volume or ''}{dir_ or ''}{file or ''}"
|
||||
if old_key != new_key: # a no-op (e.g. from == to) stays byte-identical
|
||||
moves.append((e, old_key, new_key, (volume, dir_, file)))
|
||||
moving = {id(e) for e, *_ in moves}
|
||||
staying = {self._key_of(e) for e in self._nml.collection.entry
|
||||
if e.location and id(e) not in moving}
|
||||
landing: dict[str, set[str]] = {}
|
||||
for _e, old_key, new_key, _loc in moves:
|
||||
landing.setdefault(new_key, set()).add(old_key)
|
||||
clashes = {
|
||||
new_key: sorted(olds) for new_key, olds in landing.items()
|
||||
if len(olds) > 1 or new_key in staying
|
||||
}
|
||||
return moves, clashes
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
"""How a mapping would affect the collection, without changing anything:
|
||||
total tracks, how many match ``from``, and how many exist at ``to``
|
||||
(plus a few samples). Powers the mapping editor's validation line."""
|
||||
total tracks, how many match ``from``, how many exist at ``to``, and how
|
||||
many would CLASH with another track's path (which `remap_locations`
|
||||
refuses) — plus a few samples. Powers the mapping editor's validation."""
|
||||
|
||||
with self._lock:
|
||||
total = matched = existing = 0
|
||||
@@ -1054,7 +1172,17 @@ class TraktorStore:
|
||||
existing += 1
|
||||
if len(samples) < 5:
|
||||
samples.append({"from": str(base), "to": str(target), "exists": ok})
|
||||
return {"total": total, "matched": matched, "existing": existing, "samples": samples}
|
||||
_moves, clashes = self._plan_remap(mapping)
|
||||
return {
|
||||
"total": total, "matched": matched, "existing": existing, "samples": samples,
|
||||
"collisions": len(clashes),
|
||||
"collision_samples": [self._display_key(k) for k in sorted(clashes)[:5]],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _display_key(key: str) -> str:
|
||||
"""A primary key as a readable path ("Volume/:dir/:file" -> "Volume/dir/file")."""
|
||||
return key.replace("/:", "/")
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
|
||||
"""Permanently rewrite matching track LOCATIONs to the mapping's ``to``
|
||||
@@ -1066,29 +1194,44 @@ class TraktorStore:
|
||||
untouched. Returns ``{old track id: new track id}`` for every track
|
||||
rewritten — callers holding ids (export sets) follow them with it, and
|
||||
must not rebuild it from paths; the caller saves.
|
||||
|
||||
**Refused, with nothing changed, if any track would land on another
|
||||
track's path** (see `_plan_remap`): the collection would then hold two
|
||||
ENTRYs sharing a primary key. Every re-key below is applied AT ONCE, not
|
||||
track by track, so a chain (A onto B's old path, B onward) cannot carry
|
||||
A's staged art or edits along to B's destination.
|
||||
"""
|
||||
|
||||
if mapping.empty:
|
||||
return {}
|
||||
with self._lock:
|
||||
key_remap: dict[str, str] = {}
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
base = resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if not mapping.matches(base):
|
||||
continue
|
||||
target = mapping.apply(base)
|
||||
volume, dir_, file = os_path_to_location(target)
|
||||
old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
new_key = f"{volume or ''}{dir_ or ''}{file or ''}"
|
||||
if old_key == new_key:
|
||||
continue # no-op (e.g. from == to); leave byte-identical
|
||||
loc.volume, loc.dir, loc.file = volume, dir_, file
|
||||
key_remap[old_key] = new_key
|
||||
if not key_remap:
|
||||
moves, clashes = self._plan_remap(mapping)
|
||||
if clashes:
|
||||
paths = [self._display_key(k) for k in sorted(clashes)]
|
||||
shown = ", ".join(paths[:3]) + (f" and {len(paths) - 3} more" if len(paths) > 3 else "")
|
||||
raise PlaylistError(
|
||||
f"Remapping would give {len(paths)} path{'s' if len(paths) != 1 else ''} to more "
|
||||
f"than one track ({shown}). Two entries sharing a path corrupt the collection, "
|
||||
"so nothing was changed."
|
||||
)
|
||||
if not moves:
|
||||
return {}
|
||||
key_remap = {old_key: new_key for _e, old_key, new_key, _loc in moves}
|
||||
for e, _old, _new, (volume, dir_, file) in moves:
|
||||
e.location.volume, e.location.dir, e.location.file = volume, dir_, file
|
||||
# Re-key the index too. Everything that finds an ENTRY by track id
|
||||
# goes through it — later edits, and the file-tag sync on save,
|
||||
# which would otherwise silently skip every edit made to this track
|
||||
# before the remap. Drop every old key first, then add every new
|
||||
# one, so a chain cannot delete an entry another has just claimed.
|
||||
for e, old_key, _new, _loc in moves:
|
||||
if self._entry_by_key.get(old_key) is e:
|
||||
del self._entry_by_key[old_key]
|
||||
for e, _old, new_key, _loc in moves:
|
||||
self._entry_by_key[new_key] = e
|
||||
art = {old: self._track_art.pop(old) for old in key_remap if old in self._track_art}
|
||||
for old, staged in art.items():
|
||||
self._track_art[key_remap[old]] = staged
|
||||
# Rewrite playlist entry primary keys that referenced moved tracks.
|
||||
for node in self._iter_nodes(self._root()):
|
||||
pl = node.playlist
|
||||
@@ -1100,12 +1243,188 @@ class TraktorStore:
|
||||
pk.key = key_remap[pk.key]
|
||||
# Track ids derive from the LOCATION, so a remap renames them. Carry
|
||||
# this session's journal entries across or their file-tag sync is lost.
|
||||
for old_key, new_key in key_remap.items():
|
||||
self._journal.retarget(old_key, new_key)
|
||||
self._journal.retarget_many(key_remap)
|
||||
self._note("remap", str(len(key_remap)))
|
||||
self.dirty = True
|
||||
return key_remap
|
||||
|
||||
# ---- stem conversion ---------------------------------------------------
|
||||
#: Whether a converted entry keeps Traktor's analysis fingerprint (AUDIO_ID).
|
||||
#: KEPT, as measured in Traktor 4.5 (kit 5, 2026-09-30): with it kept, Traktor
|
||||
#: loads the stem entry as it is — cues, grid and fingerprint untouched. With
|
||||
#: it cleared, Traktor re-analyses on load: it keeps grid POSITIONS (even a
|
||||
#: hand-nudged, unlocked one) but re-measures the grid's BPM (125.000023 ->
|
||||
#: 125.00042), i.e. it rewrites prep the user set. The stem file's mix is the
|
||||
#: same audio as the original, so the old fingerprint still describes it.
|
||||
_KEEP_AUDIO_ID_ON_STEM = True
|
||||
|
||||
def apply_stem_swaps(self, swaps: list, *, add_to_playlist: str | None = None) -> StemSwapResult:
|
||||
"""Point entries at converted stem files ("repoint"), or add entries for
|
||||
them ("add"), ALL AT ONCE — every swap validated before any is applied,
|
||||
so a clash leaves the collection untouched.
|
||||
|
||||
What a stem entry is, measured on the real collection: the ordinary
|
||||
ENTRY plus a `<STEMS>` element (after CUE_V2), and playlist PRIMARYKEYs of
|
||||
`TYPE="STEM"`. INFO's bitrate / playtime / playtime_float / filesize (KB)
|
||||
describe the new file.
|
||||
|
||||
**Positions move with the time base.** An MP3 with a header sits
|
||||
`timebase.offset_ms` later on Traktor's clock than the decoded audio; the
|
||||
stem file (an MP4 whose edit list Traktor honours) sits at 0. So every
|
||||
START shifts by (new offset - old offset), with the old offset read from
|
||||
`original_audio` — where the original's bytes are NOW (its parked name in
|
||||
Replace mode) — under the original's own suffix. Read from the old path
|
||||
instead, the file would be gone, the offset 0, and every cue ~51 ms late.
|
||||
A shifted grid anchor that would fall before 0 moves forward by whole
|
||||
beats (its companion with it), which leaves the grid itself unchanged; a
|
||||
hotcue that would is clamped to 0 and reported.
|
||||
"""
|
||||
with self._lock:
|
||||
# ---- validate everything first ----
|
||||
seen_ids: set[str] = set()
|
||||
planned: list[tuple[object, Entrytype, str, tuple[str, str, str]]] = []
|
||||
new_keys: set[str] = set()
|
||||
for swap in swaps:
|
||||
entry = self._entry_by_key.get(swap.track_id)
|
||||
if entry is None or entry.location is None:
|
||||
raise PlaylistError(f"Track not found: {swap.track_id}")
|
||||
if swap.track_id in seen_ids:
|
||||
raise PlaylistError(f"Track listed twice: {swap.track_id}")
|
||||
if swap.mode not in ("repoint", "add"):
|
||||
raise PlaylistError(f"Unknown stem swap mode: {swap.mode}")
|
||||
seen_ids.add(swap.track_id)
|
||||
loc = os_path_to_location(Path(swap.stem_path))
|
||||
new_key = "".join(x or "" for x in loc)
|
||||
if new_key in self._entry_by_key or new_key in new_keys:
|
||||
raise PlaylistError(
|
||||
f"The collection already has an entry for {swap.stem_path}"
|
||||
)
|
||||
new_keys.add(new_key)
|
||||
planned.append((swap, entry, new_key, loc))
|
||||
playlist = None
|
||||
if add_to_playlist is not None:
|
||||
playlist = self._find_playlist_node(add_to_playlist)
|
||||
if playlist is None or playlist.playlist is None:
|
||||
raise PlaylistError(f"Playlist not found: {add_to_playlist}")
|
||||
|
||||
# ---- apply ----
|
||||
result = StemSwapResult()
|
||||
renames: dict[str, str] = {}
|
||||
for swap, entry, new_key, loc in planned:
|
||||
old_key = swap.track_id
|
||||
old_suffix = Path(entry.location.file or "").suffix
|
||||
shift = timebase.offset_ms(swap.stem_path) - timebase.offset_ms(
|
||||
swap.original_audio, suffix=old_suffix)
|
||||
target = entry if swap.mode == "repoint" else copy.deepcopy(entry)
|
||||
clamped = self._retime(target, shift)
|
||||
self._point_at_stem(target, loc, swap)
|
||||
if swap.mode == "repoint":
|
||||
renames[old_key] = new_key
|
||||
if self._entry_by_key.get(old_key) is entry:
|
||||
del self._entry_by_key[old_key]
|
||||
self._entry_by_key[new_key] = entry
|
||||
if old_key in self._track_art:
|
||||
self._track_art[new_key] = self._track_art.pop(old_key)
|
||||
else:
|
||||
self._nml.collection.entry.append(target)
|
||||
self._entry_by_key[new_key] = target
|
||||
# Unsaved tag edits and staged art must reach the NEW file
|
||||
# too on Save; the original keeps its own.
|
||||
for field in self._journal.fields_for(old_key):
|
||||
self._journal.record("track", "set", new_key, field)
|
||||
if old_key in self._track_art:
|
||||
self._track_art[new_key] = self._track_art[old_key]
|
||||
result.renamed[old_key] = new_key
|
||||
if clamped:
|
||||
result.clamped[new_key] = clamped
|
||||
self._journal.record("stem", swap.mode, new_key, old_key)
|
||||
if any(s.mode == "add" for s, *_ in planned):
|
||||
self._nml.collection.entries = len(self._nml.collection.entry)
|
||||
# Playlists follow a repointed track — and it is a STEM now.
|
||||
if renames:
|
||||
for node in self._iter_nodes(self._root()):
|
||||
pl = node.playlist
|
||||
if pl is None or not pl.entry:
|
||||
continue
|
||||
for pe in pl.entry:
|
||||
pk = pe.primarykey
|
||||
if pk and pk.key in renames:
|
||||
pk.key = renames[pk.key]
|
||||
pk.type = "STEM"
|
||||
self._journal.retarget_many(renames)
|
||||
if playlist is not None:
|
||||
added = [new for (s, _e, new, _l) in planned if s.mode == "add"]
|
||||
pl = playlist.playlist
|
||||
pl.entry = list(pl.entry or []) + [
|
||||
Entrytype(primarykey=Primarykeytype(type="STEM", key=k)) for k in added
|
||||
]
|
||||
pl.entries = len(pl.entry)
|
||||
self._note("playlist-entries", playlist.name)
|
||||
self.dirty = True
|
||||
return result
|
||||
|
||||
def _point_at_stem(self, entry: Entrytype, loc: tuple[str, str, str], swap) -> None:
|
||||
"""LOCATION, `<STEMS>` and the file-describing INFO fields, for the stem file."""
|
||||
volume, dir_, file = loc
|
||||
old_volume = entry.location.volume if entry.location else None
|
||||
volumeid = entry.location.volumeid if entry.location else None
|
||||
if volume != old_volume:
|
||||
# VOLUMEID names a volume, so it cannot follow the file to another one;
|
||||
# borrow it from any entry already on that volume, else leave it for
|
||||
# Traktor to fill in (as `add_entry` does).
|
||||
volumeid = next(
|
||||
(e.location.volumeid for e in self._nml.collection.entry
|
||||
if e.location and e.location.volume == volume and e.location.volumeid),
|
||||
None,
|
||||
)
|
||||
entry.location = Locationtype(volume=volume, dir=dir_, file=file, volumeid=volumeid)
|
||||
entry.stems = Stemstype(stems=NML_STEMS_JSON)
|
||||
if entry.info is None:
|
||||
entry.info = Infotype()
|
||||
entry.info.bitrate = int(swap.bit_rate)
|
||||
entry.info.playtime = int(round(swap.duration))
|
||||
entry.info.playtime_float = float(swap.duration)
|
||||
entry.info.filesize = int(round(swap.size / 1024))
|
||||
if not self._KEEP_AUDIO_ID_ON_STEM:
|
||||
entry.audio_id = None
|
||||
|
||||
def _retime(self, entry: Entrytype, shift_ms: float) -> list[int]:
|
||||
"""Shift every cue and grid marker by `shift_ms`; returns the hotcue
|
||||
slots clamped at 0. Companions move WITH their marker, as the same float,
|
||||
so the pairing survives exactly."""
|
||||
if not shift_ms or not entry.cue_v2:
|
||||
return []
|
||||
markers = beatgrid.grid_markers(entry)
|
||||
comps = beatgrid.companions(entry)
|
||||
comp_ids = {id(c) for c in comps.values()}
|
||||
clamped: list[int] = []
|
||||
for c in entry.cue_v2:
|
||||
if c.grid is not None or id(c) in comp_ids:
|
||||
continue
|
||||
start = (c.start or 0.0) + shift_ms
|
||||
if start < 0:
|
||||
if c.hotcue is not None and c.hotcue >= 0:
|
||||
clamped.append(c.hotcue)
|
||||
start = 0.0
|
||||
c.start = start
|
||||
for i, m in enumerate(markers):
|
||||
start = (m.start or 0.0) + shift_ms
|
||||
if start < 0:
|
||||
bpm = m.grid.bpm if m.grid and m.grid.bpm else 0.0
|
||||
if bpm > 0:
|
||||
beat = 60000.0 / bpm
|
||||
start += math.ceil(-start / beat) * beat
|
||||
nxt = markers[i + 1].start + shift_ms if i + 1 < len(markers) else None
|
||||
if nxt is not None and start >= nxt:
|
||||
start = 0.0 # a pathological grid: keep the order, lose the phase
|
||||
else:
|
||||
start = 0.0
|
||||
m.start = start
|
||||
if i in comps:
|
||||
comps[i].start = m.start
|
||||
self._sort_cues(entry)
|
||||
return clamped
|
||||
|
||||
def _entry_field_value(self, entry: Entrytype, field: str):
|
||||
"""Read a single editable field's current value from the model, in the
|
||||
shape file_tags expects (rating as 0–5 stars)."""
|
||||
@@ -1118,6 +1437,11 @@ class TraktorStore:
|
||||
if field == "rating":
|
||||
r = entry.info.ranking if entry.info else None
|
||||
return round(r / 51) if r else 0
|
||||
if field == "comment2":
|
||||
return entry.info.rating if entry.info else None
|
||||
if field == "release_date":
|
||||
# A file tag wants ISO, not the NML's "YYYY/M/D".
|
||||
return iso_date(entry.info.release_date) if entry.info else None
|
||||
return getattr(entry.info, field, None) if entry.info else None
|
||||
|
||||
def count_playlists(self) -> int:
|
||||
@@ -1159,7 +1483,8 @@ class TraktorStore:
|
||||
# Report BOTH writes: a failed tag write must not be masked by a
|
||||
# successful art write on the same track.
|
||||
written = []
|
||||
if fields := self._journal.fields_for(track_id):
|
||||
fields = self._journal.fields_for(track_id) - self._COLLECTION_ONLY_FIELDS
|
||||
if fields:
|
||||
meta = {f: self._entry_field_value(entry, f) for f in fields}
|
||||
written.append(file_tags.write_tags(path, meta, popm_email=TRAKTOR_POPM_EMAIL))
|
||||
if track_id in self._track_art:
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Traktor's clock vs the decoded audio's — one rule, used at every boundary.
|
||||
|
||||
**On an MP3 with a gapless header, Traktor's time 0 is NOT the decoded audio's
|
||||
time 0.** Traktor decodes MP3 naively: it ignores the LAME gapless fields and
|
||||
decodes the Xing/Info header frame as if it were audio. A gapless decoder skips
|
||||
that frame and trims the encoder's start padding. So every position Traktor
|
||||
stores — grid markers, cues, loops — sits
|
||||
|
||||
samples_per_frame + encoder_delay + 529 (= 2257 for LAME's usual 576)
|
||||
|
||||
samples LATER than the same moment in the decoded audio: ~51.2 ms at 44.1 kHz,
|
||||
~47.0 ms at 48 kHz. The rule is in SAMPLES. An MP3 WITHOUT a header is decoded
|
||||
the same way by both sides (nothing to skip, nothing to trim), so its offset is
|
||||
0 — as is every other format: WAV, AIFF, FLAC and AAC (Traktor honours the MP4
|
||||
edit list) line up to the sample.
|
||||
|
||||
Measured 2026-09-30 in Traktor 4.5 ("kit 4", see the stem-conversion discussion
|
||||
log): hotcues Konduktor wrote on a synthetic kick, blinded, landed on it only
|
||||
at this offset, and hotcues placed by hand in Traktor read back at it (+2255 at
|
||||
44.1 kHz, +2242 at 48 kHz, header-less −6, WAV −4, AAC −13). Traktor's AutoGrid
|
||||
agrees, and `bench_grid_detect.py` shows it on every Traktor-analysed MP3.
|
||||
Derived, not measured: a header frame whose delay field a gapless decoder does
|
||||
not trust (no LAME/Lavf/Lavc tag, or a VBRI tag) — the decoder then skips the
|
||||
frame but trims nothing, so the offset is one frame.
|
||||
|
||||
The generic model is in the DECODED time base — what Konduktor's deck plays and
|
||||
the grid detector measures. So the Traktor store ADDS the offset on every write
|
||||
and the projection SUBTRACTS it on every read. A read is NOT clamped at 0: a
|
||||
Traktor grid anchor can sit inside the header frame (a beat before the decoded
|
||||
audio starts), and clamping it would move the grid on its next write-back.
|
||||
Get it wrong and nothing fails: every MP3 cue and beat is simply ~51 ms early in
|
||||
Traktor, or late in Konduktor — which is what every release before this did.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core import mp3_gapless
|
||||
|
||||
|
||||
def offset_samples(path: Path | str | None, suffix: str | None = None) -> tuple[int, int]:
|
||||
"""(samples Traktor runs behind the decoded audio, sample rate).
|
||||
|
||||
(0, 0) for anything that is not an MP3 with a header frame — including a
|
||||
file that cannot be read: with no header to go by, 0 is the answer that
|
||||
cannot move a cue, since a position read at 0 is written back at 0.
|
||||
|
||||
`suffix` overrides the format the name implies — for a file whose bytes are
|
||||
a track's but whose name is not, like a converted track's original parked
|
||||
as `.<name>.konduktor-parked` until Save.
|
||||
"""
|
||||
if not path or (suffix or Path(path).suffix).lower() != ".mp3":
|
||||
return 0, 0
|
||||
start = mp3_gapless.read(path)
|
||||
if start is None or not start.header_frame:
|
||||
return 0, 0
|
||||
return start.samples_per_frame + start.trimmed, start.sample_rate
|
||||
|
||||
|
||||
def offset_ms(path: Path | str | None, suffix: str | None = None) -> float:
|
||||
"""Milliseconds to ADD to a decoded-audio time to get Traktor's."""
|
||||
samples, rate = offset_samples(path, suffix)
|
||||
return samples * 1000.0 / rate if samples else 0.0
|
||||
|
||||
|
||||
def to_traktor_ms(seconds: float, off_ms: float) -> float:
|
||||
"""A decoded-audio time in seconds -> a Traktor START in ms (never < 0:
|
||||
Traktor cannot store a position before its own time 0)."""
|
||||
return max(0.0, seconds * 1000.0 + off_ms)
|
||||
|
||||
|
||||
def from_traktor_ms(start_ms: float, off_ms: float) -> float:
|
||||
"""A Traktor START in ms -> decoded-audio seconds. Deliberately unclamped."""
|
||||
return (start_ms - off_ms) / 1000.0
|
||||
@@ -25,12 +25,14 @@ human summary, and this module versions them.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
|
||||
from .core import registry
|
||||
from .core.adapter import LibraryAdapter
|
||||
from .core.pathmap import PathMapping
|
||||
from .relocation import RelocationCheck
|
||||
|
||||
|
||||
class AppState:
|
||||
@@ -47,6 +49,18 @@ class AppState:
|
||||
# module docstring for why it is not symmetrical with `adapter`.
|
||||
self.source_path: Path | None = None
|
||||
self.source: LibraryAdapter | None = None
|
||||
# This open's missing-files check (see `relocation.py`). A new one per
|
||||
# open, which is what makes the dialog ask again on a reopen.
|
||||
self.relocation: RelocationCheck | None = None
|
||||
# Serialises the operations that REPLACE or COMMIT the whole library —
|
||||
# open, save, discard (and a stem batch's swap step). A save landing in
|
||||
# the middle of another would commit a half-applied state; reentrant so
|
||||
# one of them may call another.
|
||||
self.mutation = threading.RLock()
|
||||
# Converted-to-stem tracks awaiting Save or Discard (see stems/pending.py),
|
||||
# and what the last open's crash recovery did about any left over.
|
||||
self.pending = None
|
||||
self.recovery: dict | None = None
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
@@ -91,6 +105,10 @@ class AppState:
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> None:
|
||||
with self.mutation:
|
||||
self._open(path)
|
||||
|
||||
def _open(self, path: Path) -> None:
|
||||
# The registry picks the adapter by probing the file, not by extension —
|
||||
# a Rekordbox library is a .db and a Serato one is a directory. Raises on
|
||||
# an unrecognised or unparseable file; only commit once it has parsed.
|
||||
@@ -103,6 +121,10 @@ class AppState:
|
||||
# library gets corrupted. Only close once the new one has parsed, so a
|
||||
# failed open leaves the current library intact.
|
||||
previous = self.adapter
|
||||
# Leaving a library discards its unsaved edits (the UI has confirmed), so
|
||||
# a stem conversion's parked originals go back under their own names.
|
||||
if self.pending is not None and self.pending.items:
|
||||
self.pending.restore()
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
@@ -127,6 +149,18 @@ class AppState:
|
||||
label=Path(str(path)).name,
|
||||
sidecar=not getattr(driver, "removable", False),
|
||||
)
|
||||
# A crash may have left converted tracks mid-lifecycle: settle them from
|
||||
# what the SAVED library says, BEFORE the missing-files check — a parked
|
||||
# original is exactly what that check would report as missing.
|
||||
from .stems.pending import Pending
|
||||
|
||||
self.pending = Pending(self.library_id)
|
||||
self.recovery = None
|
||||
if self.pending.items:
|
||||
self.recovery = self.pending.recover(lambda item: adapter.track(item["new_id"]) is not None)
|
||||
# Started after the saved mapping is applied, so a volume that mapping
|
||||
# already fixes is not asked about.
|
||||
self.relocation = RelocationCheck(adapter)
|
||||
# Version history: record an "as I found it" baseline (deduped, so
|
||||
# re-opening an unchanged library is a no-op). Best-effort.
|
||||
history.ensure_baseline(path)
|
||||
@@ -139,6 +173,10 @@ class AppState:
|
||||
cannot restore from.
|
||||
"""
|
||||
assert self.adapter is not None and self.path is not None
|
||||
with self.mutation:
|
||||
return self._save()
|
||||
|
||||
def _save(self):
|
||||
outcome = self.adapter.save()
|
||||
# Not every platform is versioned. A library that is more than one file
|
||||
# has no single blob that IS the library, and it says so through its
|
||||
@@ -149,8 +187,30 @@ class AppState:
|
||||
commit = history.commit(
|
||||
self.path, outcome.snapshot, outcome.summary, __version__
|
||||
)
|
||||
# The swap is now on disk: what it replaced can go. After the library
|
||||
# write, so a failed save deletes nothing; here rather than in the save
|
||||
# route, because import and path remap save too.
|
||||
if self.pending is not None and self.pending.swapped():
|
||||
renames = self.pending.commit()
|
||||
if renames and self.library_id:
|
||||
from . import exports
|
||||
|
||||
exports.retarget(self.library_id, renames)
|
||||
return outcome, commit
|
||||
|
||||
def discard(self) -> None:
|
||||
"""Drop every unsaved edit: the library re-reads itself from disk.
|
||||
|
||||
Through the adapter's own `reload`, NOT `open` — reopening would start a
|
||||
new missing-files check and forget this session's relocation answers,
|
||||
which are not edits and survive a reload (the store keeps them).
|
||||
"""
|
||||
assert self.adapter is not None
|
||||
with self.mutation:
|
||||
if self.pending is not None and self.pending.items:
|
||||
self.pending.restore()
|
||||
self.adapter.reload()
|
||||
|
||||
|
||||
STATE = AppState()
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ from typing import Protocol, runtime_checkable
|
||||
from .capabilities import Capabilities
|
||||
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
|
||||
from .pathmap import PathMapping
|
||||
from .relocate import PathGroup
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -72,6 +73,49 @@ 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)
|
||||
class StemSwap:
|
||||
"""Put a converted stem file into the library in place of — or beside — a track.
|
||||
|
||||
The conversion itself (separation, encoding, file moves) is not the
|
||||
adapter's business; this is only the library side, and it arrives once the
|
||||
file is finished and verified.
|
||||
|
||||
* `mode` "repoint": the track's entry now names the stem file and keeps
|
||||
its playlists, prep and history — its id changes with its location.
|
||||
"add": a NEW entry for the stem file, copying the track's prep and
|
||||
metadata; the original entry stays.
|
||||
* `original_audio` is where the original's audio bytes are RIGHT NOW. In
|
||||
Replace mode that is its parked name, not its old one — a platform whose
|
||||
clock depends on the file (an MP3's header) must read it there, and
|
||||
must not look at the old path, which no longer holds it.
|
||||
* `bit_rate` (bps per stream), `duration` (seconds) and `size` (bytes)
|
||||
describe the stem file, for the library's own fields.
|
||||
"""
|
||||
|
||||
track_id: str
|
||||
stem_path: Path
|
||||
mode: str # "repoint" | "add"
|
||||
original_audio: Path | None
|
||||
bit_rate: int
|
||||
duration: float
|
||||
size: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class StemSwapResult:
|
||||
#: Old track id -> the id of the entry that now names the stem file.
|
||||
renamed: dict[str, str] = field(default_factory=dict)
|
||||
#: New id -> hotcue slots whose position fell before the stem file's start
|
||||
#: and were moved to 0 (a platform time-base shift can push one there).
|
||||
clamped: dict[str, list[int]] = field(default_factory=dict)
|
||||
|
||||
|
||||
class AdapterError(Exception):
|
||||
@@ -134,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.
|
||||
@@ -142,6 +192,13 @@ class LibraryAdapter(Protocol):
|
||||
# `capabilities().tracks.removable`.
|
||||
def remove_tracks(self, track_ids: list[str]) -> int: ...
|
||||
|
||||
# Swap converted stem files into the library (see `StemSwap`), all at once:
|
||||
# every swap is validated before any is applied, so a clash leaves the
|
||||
# library untouched. Gated on `capabilities().tracks.stem_convertible`.
|
||||
# `add_to_playlist` receives the entries "add" mode creates, in order.
|
||||
def apply_stem_swaps(self, swaps: list["StemSwap"], *,
|
||||
add_to_playlist: str | None = None) -> "StemSwapResult": ...
|
||||
|
||||
# ---- commands: track metadata / art ---------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
|
||||
@@ -160,6 +217,9 @@ class LibraryAdapter(Protocol):
|
||||
name: str | None = None,
|
||||
) -> TrackCues: ...
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: ...
|
||||
# `color` is "#RRGGBB" from `capabilities().cues.palette`, or None for the
|
||||
# platform's uncoloured cue. Any other cue command keeps a slot's colour.
|
||||
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues: ...
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
|
||||
|
||||
@@ -176,6 +236,12 @@ class LibraryAdapter(Protocol):
|
||||
# ---- audio / paths ---------------------------------------------------
|
||||
def audio_path(self, track_id: str) -> Path | None: ...
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None: ...
|
||||
# The open-time missing-files check (`core/relocate.py`): the stored volumes
|
||||
# in which NO track resolves, and the mappings the user confirmed for them —
|
||||
# session-only, applied beneath the saved mapping. An adapter that does not
|
||||
# take part returns no groups, so its library is never checked.
|
||||
def unresolved_path_groups(self) -> list[PathGroup]: ...
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None: ...
|
||||
def path_prefix_suggestions(self) -> dict: ...
|
||||
def remap_preview(self, mapping: PathMapping) -> dict: ...
|
||||
# {old track id: new track id}; ids may change because a Traktor id IS its path.
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Waveform analysis kept on the export's own drive, so a re-export decodes only
|
||||
what changed.
|
||||
|
||||
Decoding is the slow part of a Pioneer export (~1.5 s a track, where copying a
|
||||
track to a stick is well under a second), so skipping unchanged copies alone
|
||||
would leave most of a re-export's time in place. What is cached is the
|
||||
MEASUREMENT (`waveform.Analysis`), not any platform's tags: every Pioneer target
|
||||
turns the same measurement into its own files, and the Rekordbox Library target
|
||||
names its analysis folders after a fresh UUID each time, so reusing old ANLZ
|
||||
files by path could never have worked there.
|
||||
|
||||
## Where, and keyed by what
|
||||
|
||||
It lives on the destination (`.konduktor-cache/`), beside the manifest, for the
|
||||
manifest's reason: it describes that drive, and should travel, be cloned or be
|
||||
wiped with it. An entry is keyed by the SOURCE file's path, size and mtime —
|
||||
the same facts the runner uses to decide a copy is unchanged — so an edited
|
||||
track is re-measured exactly when it is re-copied, and the same stick plugged
|
||||
into another computer (other source paths) simply misses and re-decodes.
|
||||
|
||||
`waveform.ANALYSIS_VERSION` is part of every key: change what `analyse()`
|
||||
measures without bumping it and every re-export serves the old measurement.
|
||||
|
||||
Best-effort in both directions: an unreadable entry is a miss, and a failed
|
||||
store is logged, never fatal — the cache can cost time, never an export.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import waveform
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: The folder, relative to the export's destination.
|
||||
CACHE_DIR = ".konduktor-cache"
|
||||
|
||||
|
||||
def fingerprint(source: Path | str, size: int, mtime_ns: int) -> str:
|
||||
"""The identity of one version of one source file."""
|
||||
text = f"{waveform.ANALYSIS_VERSION}|{source}|{size}|{mtime_ns}"
|
||||
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:24]
|
||||
|
||||
|
||||
class AnalysisCache:
|
||||
def __init__(self, folder: Path):
|
||||
self.folder = Path(folder)
|
||||
|
||||
def _path(self, key: str, lead: float, n_columns: int) -> Path:
|
||||
# One source can be measured with different leads (a target's clock
|
||||
# offset), so each variant is its own entry under the same key prefix.
|
||||
return self.folder / f"{key}-{int(round(lead * 1_000_000))}-{n_columns}.npz"
|
||||
|
||||
def analyse(self, audio: Path, key: str, *, lead: float = 0.0,
|
||||
n_columns: int = 400) -> waveform.Analysis | None:
|
||||
"""`waveform.analyse(audio, …)`, served from the cache when it can be."""
|
||||
path = self._path(key, lead, n_columns)
|
||||
hit, value = self._load(path, n_columns)
|
||||
if hit:
|
||||
return value
|
||||
value = waveform.analyse(audio, n_columns=n_columns, lead=lead)
|
||||
self._store(path, value)
|
||||
return value
|
||||
|
||||
def prune(self, keep: set[str]) -> None:
|
||||
"""Drop every entry whose key is not in `keep`."""
|
||||
try:
|
||||
for entry in self.folder.iterdir():
|
||||
if entry.name.split("-", 1)[0] not in keep:
|
||||
entry.unlink()
|
||||
self.folder.rmdir() # only succeeds when nothing is left
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def clear(self) -> None:
|
||||
self.prune(set())
|
||||
|
||||
# ---- storage -----------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _load(path: Path, n_columns: int) -> tuple[bool, waveform.Analysis | None]:
|
||||
try:
|
||||
with np.load(path, allow_pickle=False) as data:
|
||||
if bool(data["undecodable"]):
|
||||
# Remembered too: a file nothing can decode would otherwise
|
||||
# be retried, slowly, on every export.
|
||||
return True, None
|
||||
rms = data["rms"]
|
||||
if len(rms) != n_columns:
|
||||
return False, None
|
||||
return True, waveform.Analysis(
|
||||
columns=waveform.Columns(
|
||||
rms=rms, brightness=data["brightness"],
|
||||
duration=float(data["duration"]),
|
||||
),
|
||||
frames=waveform.Frames(bands=data["bands"], duration=float(data["duration"])),
|
||||
)
|
||||
except FileNotFoundError:
|
||||
return False, None
|
||||
except Exception as ex: # noqa: BLE001 — a damaged entry is a miss
|
||||
log.debug("ignoring unreadable analysis cache entry %s: %s", path, ex)
|
||||
return False, None
|
||||
|
||||
@staticmethod
|
||||
def _store(path: Path, value: waveform.Analysis | None) -> None:
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
partial = path.with_name(path.name + ".partial")
|
||||
with partial.open("wb") as out:
|
||||
if value is None:
|
||||
np.savez_compressed(out, undecodable=np.array(True))
|
||||
else:
|
||||
# Full precision: a cached export must write the same bytes
|
||||
# a fresh one would.
|
||||
np.savez_compressed(
|
||||
out, undecodable=np.array(False),
|
||||
rms=value.columns.rms, brightness=value.columns.brightness,
|
||||
bands=value.frames.bands, duration=np.array(value.columns.duration),
|
||||
)
|
||||
os.replace(partial, path)
|
||||
except OSError as ex:
|
||||
log.warning("could not cache the analysis of %s: %s", path.name, ex)
|
||||
@@ -63,6 +63,12 @@ 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
|
||||
# The audio files this library can hold, as lower-case suffixes. What a
|
||||
# browsed folder offers to add — a file the library would refuse, or that
|
||||
# the DJ app cannot play, is not worth listing as addable.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""The colour a cue is SHOWN in — the one backend definition.
|
||||
|
||||
A stored colour wins; otherwise the cue's type decides. That is Traktor's own
|
||||
convention (it stores a colour only on a grid marker's white companion cue and
|
||||
draws every other cue from its type) and it is exactly what Konduktor's deck and
|
||||
table draw. **Keep in lockstep with `TYPE_COLORS` in `frontend/src/lib/cues.ts`.**
|
||||
|
||||
Why the backend needs it: an export to a platform that stores a colour per cue
|
||||
(rekordbox) must write what the user SEES. Writing "no colour" hands the choice
|
||||
to the target, which draws its own defaults — rekordbox showed green cues and
|
||||
orange loops where Konduktor and Traktor show blue and green.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .model import CuePoint
|
||||
|
||||
TYPE_COLORS = {
|
||||
"cue": "#4D94FF", # blue
|
||||
"fade_in": "#FF9A3D", # orange
|
||||
"fade_out": "#FF9A3D", # orange
|
||||
"load": "#FFD23D", # yellow
|
||||
"loop": "#3DDC84", # green
|
||||
}
|
||||
MEMORY_COLOR = "#9AA1B2" # grey
|
||||
|
||||
|
||||
def effective_color(cue: CuePoint) -> str:
|
||||
"""`#RRGGBB` — the stored colour, or the type's."""
|
||||
if cue.color:
|
||||
return cue.color.upper()
|
||||
if cue.role == "memory":
|
||||
return MEMORY_COLOR
|
||||
return TYPE_COLORS.get(cue.type, MEMORY_COLOR)
|
||||
@@ -95,11 +95,18 @@ class EditJournal:
|
||||
"""Follow a track whose id changed (a path remap rewrites LOCATIONs, and
|
||||
the id is derived from the location). Without this, edits made earlier in
|
||||
the session would silently stop syncing to the file."""
|
||||
if old_id == new_id:
|
||||
self.retarget_many({old_id: new_id})
|
||||
|
||||
def retarget_many(self, renames: dict[str, str]) -> None:
|
||||
"""`retarget` for a whole remap AT ONCE. One at a time would be wrong
|
||||
for a chain — A moving to B's old path while B moves on to C would
|
||||
carry A's edits to C along with B's."""
|
||||
renames = {o: n for o, n in renames.items() if o != n}
|
||||
if not renames:
|
||||
return
|
||||
for i, c in enumerate(self.changes):
|
||||
if c.target == old_id and c.scope in ("track", "cue", "grid", "lock"):
|
||||
self.changes[i] = Change(c.scope, c.op, new_id, c.detail, c.before, c.after)
|
||||
if c.target in renames and c.scope in ("track", "cue", "grid", "lock"):
|
||||
self.changes[i] = Change(c.scope, c.op, renames[c.target], c.detail, c.before, c.after)
|
||||
|
||||
# ---- the version-history message --------------------------------------
|
||||
def summary(self, extra_tracks: set[str] | None = None) -> str:
|
||||
@@ -127,6 +134,9 @@ class EditJournal:
|
||||
n_removed = len(self.removed_tracks())
|
||||
if n_removed:
|
||||
parts.append(f"removed {tracks(n_removed)} from the collection")
|
||||
n_stems = len({c.target for c in self.changes if c.scope == "stem" and c.target})
|
||||
if n_stems:
|
||||
parts.append(f"converted {tracks(n_stems)} to stems")
|
||||
|
||||
# --- track metadata + cover art (already counted per-track) ---
|
||||
n_meta = len(self.edited_tracks() | (extra_tracks or set()))
|
||||
|
||||
@@ -29,11 +29,14 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Protocol, runtime_checkable
|
||||
from typing import TYPE_CHECKING, Callable, Protocol, runtime_checkable
|
||||
|
||||
from .capabilities import Capabilities
|
||||
from .model import Track, TrackCues
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .analysis_cache import AnalysisCache
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportTrack:
|
||||
@@ -45,6 +48,25 @@ class ExportTrack:
|
||||
#: write should be discovering.
|
||||
destination: Path
|
||||
cues: TrackCues | None = None
|
||||
#: The cover as the SOURCE library serves it — `(bytes, mime)` from
|
||||
#: `LibraryAdapter.cover_art` — or None. Carried rather than re-read from the
|
||||
#: copied file, because a library's art is not always embedded in the audio
|
||||
#: (rekordbox keeps its own copy under `share/`).
|
||||
art: tuple[bytes, str] | None = None
|
||||
#: The source file's identity (`analysis_cache.fingerprint`), and the cache
|
||||
#: on the destination drive — both set by the runner, so a re-export does
|
||||
#: not decode an unchanged track again. Either may be None.
|
||||
fingerprint: str | None = None
|
||||
analysis_cache: "AnalysisCache | None" = field(default=None, repr=False)
|
||||
|
||||
def waveform(self, *, lead: float = 0.0):
|
||||
"""`waveform.analyse()` of the copied audio — the call every exporter that
|
||||
measures audio makes, so all of them share the cache."""
|
||||
from . import waveform
|
||||
|
||||
if self.analysis_cache is not None and self.fingerprint:
|
||||
return self.analysis_cache.analyse(self.destination, self.fingerprint, lead=lead)
|
||||
return waveform.analyse(self.destination, lead=lead)
|
||||
|
||||
@property
|
||||
def source_id(self) -> str:
|
||||
@@ -74,6 +96,13 @@ 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, and — for a per-track loop —
|
||||
#: `step` of `of`, which drives the progress 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[..., None] = field(
|
||||
default=lambda message, step=None, of=None: None, repr=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -105,6 +134,16 @@ class LibraryExporter(Protocol):
|
||||
platform: str
|
||||
#: What the written library file is called, e.g. "collection.nml".
|
||||
library_filename: str
|
||||
#: Where the target sits in the export dialog's list, lowest first. Optional
|
||||
#: (unset sorts last): a stick's formats lead, a computer library trails.
|
||||
#: The name the export dialog shows. Optional: a target named after its
|
||||
#: platform omits it and the driver's `display_name` is used. Needed where
|
||||
#: one platform has two targets ("Rekordbox Library" / "Rekordbox Export").
|
||||
#: The library is only found when the destination is a DRIVE'S ROOT — a
|
||||
#: player looks for it there and nowhere else. Several targets can share one
|
||||
#: destination, so this is a warning the UI raises, not a refusal: the other
|
||||
#: targets in the same export are still perfectly valid in any folder.
|
||||
drive_root: bool = False
|
||||
|
||||
def capabilities(self) -> Capabilities:
|
||||
"""What this target can represent — STATIC, with no library to read."""
|
||||
|
||||
@@ -31,6 +31,7 @@ from pathlib import Path
|
||||
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
|
||||
from .model import PlaylistNode, Track, TrackCues
|
||||
from .places import is_hidden
|
||||
from .stem_file import is_stem_file
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -59,7 +60,8 @@ def _bpm(tags) -> float | None:
|
||||
|
||||
def read_track(path: Path) -> Track:
|
||||
"""Project one audio file. Never raises: an unreadable tag is an untitled track."""
|
||||
track = Track(id=str(path), title=path.stem, filepath=str(path))
|
||||
track = Track(id=str(path), title=path.stem, filepath=str(path),
|
||||
media_kind="stem" if is_stem_file(path) else "audio")
|
||||
try:
|
||||
import mutagen
|
||||
|
||||
@@ -112,7 +114,7 @@ def capabilities_for(folder: Path) -> Capabilities:
|
||||
platform="folder",
|
||||
writable=False,
|
||||
readonly_cause="not_in_library",
|
||||
tracks=TrackCapabilities(editable_fields=[], artwork=False),
|
||||
tracks=TrackCapabilities(editable_fields=[], artwork=False, media_kinds=["audio", "stem"]),
|
||||
save=SaveCapabilities(
|
||||
app_name="Files",
|
||||
library_label=folder.name or str(folder),
|
||||
|
||||
@@ -41,6 +41,10 @@ class Track(BaseModel):
|
||||
producer: str | None = None
|
||||
mix: str | None = None
|
||||
comment: str | None = None
|
||||
# A second free-text comment. Traktor's "Comment 2", which it keeps only in
|
||||
# the collection (`INFO@RATING` — not the star rating, that is RANKING) and
|
||||
# never writes into the audio file.
|
||||
comment2: str | None = None
|
||||
bpm: float | None = None
|
||||
# The platform's own display string, shown verbatim ("10m", "8A", "Am").
|
||||
key: str | None = None
|
||||
@@ -51,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
|
||||
@@ -210,6 +214,11 @@ class PlatformOption(BaseModel):
|
||||
found: int = 0
|
||||
#: The library lives on a plugged-in drive, so `found` changes between calls.
|
||||
removable: bool = False
|
||||
#: As an export TARGET: its library is only found at a drive's root.
|
||||
drive_root: bool = False
|
||||
#: As an export TARGET: its library is only ever read on a computer, never
|
||||
#: from a drive — so it does nothing beside a stick format.
|
||||
computer_only: bool = False
|
||||
|
||||
|
||||
class RemapSample(BaseModel):
|
||||
@@ -224,6 +233,10 @@ class RemapPreview(BaseModel):
|
||||
matched: int # how many match the `from` prefix
|
||||
existing: int # of matched, how many exist at the `to` target
|
||||
samples: list[RemapSample] = []
|
||||
# Target paths more than one track would land on. Non-zero means the remap
|
||||
# would be refused: two entries sharing a path corrupt the library.
|
||||
collisions: int = 0
|
||||
collision_samples: list[str] = []
|
||||
|
||||
|
||||
class PrefixGroup(BaseModel):
|
||||
@@ -234,3 +247,43 @@ class PrefixGroup(BaseModel):
|
||||
class PrefixSuggestions(BaseModel):
|
||||
primary: str # best guess for the `from` prefix (largest group)
|
||||
groups: list[PrefixGroup] = [] # alternatives, ranked by count
|
||||
|
||||
|
||||
class RelocationCandidate(BaseModel):
|
||||
"""One place a volume's tracks were found, as a mapping the user can pick."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
from_: str = Field(alias="from")
|
||||
to: str
|
||||
found: int # of the volume's tracks, how many exist under this mapping
|
||||
|
||||
|
||||
class RelocationVolume(BaseModel):
|
||||
"""A stored volume in which NO track resolves, and where its tracks are now.
|
||||
|
||||
`ambiguous` means more than one candidate resolves most of the volume (a
|
||||
drive and its backup clone): the user chooses, nothing is preselected.
|
||||
"""
|
||||
|
||||
label: str # how the library names the place, e.g. Traktor's "X:"
|
||||
root: str # the stored OS-path prefix
|
||||
total: int
|
||||
status: Literal["found", "ambiguous", "not_found"]
|
||||
candidates: list[RelocationCandidate] = []
|
||||
|
||||
|
||||
class Relocation(BaseModel):
|
||||
"""The open-time missing-files check, pending until the user answers it.
|
||||
|
||||
`scanning` while the search is still running; afterwards `volumes` is empty
|
||||
when there is nothing to ask — every volume resolves, the platform does not
|
||||
take part, or the user has already answered for this open.
|
||||
"""
|
||||
|
||||
scanning: bool = False
|
||||
volumes: list[RelocationVolume] = []
|
||||
|
||||
|
||||
class RelocationApplied(BaseModel):
|
||||
mappings: int
|
||||
tracks: int # how many tracks the applied mappings resolve
|
||||
@@ -0,0 +1,127 @@
|
||||
"""What an MP3's first frame says about where its audio starts.
|
||||
|
||||
A gapless MP3 opens with a HEADER FRAME — a valid MPEG frame whose payload is a
|
||||
`Xing` (VBR) or `Info` (CBR) tag instead of audio — often followed by a LAME
|
||||
extension recording the encoder delay. A gapless decoder (FFmpeg, libsndfile's
|
||||
mpg123, CoreAudio) skips that frame and trims `encoder delay + 529` samples of
|
||||
start padding; a naive one decodes the frame as silence and trims nothing. Where
|
||||
a platform's clock sits relative to Konduktor's decoded time base therefore
|
||||
depends on these facts, per file — which is why they are read here, once, rather
|
||||
than assumed per format.
|
||||
|
||||
Format knowledge, not platform knowledge: this reads bytes and says what is
|
||||
there. What a platform DOES with them lives in that platform's `timebase`.
|
||||
|
||||
Two things are easy to get wrong, and both were got wrong once:
|
||||
* the first frame comes AFTER the ID3v2 tag, which can be megabytes of cover
|
||||
art — a check that only looks at the start of the file sees no header;
|
||||
* the tag sits at a fixed offset after the side information, whose size
|
||||
depends on the MPEG version and channel mode.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
#: The mp3 decoder delay a gapless decoder trims on top of the encoder's.
|
||||
DECODER_DELAY = 529
|
||||
#: Encoder strings whose LAME-style delay field FFmpeg (and mpg123) honour.
|
||||
_TRUSTED_ENCODERS = (b"LAME", b"Lavf", b"Lavc")
|
||||
#: How far past the ID3 tag to look for the first frame (junk, padding).
|
||||
_SCAN = 64 * 1024
|
||||
|
||||
_RATES = {3: (44100, 48000, 32000), 2: (22050, 24000, 16000), 0: (11025, 12000, 8000)}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Mp3Start:
|
||||
sample_rate: int
|
||||
#: Samples in one frame: 1152 for MPEG-1 Layer III, 576 for MPEG-2/2.5.
|
||||
samples_per_frame: int
|
||||
#: The first frame is a Xing/Info/VBRI tag, not audio.
|
||||
header_frame: bool
|
||||
#: Encoder delay from a LAME-style tag a gapless decoder trusts, else None.
|
||||
encoder_delay: int | None
|
||||
|
||||
@property
|
||||
def trimmed(self) -> int:
|
||||
"""Samples of start padding a gapless decoder removes (0 without a
|
||||
trusted delay field: it has nothing to trim by)."""
|
||||
return 0 if self.encoder_delay is None else self.encoder_delay + DECODER_DELAY
|
||||
|
||||
|
||||
def _id3_end(head: bytes) -> int:
|
||||
if head[:3] != b"ID3" or len(head) < 10:
|
||||
return 0
|
||||
size = ((head[6] & 127) << 21) | ((head[7] & 127) << 14) | ((head[8] & 127) << 7) | (head[9] & 127)
|
||||
footer = 10 if head[5] & 0x10 else 0
|
||||
return 10 + size + footer
|
||||
|
||||
|
||||
def _frame_header(b: bytes, i: int):
|
||||
"""(version bits, sample rate, mono) if a Layer III frame header starts at i."""
|
||||
if i + 4 > len(b) or b[i] != 0xFF or (b[i + 1] & 0xE0) != 0xE0:
|
||||
return None
|
||||
version = (b[i + 1] >> 3) & 3
|
||||
layer = (b[i + 1] >> 1) & 3
|
||||
bitrate = b[i + 2] >> 4
|
||||
rate = (b[i + 2] >> 2) & 3
|
||||
if version == 1 or layer != 1 or bitrate in (0, 15) or rate == 3:
|
||||
return None
|
||||
return version, _RATES[version][rate], (b[i + 3] >> 6) == 3
|
||||
|
||||
|
||||
def parse(data: bytes, audio_start: int = 0) -> Mp3Start | None:
|
||||
"""Read the first frame of `data`, whose audio starts at `audio_start`
|
||||
(after any ID3v2 tag). None if no Layer III frame is found."""
|
||||
for i in range(audio_start, min(len(data) - 4, audio_start + _SCAN)):
|
||||
hdr = _frame_header(data, i)
|
||||
if hdr is None:
|
||||
continue
|
||||
version, rate, mono = hdr
|
||||
mpeg1 = version == 3
|
||||
spf = 1152 if mpeg1 else 576
|
||||
side = (17 if mono else 32) if mpeg1 else (9 if mono else 17)
|
||||
x = i + 4 + side
|
||||
tag = data[x:x + 4]
|
||||
if tag in (b"Xing", b"Info"):
|
||||
flags = int.from_bytes(data[x + 4:x + 8], "big")
|
||||
lame = x + 8 + (4 if flags & 1 else 0) + (4 if flags & 2 else 0) \
|
||||
+ (100 if flags & 4 else 0) + (4 if flags & 8 else 0)
|
||||
delay = None
|
||||
if data[lame:lame + 4] in _TRUSTED_ENCODERS and len(data) >= lame + 24:
|
||||
d = data[lame + 21:lame + 24]
|
||||
delay = (d[0] << 4) | (d[1] >> 4)
|
||||
return Mp3Start(rate, spf, True, delay)
|
||||
if data[i + 36:i + 40] == b"VBRI": # Fraunhofer's tag, always at 32 + 4
|
||||
return Mp3Start(rate, spf, True, None)
|
||||
return Mp3Start(rate, spf, False, None)
|
||||
return None
|
||||
|
||||
|
||||
@lru_cache(maxsize=16384)
|
||||
def _read_cached(path: str, size: int, mtime_ns: int) -> Mp3Start | None:
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(10)
|
||||
start = _id3_end(head)
|
||||
f.seek(start)
|
||||
# Enough for the first frame and a scan past junk before it.
|
||||
return parse(f.read(_SCAN + 2048), 0)
|
||||
|
||||
|
||||
def read(path: Path | str | None) -> Mp3Start | None:
|
||||
"""`parse` a file on disk; None when it is missing, unreadable or no MP3.
|
||||
|
||||
Cached per (path, size, mtime), so a file that appears later — a drive
|
||||
plugged in mid-session — or is replaced is read afresh, and a missing one is
|
||||
never remembered as headerless.
|
||||
"""
|
||||
if not path:
|
||||
return None
|
||||
try:
|
||||
st = os.stat(path)
|
||||
return _read_cached(str(path), st.st_size, st.st_mtime_ns)
|
||||
except OSError:
|
||||
return None
|
||||
@@ -0,0 +1,106 @@
|
||||
"""The priming an MP4/M4A's edit list tells a decoder to skip.
|
||||
|
||||
An AAC encoder emits `priming` samples of lead-in before the audio proper —
|
||||
1024 from FFmpeg's `aac`, 2112 from Apple's — and records it as the
|
||||
`media_time` of the audio track's edit list (`moov/trak/edts/elst`). A decoder
|
||||
that honours the edit list (FFmpeg, CoreAudio, Traktor) starts the audio after
|
||||
it; one that ignores it (rekordbox) plays the priming as audio. What a platform
|
||||
does with it lives in that platform's `timebase`; this only reads the box.
|
||||
|
||||
Only box headers are read and `mdat` is seeked past, so `moov` at the END of a
|
||||
file (FFmpeg's default, and every commercial stem file) costs a few reads.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import struct
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
_CONTAINERS = {b"moov", b"trak", b"mdia", b"edts"}
|
||||
|
||||
|
||||
def _boxes(f, start: int, end: int):
|
||||
"""(type, payload offset, payload end) for each box in [start, end)."""
|
||||
pos = start
|
||||
while pos + 8 <= end:
|
||||
f.seek(pos)
|
||||
head = f.read(8)
|
||||
if len(head) < 8:
|
||||
return
|
||||
size, kind = struct.unpack(">I4s", head)
|
||||
body = pos + 8
|
||||
if size == 1:
|
||||
size = struct.unpack(">Q", f.read(8))[0]
|
||||
body = pos + 16
|
||||
elif size == 0:
|
||||
size = end - pos
|
||||
if size < 8:
|
||||
return
|
||||
yield kind, body, min(pos + size, end)
|
||||
pos += size
|
||||
|
||||
|
||||
def _audio_track_priming(f, trak_start: int, trak_end: int) -> tuple[int, int] | None:
|
||||
"""(media_time, media timescale) of one trak if it is audio, else None."""
|
||||
handler = timescale = None
|
||||
media_time = 0 # no edit list: nothing to skip
|
||||
for kind, body, end in _boxes(f, trak_start, trak_end):
|
||||
if kind == b"mdia":
|
||||
for k2, b2, e2 in _boxes(f, body, end):
|
||||
f.seek(b2)
|
||||
if k2 == b"hdlr":
|
||||
handler = f.read(12)[8:12]
|
||||
elif k2 == b"mdhd":
|
||||
version = f.read(1)[0]
|
||||
f.seek(b2 + (20 if version == 1 else 12))
|
||||
timescale = struct.unpack(">I", f.read(4))[0]
|
||||
elif kind == b"edts":
|
||||
for k2, b2, e2 in _boxes(f, body, end):
|
||||
if k2 != b"elst":
|
||||
continue
|
||||
f.seek(b2)
|
||||
version = f.read(1)[0]
|
||||
f.read(3)
|
||||
count = struct.unpack(">I", f.read(4))[0]
|
||||
for _ in range(count):
|
||||
if version == 1:
|
||||
_dur, mt = struct.unpack(">Qq", f.read(16))
|
||||
else:
|
||||
_dur, mt = struct.unpack(">Ii", f.read(8))
|
||||
f.read(4) # media rate
|
||||
if mt >= 0: # -1 is an EMPTY edit (a delay), not a skip
|
||||
media_time = mt
|
||||
break
|
||||
if handler != b"soun" or not timescale:
|
||||
return None
|
||||
return media_time, timescale
|
||||
|
||||
|
||||
@lru_cache(maxsize=16384)
|
||||
def _read_cached(path: str, size: int, mtime_ns: int) -> float | None:
|
||||
with open(path, "rb") as f:
|
||||
for kind, body, end in _boxes(f, 0, size):
|
||||
if kind != b"moov":
|
||||
continue
|
||||
for k2, b2, e2 in _boxes(f, body, end):
|
||||
if k2 == b"trak":
|
||||
found = _audio_track_priming(f, b2, e2)
|
||||
if found is not None: # the FIRST audio track: a stem's master
|
||||
media_time, timescale = found
|
||||
return media_time / timescale
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def priming_seconds(path: Path | str | None) -> float | None:
|
||||
"""Seconds of priming the first audio track's edit list skips (0.0 when it
|
||||
has no edit list); None when the file is missing or not a readable MP4.
|
||||
Cached per (path, size, mtime), like `mp3_gapless.read`."""
|
||||
if not path:
|
||||
return None
|
||||
try:
|
||||
st = os.stat(path)
|
||||
return _read_cached(str(path), st.st_size, st.st_mtime_ns)
|
||||
except (OSError, struct.error, IndexError):
|
||||
return None
|
||||
@@ -121,6 +121,18 @@ def is_boot_volume(path: Path) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def is_drive_root(path: Path) -> bool:
|
||||
"""Whether `path` is the root of a mounted drive — `/Volumes/STICK`, `E:\\`.
|
||||
|
||||
What a OneLibrary export needs, since a CDJ looks for `PIONEER/` there and
|
||||
nowhere else. A folder that does not exist yet is not one.
|
||||
"""
|
||||
try:
|
||||
return os.path.ismount(Path(path).expanduser())
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def volumes(*, include_boot: bool = False) -> list[Path]:
|
||||
"""Mounted volumes, newest-mounted order not guaranteed. Sorted by name."""
|
||||
found = [v for v in mount_points() if include_boot or not is_boot_volume(v)]
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Finding where a library's audio went: the search behind auto path remapping.
|
||||
|
||||
A library stores absolute paths, and they go stale in ways a DJ does not think
|
||||
of as "moving" anything: the collection on an SSD was built on Windows where the
|
||||
drive was `X:`, and on a Mac the same drive is `/Volumes/MiniSSD`. Every track
|
||||
then reads as missing, though nothing moved. That is what this module fixes,
|
||||
and ALL it fixes — a prefix changed, the layout underneath did not. A user who
|
||||
reorganised their folders needs a relocate-by-filename feature, which this is
|
||||
not.
|
||||
|
||||
The search is by SAMPLING, never by walking a drive: a drive can hold hundreds
|
||||
of thousands of files, and a stat of a path that is not there costs next to
|
||||
nothing. For each group of tracks that share a stored root, a sample of tracks
|
||||
is tried against each candidate root (the mounted drives, the home folder),
|
||||
dropping leading folders one at a time, and the roots that resolve them are
|
||||
counted. The winner is then verified against the WHOLE group, because a count
|
||||
the user is asked to confirm should be the real one.
|
||||
|
||||
Which groups to search is the adapter's business, not this module's: only the
|
||||
adapter knows how its stored paths resolve, including through a mapping the
|
||||
user already saved. It hands over the groups in which NO track resolves — the
|
||||
threshold is "none", so a volume missing a few deleted files never prompts.
|
||||
|
||||
Two candidates that both resolve most of a group (a drive and its backup clone)
|
||||
are reported as AMBIGUOUS rather than ranked: which one the user meant is not a
|
||||
question sample counts can answer, and a wrong guess would silently play and
|
||||
tag files on the wrong drive.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .pathmap import PathMapping
|
||||
|
||||
#: Tracks sampled per group. Enough that a drive holding a partial copy loses
|
||||
#: clearly to one holding all of it; few enough that a group costs milliseconds.
|
||||
SAMPLE = 50
|
||||
|
||||
#: How many leading folders may be dropped from a stored path. Covers
|
||||
#: `/Users/<name>/Music/<library>`-deep moves with room to spare.
|
||||
MAX_DROP = 8
|
||||
|
||||
#: A runner-up resolving at least this share of the winner's tracks makes the
|
||||
#: group ambiguous.
|
||||
AMBIGUOUS_SHARE = 0.5
|
||||
|
||||
_SEP = re.compile(r"[\\/]")
|
||||
|
||||
|
||||
@dataclass
|
||||
class PathGroup:
|
||||
"""Tracks whose stored paths share a root the library names as one place.
|
||||
|
||||
`root` is the OS-path prefix every path starts with (`X:`, `/Volumes/SSD`,
|
||||
`/`); `label` is how the library itself names that place, for the UI.
|
||||
`paths` are the STORED paths — before any mapping.
|
||||
"""
|
||||
|
||||
label: str
|
||||
root: str
|
||||
paths: list[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Candidate:
|
||||
"""A mapping that resolves some of a group, with how many it resolves."""
|
||||
|
||||
mapping: PathMapping
|
||||
found: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Proposal:
|
||||
"""What the search concluded about one group."""
|
||||
|
||||
label: str
|
||||
root: str
|
||||
total: int
|
||||
#: Best first. Empty when nothing was found.
|
||||
candidates: list[Candidate] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def status(self) -> str:
|
||||
if not self.candidates:
|
||||
return "not_found"
|
||||
if len(self.candidates) > 1:
|
||||
return "ambiguous"
|
||||
return "found"
|
||||
|
||||
|
||||
def _split(path: str, root: str) -> tuple[list[str], str] | None:
|
||||
"""A stored path's folders below `root`, and its filename."""
|
||||
if not path.startswith(root):
|
||||
return None
|
||||
segs = [s for s in _SEP.split(path[len(root):]) if s]
|
||||
if not segs:
|
||||
return None
|
||||
return segs[:-1], segs[-1]
|
||||
|
||||
|
||||
def _from_prefix(root: str, path: str, dropped: list[str]) -> str:
|
||||
"""The stored prefix a mapping must replace: `root` plus the dropped folders,
|
||||
spelled with the separator the stored path uses, so it matches it."""
|
||||
if not dropped:
|
||||
return root
|
||||
rest = path[len(root):]
|
||||
sep = "\\" if "\\" in rest and "/" not in rest else "/"
|
||||
return root.rstrip("/\\") + sep + sep.join(dropped)
|
||||
|
||||
|
||||
def _sample(paths: list[str], n: int) -> list[str]:
|
||||
"""`n` paths spread evenly over the group, so one album is not the sample."""
|
||||
if len(paths) <= n:
|
||||
return list(paths)
|
||||
step = len(paths) / n
|
||||
return [paths[int(i * step)] for i in range(n)]
|
||||
|
||||
|
||||
def _hits(path: str, root: str, roots: list[Path]) -> set[tuple[str, str]]:
|
||||
"""Every (from, to) mapping that resolves this one stored path, at the
|
||||
SHALLOWEST drop that resolves it at all — dropping more folders only makes a
|
||||
match likelier to be a coincidence."""
|
||||
split = _split(path, root)
|
||||
if split is None:
|
||||
return set()
|
||||
dirs, name = split
|
||||
# A bare filesystem root cannot be a mapping's `from` (it would match every
|
||||
# path), so a group rooted at `/` starts by dropping one folder. And at
|
||||
# least one folder must survive the drop: a filename alone at a drive's
|
||||
# root is far too weak to call a match.
|
||||
first = 1 if not root.strip("/\\") else 0
|
||||
last = min(MAX_DROP, max(len(dirs) - 1, 0))
|
||||
for drop in range(first, last + 1):
|
||||
found = set()
|
||||
for base in roots:
|
||||
try:
|
||||
if base.joinpath(*dirs[drop:], name).exists():
|
||||
found.add((_from_prefix(root, path, dirs[:drop]), str(base)))
|
||||
except OSError:
|
||||
continue
|
||||
if found:
|
||||
return found
|
||||
return set()
|
||||
|
||||
|
||||
def _resolves(mapping: PathMapping, paths: list[str]) -> int:
|
||||
n = 0
|
||||
for p in paths:
|
||||
target = mapping.apply(Path(p))
|
||||
try:
|
||||
if str(target) != p and target.exists():
|
||||
n += 1
|
||||
except OSError:
|
||||
continue
|
||||
return n
|
||||
|
||||
|
||||
def search(groups: list[PathGroup], roots: list[Path]) -> list[Proposal]:
|
||||
"""Where each group's tracks are now, if anywhere among `roots`."""
|
||||
roots = list(dict.fromkeys(Path(r) for r in roots))
|
||||
out: list[Proposal] = []
|
||||
for group in groups:
|
||||
sample = _sample(group.paths, SAMPLE)
|
||||
votes: dict[tuple[str, str], int] = {}
|
||||
for p in sample:
|
||||
for hit in _hits(p, group.root, roots):
|
||||
votes[hit] = votes.get(hit, 0) + 1
|
||||
# One sampled track is a coincidence (a common filename in a common
|
||||
# folder name); a group too small to sample three is taken on one.
|
||||
floor = min(3, len(sample))
|
||||
ranked = sorted(
|
||||
(h for h, n in votes.items() if n >= floor), key=lambda h: -votes[h]
|
||||
)[:3]
|
||||
candidates = []
|
||||
for from_, to in ranked:
|
||||
mapping = PathMapping.make(from_, to)
|
||||
found = _resolves(mapping, group.paths)
|
||||
if found:
|
||||
candidates.append(Candidate(mapping, found))
|
||||
candidates.sort(key=lambda c: -c.found)
|
||||
if candidates:
|
||||
best = candidates[0].found
|
||||
candidates = [c for c in candidates if c.found >= best * AMBIGUOUS_SHARE]
|
||||
out.append(Proposal(group.label, group.root, len(group.paths), candidates))
|
||||
return out
|
||||
@@ -0,0 +1,447 @@
|
||||
"""Write a native-instruments STEM file (`.stem.m4a`) from a source track.
|
||||
|
||||
The file layout is measured, not guessed, and matches the user's commercial
|
||||
stem files (see the stem-conversion discussion log): an `ipod` MP4 with FIVE
|
||||
AAC-LC stereo 44.1 kHz streams — stream 0 the full mix and 1-4 drums / bass /
|
||||
synths / vox — streams 1-4 not enabled (`disposition` 0, so a player that knows
|
||||
nothing of stems plays the mix), and a `moov/udta/stem` box holding JSON that
|
||||
names and colours the stems. Traktor 4.5 loads such a file as stems and honours
|
||||
the MP4 edit list, so a stem file's time base is the decoded audio's own.
|
||||
|
||||
Platform-independent on purpose: the separation itself is a callback
|
||||
(`separate`) so this module never imports torch — the stem ENGINE supplies it
|
||||
in production, and the tests use a fake one. Konduktor's backend owns decode,
|
||||
encode, mux, tags and verification, where they are testable on any machine.
|
||||
|
||||
Things that were measured and are easy to get wrong:
|
||||
* **Mono sources are duplicated by hand.** FFmpeg's resampler upmixes mono to
|
||||
stereo at -3 dB (0.5 -> 0.354), which would make a converted mono track
|
||||
quieter than its source.
|
||||
* **Resampling does not move time**: a 48 kHz impulse at 1.000 s lands on
|
||||
sample 44100 exactly. Tested, because a shift here would move every cue.
|
||||
* **Both encoders are sample-exact on timing** (`aac` primes 1024 samples,
|
||||
Apple's `aac_at` 2112, both recorded in the edit list), but each decodes a
|
||||
little LONGER than the input — the last frame's padding (up to one frame for
|
||||
`aac`, ~2 for `aac_at`). So the length check allows 0..2048 extra samples,
|
||||
and the duration reported to the collection is the SOURCE's.
|
||||
* **Two JSON serialisations, one object.** The file's `stem` box is written
|
||||
the way the commercial files write it (Python's default `json.dumps`: key
|
||||
order kept, `4.0`, 17-digit floats) and Traktor's `<STEMS>` element the way
|
||||
Traktor writes it (sorted keys, `4`, 16 digits — the one value on all 3,678
|
||||
stem entries of the real collection). Neither can be derived from the other
|
||||
byte for byte — Traktor's 16 digits do not even round-trip the same double —
|
||||
so both are literals, and a test proves they hold the same float32 values
|
||||
(the precision NI stores them at: 0.02f, 0.14f, 0.05f).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fractions
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import mp4_edit, tag_copy
|
||||
|
||||
SR = 44100
|
||||
FRAME = 1024 # AAC-LC frame size, for both encoders
|
||||
#: The stem slots, in file order after the mix. Demucs names its outputs
|
||||
#: drums / bass / other / vocals; "other" is what NI calls Synths.
|
||||
STEM_NAMES = ("Drums", "Bass", "Synths", "Vox")
|
||||
DEMUCS_ORDER = ("drums", "bass", "other", "vocals")
|
||||
|
||||
#: The `moov/udta/stem` box payload, byte for byte as the commercial files have it.
|
||||
STEM_BOX_JSON = (
|
||||
b'{"mastering_dsp": {"compressor": {"ratio": 4.0, "output_gain": 0.0, "enabled": false, '
|
||||
b'"threshold": 0.0, "attack": 0.019999999552965164, "input_gain": 0.0, "release": '
|
||||
b'0.14000000059604645, "hp_cutoff": 50, "dry_wet": 50}, "limiter": {"release": '
|
||||
b'0.05000000074505806, "threshold": 0.0, "ceiling": 0.0, "enabled": false}}, "version": 1, '
|
||||
b'"stems": [{"color": "#FD4A4A", "name": "Drums"}, {"color": "#FFFF00", "name": "Bass"}, '
|
||||
b'{"color": "#00E8E8", "name": "Synths"}, {"color": "#AD65FF", "name": "Vox"}]}'
|
||||
)
|
||||
#: Traktor's `<ENTRY><STEMS STEMS="…">` value for the same object, as Traktor writes it.
|
||||
NML_STEMS_JSON = (
|
||||
'{"mastering_dsp":{"compressor":{"attack":0.01999999955296516,"dry_wet":50,"enabled":false,'
|
||||
'"hp_cutoff":50,"input_gain":0,"output_gain":0,"ratio":4,"release":0.1400000005960464,'
|
||||
'"threshold":0},"limiter":{"ceiling":0,"enabled":false,"release":0.05000000074505806,'
|
||||
'"threshold":0}},"stems":[{"color":"#FD4A4A","name":"Drums"},{"color":"#FFFF00","name":"Bass"},'
|
||||
'{"color":"#00E8E8","name":"Synths"},{"color":"#AD65FF","name":"Vox"}],"version":1}'
|
||||
)
|
||||
|
||||
#: Codecs whose source counts as lossless for the bitrate rule.
|
||||
_LOSSLESS = ("flac", "alac", "wavpack", "tta", "ape", "truehd", "mlp")
|
||||
#: Output bitrate: sources below 256 kbps get 256 (AAC below that is audible on a
|
||||
#: soloed stem), everything else — and every lossless source — 320.
|
||||
_FLOOR, _TOP = 256_000, 320_000
|
||||
#: Decoded length may exceed the source by the encoders' final-frame padding.
|
||||
_LENGTH_SLACK = 2 * FRAME
|
||||
|
||||
|
||||
class StemFileError(Exception):
|
||||
"""The file could not be written, or failed verification. User-facing."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Source:
|
||||
"""A decoded source: stereo float32 at 44.1 kHz, plus what the bitrate rule
|
||||
and the collection need to know about the original."""
|
||||
|
||||
pcm: np.ndarray # shape (2, n), float32 — NOT clamped (masters exceed 0 dBFS)
|
||||
codec: str
|
||||
bit_rate: int | None # bps, as the container/stream reports it
|
||||
|
||||
@property
|
||||
def samples(self) -> int:
|
||||
return int(self.pcm.shape[1])
|
||||
|
||||
@property
|
||||
def lossless(self) -> bool:
|
||||
return self.codec.startswith("pcm_") or self.codec in _LOSSLESS
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Written:
|
||||
"""What a finished stem file is, for the collection entry that points at it."""
|
||||
|
||||
path: Path
|
||||
bit_rate: int # bps per stream, as encoded
|
||||
duration: float # seconds, the SOURCE's (see the module notes)
|
||||
size: int # bytes
|
||||
tags: dict
|
||||
|
||||
|
||||
def default_encoder() -> str:
|
||||
"""Apple's AudioToolbox encoder on macOS (the better AAC encoder there),
|
||||
FFmpeg's own elsewhere. Both are timing-exact in Traktor (kit 1)."""
|
||||
import av
|
||||
|
||||
return "aac_at" if sys.platform == "darwin" and "aac_at" in av.codecs_available else "aac"
|
||||
|
||||
|
||||
def choose_bitrate(source: Source) -> int:
|
||||
if source.lossless or not source.bit_rate:
|
||||
return _TOP
|
||||
return _FLOOR if source.bit_rate < _FLOOR else _TOP
|
||||
|
||||
|
||||
def decode(path: Path | str) -> Source:
|
||||
"""Decode the first audio stream to stereo float32 at 44.1 kHz."""
|
||||
import av
|
||||
|
||||
with av.open(str(path), metadata_errors="ignore") as container:
|
||||
stream = container.streams.audio[0]
|
||||
codec = stream.codec_context.name
|
||||
bit_rate = stream.bit_rate or container.bit_rate or None
|
||||
channels = stream.codec_context.channels
|
||||
# Mono stays mono through the resampler and is duplicated below (see the
|
||||
# module notes); anything wider is downmixed by it.
|
||||
layout = "mono" if channels == 1 else "stereo"
|
||||
resampler = av.AudioResampler(format="fltp", layout=layout, rate=SR)
|
||||
chunks = [f.to_ndarray() for frame in container.decode(stream) for f in resampler.resample(frame)]
|
||||
chunks += [f.to_ndarray() for f in resampler.resample(None)]
|
||||
if not chunks:
|
||||
raise StemFileError("The file has no audio to convert")
|
||||
pcm = np.concatenate(chunks, axis=1).astype(np.float32, copy=False)
|
||||
if pcm.shape[0] == 1:
|
||||
pcm = np.repeat(pcm, 2, axis=0)
|
||||
return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate)
|
||||
|
||||
|
||||
def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
|
||||
checkpoint: Callable[[], None] | None) -> None:
|
||||
"""Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the
|
||||
muxer never buffers a whole stream (which it would if they came one after
|
||||
another)."""
|
||||
import av
|
||||
|
||||
n = tracks[0].shape[1]
|
||||
tb = fractions.Fraction(1, SR)
|
||||
container = av.open(fp, "w", format="ipod")
|
||||
try:
|
||||
streams = []
|
||||
for k in range(len(tracks)):
|
||||
s = container.add_stream(encoder, rate=SR, layout="stereo")
|
||||
s.bit_rate = bit_rate
|
||||
if k:
|
||||
s.disposition = 0 # present, not enabled: a plain player plays the mix
|
||||
streams.append(s)
|
||||
for i, offset in enumerate(range(0, n, FRAME)):
|
||||
if checkpoint is not None and i % 512 == 0:
|
||||
checkpoint()
|
||||
for s, x in zip(streams, tracks):
|
||||
frame = av.AudioFrame.from_ndarray(
|
||||
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
|
||||
format="fltp", layout="stereo",
|
||||
)
|
||||
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
|
||||
for packet in s.encode(frame):
|
||||
container.mux(packet)
|
||||
for s in streams:
|
||||
for packet in s.encode(None):
|
||||
container.mux(packet)
|
||||
finally:
|
||||
container.close()
|
||||
|
||||
|
||||
def _find(f, start: int, end: int, kind: bytes):
|
||||
for k, body, box_end in mp4_edit._boxes(f, start, end):
|
||||
if k == kind:
|
||||
return body - 8, body, box_end # header offset, payload, end
|
||||
return None
|
||||
|
||||
|
||||
def add_stem_box(path: Path | str) -> None:
|
||||
"""Append the `stem` box to `moov/udta` in place.
|
||||
|
||||
Only valid when `moov` is the file's LAST box, which it is for what `_encode`
|
||||
writes (FFmpeg's default): then growing it moves no media data, so no chunk
|
||||
offset changes and only the sizes of `moov` and `udta` need patching. The
|
||||
box header is always 32-bit here (`moov` is far below 4 GiB).
|
||||
"""
|
||||
path = Path(path)
|
||||
size = path.stat().st_size
|
||||
box = struct.pack(">I4s", 8 + len(STEM_BOX_JSON), b"stem") + STEM_BOX_JSON
|
||||
with open(path, "r+b") as f:
|
||||
moov = _find(f, 0, size, b"moov")
|
||||
if moov is None or moov[2] != size:
|
||||
raise StemFileError("Unexpected MP4 layout: the index is not at the end of the file")
|
||||
moov_at, moov_body, _ = moov
|
||||
f.seek(moov_at)
|
||||
data = bytearray(f.read(size - moov_at))
|
||||
udta = _find(f, moov_body, size, b"udta")
|
||||
if udta is not None:
|
||||
u_at, _u_body, u_end = (x - moov_at for x in udta)
|
||||
data[u_end:u_end] = box
|
||||
struct.pack_into(">I", data, u_at, u_end - u_at + len(box))
|
||||
grow = len(box)
|
||||
else:
|
||||
wrapped = struct.pack(">I4s", 8 + len(box), b"udta") + box
|
||||
data += wrapped
|
||||
grow = len(wrapped)
|
||||
struct.pack_into(">I", data, 0, struct.unpack_from(">I", data, 0)[0] + grow)
|
||||
f.seek(moov_at)
|
||||
f.write(data)
|
||||
|
||||
|
||||
def read_stem_box(path: Path | str) -> bytes | None:
|
||||
"""The `moov/udta/stem` payload, or None."""
|
||||
path = Path(path)
|
||||
size = path.stat().st_size
|
||||
with open(path, "rb") as f:
|
||||
moov = _find(f, 0, size, b"moov")
|
||||
if moov is None:
|
||||
return None
|
||||
udta = _find(f, moov[1], moov[2], b"udta")
|
||||
if udta is None:
|
||||
return None
|
||||
stem = _find(f, udta[1], udta[2], b"stem")
|
||||
if stem is None:
|
||||
return None
|
||||
f.seek(stem[1])
|
||||
return f.read(stem[2] - stem[1])
|
||||
|
||||
|
||||
def _aligned(decoded: np.ndarray, source: np.ndarray, window: int = 10 * SR, search: int = 64) -> int:
|
||||
"""Lag (samples) of `decoded` against `source` in the loudest `window`,
|
||||
searched within +-`search`. 0 means the file starts where the source does."""
|
||||
mono_s = source.mean(axis=0)
|
||||
mono_d = decoded.mean(axis=0)
|
||||
n = min(len(mono_s), len(mono_d))
|
||||
if n <= 2 * search:
|
||||
return 0
|
||||
block = SR
|
||||
energy = [float(np.square(mono_s[i:i + block]).sum()) for i in range(0, max(1, n - window), block)]
|
||||
start = int(np.argmax(energy)) * block if energy else 0
|
||||
stop = min(n - search, start + window)
|
||||
start = max(search, start)
|
||||
ref = mono_s[start:stop]
|
||||
best, best_lag = -np.inf, 0
|
||||
for lag in range(-search, search + 1):
|
||||
seg = mono_d[start + lag:stop + lag]
|
||||
if len(seg) != len(ref):
|
||||
continue
|
||||
score = float(np.dot(ref, seg))
|
||||
if score > best:
|
||||
best, best_lag = score, lag
|
||||
return best_lag
|
||||
|
||||
|
||||
def verify(path: Path | str, source: Source) -> None:
|
||||
"""Refuse a file that is not the stem file it should be: five stereo
|
||||
44.1 kHz streams, only the first enabled, the stem box intact (mutagen
|
||||
rewrote the tags after it), the mix the right length and — by
|
||||
cross-correlation over its loudest ten seconds — not shifted by a sample."""
|
||||
import av
|
||||
|
||||
with av.open(str(path)) as container:
|
||||
streams = container.streams.audio
|
||||
if len(streams) != 5:
|
||||
raise StemFileError(f"Expected 5 audio streams, found {len(streams)}")
|
||||
for s in streams:
|
||||
if s.codec_context.channels != 2 or s.codec_context.sample_rate != SR:
|
||||
raise StemFileError("A stream is not stereo 44.1 kHz")
|
||||
if int(streams[0].disposition) == 0 or any(int(s.disposition) for s in streams[1:]):
|
||||
raise StemFileError("Only the mix stream may be enabled")
|
||||
chunks = [f.to_ndarray() for f in container.decode(streams[0])]
|
||||
mix = np.concatenate(chunks, axis=1) if chunks else np.zeros((2, 0), np.float32)
|
||||
extra = mix.shape[1] - source.samples
|
||||
if not 0 <= extra <= _LENGTH_SLACK:
|
||||
raise StemFileError(f"The mix is {extra:+d} samples off the source's length")
|
||||
if read_stem_box(path) != STEM_BOX_JSON:
|
||||
raise StemFileError("The stem description box is missing or damaged")
|
||||
lag = _aligned(mix, source.pcm)
|
||||
if abs(lag) > 1:
|
||||
raise StemFileError(f"The mix is shifted {lag:+d} samples against the source")
|
||||
|
||||
|
||||
Separate = Callable[[np.ndarray], list[np.ndarray]]
|
||||
|
||||
|
||||
def build(source_path: Path | str, target: Path | str, separate: Separate, *,
|
||||
encoder: str | None = None, checkpoint: Callable[[], None] | None = None) -> Written:
|
||||
"""Convert `source_path` into a stem file at `target`.
|
||||
|
||||
`separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems
|
||||
in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch
|
||||
writes a `*.konduktor-partial` and renames it once the batch commits — since
|
||||
nothing here infers a format from the suffix. `checkpoint()` is called between
|
||||
phases and during the encode, and may raise to cancel.
|
||||
"""
|
||||
target = Path(target)
|
||||
tick = checkpoint or (lambda: None)
|
||||
source = decode(source_path)
|
||||
tick()
|
||||
stems = separate(source.pcm)
|
||||
tick()
|
||||
if len(stems) != 4 or any(s.shape != source.pcm.shape for s in stems):
|
||||
raise StemFileError("The separation did not return four stems of the mix's length")
|
||||
bit_rate = choose_bitrate(source)
|
||||
with open(target, "wb") as fp:
|
||||
_encode(fp, [source.pcm, *stems], bit_rate=bit_rate,
|
||||
encoder=encoder or default_encoder(), checkpoint=checkpoint)
|
||||
add_stem_box(target)
|
||||
tags = tag_copy.copy_tags(source_path, target)
|
||||
verify(target, source)
|
||||
return Written(path=target, bit_rate=bit_rate, duration=source.samples / SR,
|
||||
size=target.stat().st_size, tags=tags)
|
||||
|
||||
|
||||
def stem_target_name(source_name: str) -> str:
|
||||
"""`Track.mp3` -> `Track.stem.m4a` (Traktor needs the `.stem.m4a` suffix)."""
|
||||
stem = source_name.rsplit(".", 1)[0] if "." in source_name else source_name
|
||||
return f"{stem}.stem.m4a"
|
||||
|
||||
|
||||
def is_stem_file(path: Path | str) -> bool:
|
||||
"""Whether a FILE is already a stem container — decided by its contents, not
|
||||
by `<STEMS>` in the collection (105 plain MP3s there carry one)."""
|
||||
path = Path(path)
|
||||
if path.suffix.lower() not in (".m4a", ".mp4"):
|
||||
return False
|
||||
try:
|
||||
return read_stem_box(path) is not None
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def stem_layout(path: Path | str) -> list[dict] | None:
|
||||
"""The stems a file carries, for PLAYBACK: `[{"name", "color"}]` in stream
|
||||
order (stream k+1 is stem k), or None when the file is not a playable stem
|
||||
file — no `stem` box, a box that does not parse, or fewer audio streams than
|
||||
it names. Read from the FILE, never from the library's `<STEMS>`: 105 plain
|
||||
MP3 entries in the real collection carry that element."""
|
||||
import json
|
||||
|
||||
import av
|
||||
|
||||
path = Path(path)
|
||||
try:
|
||||
raw = read_stem_box(path)
|
||||
if raw is None:
|
||||
return None
|
||||
stems = json.loads(raw).get("stems") or []
|
||||
with av.open(str(path), metadata_errors="ignore") as c:
|
||||
streams = len(c.streams.audio)
|
||||
except (OSError, ValueError, av.FFmpegError):
|
||||
return None
|
||||
if not stems or streams < 1 + len(stems):
|
||||
return None
|
||||
return [{"name": str(s.get("name") or f"Stem {i + 1}"), "color": str(s.get("color") or "#FFFFFF")}
|
||||
for i, s in enumerate(stems)]
|
||||
|
||||
|
||||
def _traktor_json(v) -> str:
|
||||
if isinstance(v, bool):
|
||||
return "true" if v else "false"
|
||||
if isinstance(v, float):
|
||||
return str(int(v)) if v.is_integer() else "%.16g" % v
|
||||
if isinstance(v, (int, str)) or v is None:
|
||||
return json.dumps(v, ensure_ascii=False)
|
||||
if isinstance(v, list):
|
||||
return "[" + ",".join(_traktor_json(x) for x in v) + "]"
|
||||
if isinstance(v, dict):
|
||||
return "{" + ",".join(f"{json.dumps(k, ensure_ascii=False)}:{_traktor_json(v[k])}"
|
||||
for k in sorted(v)) + "}"
|
||||
raise TypeError(f"not JSON: {v!r}")
|
||||
|
||||
|
||||
def traktor_stems_json(box: bytes) -> str:
|
||||
"""A `stem` box payload as Traktor writes it into `<STEMS STEMS="…">`: keys
|
||||
sorted, no spaces, a whole float as an integer, any other to 16 significant
|
||||
digits. Measured: it reproduces Traktor's value for every stem file on this
|
||||
machine, and re-renders each of the 3,678 `<STEMS>` in the user's big
|
||||
collection unchanged — but all of those carry ONE layout (NI's defaults),
|
||||
so a box with other values is the same rule extrapolated. Raises ValueError
|
||||
on a box that is not JSON."""
|
||||
return _traktor_json(json.loads(box))
|
||||
|
||||
|
||||
def nml_stems_for(path: Path | str) -> str | None:
|
||||
"""The `<STEMS>` value a library entry for this file should carry, or None
|
||||
when it is not a playable stem file (the test `stem_layout` applies)."""
|
||||
if stem_layout(path) is None:
|
||||
return None
|
||||
try:
|
||||
return traktor_stems_json(read_stem_box(path))
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def extract_stream(path: Path | str, stream: int, fp) -> None:
|
||||
"""Copy audio stream `stream` (0 = the mix, 1-4 the stems) into its own MP4,
|
||||
written to the file object `fp` — packets COPIED, never re-encoded.
|
||||
|
||||
A browser decodes only an MP4's first audio stream, so this is how the deck
|
||||
gets at the stems. Measured bit-identical to decoding the stream in place,
|
||||
with the edit list (and so the priming: 1024 for FFmpeg's encoder, 2112 for
|
||||
Apple's) carried across — on Konduktor's files and commercial ones alike, so
|
||||
every stem stays sample-locked to the mix and to the cue timeline.
|
||||
"""
|
||||
import av
|
||||
|
||||
with av.open(str(path), metadata_errors="ignore") as inp:
|
||||
if not 0 <= stream < len(inp.streams.audio):
|
||||
raise StemFileError(f"The file has no audio stream {stream}")
|
||||
ist = inp.streams.audio[stream]
|
||||
out = av.open(fp, "w", format="ipod")
|
||||
try:
|
||||
ost = out.add_stream_from_template(ist)
|
||||
for pkt in inp.demux(ist):
|
||||
if pkt.dts is None:
|
||||
continue # the demuxer's end-of-stream flush packet
|
||||
pkt.stream = ost
|
||||
out.mux(pkt)
|
||||
finally:
|
||||
out.close()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DEMUCS_ORDER", "NML_STEMS_JSON", "SR", "STEM_BOX_JSON", "STEM_NAMES", "Source",
|
||||
"StemFileError", "Written", "add_stem_box", "build", "choose_bitrate", "decode",
|
||||
"default_encoder", "extract_stream", "is_stem_file", "nml_stems_for", "read_stem_box", "stem_layout",
|
||||
"stem_target_name", "traktor_stems_json", "verify",
|
||||
]
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Copy a track's file tags into the MP4 a stem conversion writes.
|
||||
|
||||
A converted `.stem.m4a` replaces its source file — in Replace mode the source is
|
||||
deleted on Save — so every tag the source carried must survive the move, not just
|
||||
the handful Konduktor edits (`audio_tags.write_tags`). The collection keeps its
|
||||
own copy of the metadata either way; this is about the FILE, which is what
|
||||
travels: another DJ app, a stick, a re-import.
|
||||
|
||||
One canonical field list, read from whichever tag format the source uses (ID3 on
|
||||
MP3/AIFF/WAV, Vorbis comments on FLAC/Ogg, MP4 atoms on M4A) and written as the
|
||||
MP4 atoms the user's own commercial stem files use — `tmpo` for BPM and the
|
||||
iTunes freeform `initialkey` for the key — plus the freeform names
|
||||
`audio_tags._write_mp4` already writes (LABEL / REMIXER / PRODUCER / MIX), so a
|
||||
later tag edit updates the same atom. Cover art is read by `audio_tags.read_cover`.
|
||||
|
||||
Deliberately NOT copied: the rating (the collection owns it, and players store
|
||||
it under incompatible schemes), ReplayGain / loudness (it describes the SOURCE
|
||||
encode), and app-private blobs (Traktor's own `NITR`/PRIV data: Traktor rewrites
|
||||
its analysis for the new file).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from . import audio_tags
|
||||
|
||||
#: canonical field -> MP4 atom. `None` = an iTunes freeform atom named below.
|
||||
_MP4_ATOMS = {
|
||||
"title": "\xa9nam",
|
||||
"artist": "\xa9ART",
|
||||
"album": "\xa9alb",
|
||||
"albumartist": "aART",
|
||||
"genre": "\xa9gen",
|
||||
"comment": "\xa9cmt",
|
||||
"date": "\xa9day",
|
||||
"composer": "\xa9wrt",
|
||||
"grouping": "\xa9grp",
|
||||
"copyright": "cprt",
|
||||
"lyrics": "\xa9lyr",
|
||||
}
|
||||
_FREEFORM = {
|
||||
"key": "initialkey",
|
||||
"label": "LABEL",
|
||||
"remixer": "REMIXER",
|
||||
"producer": "PRODUCER",
|
||||
"mix": "MIX",
|
||||
"isrc": "ISRC",
|
||||
}
|
||||
#: Structured MP4 atoms: track/disc number pairs, BPM, compilation flag.
|
||||
_STRUCTURED = ("tracknumber", "discnumber", "bpm", "compilation")
|
||||
|
||||
# ---- reading ---------------------------------------------------------------
|
||||
_ID3_TEXT = {
|
||||
"TIT2": "title", "TPE1": "artist", "TALB": "album", "TPE2": "albumartist",
|
||||
"TCON": "genre", "TDRC": "date", "TCOM": "composer", "GRP1": "grouping",
|
||||
"TIT1": "grouping", "TCOP": "copyright", "TKEY": "key", "TPUB": "label",
|
||||
"TPE4": "remixer", "TIT3": "mix", "TSRC": "isrc", "TRCK": "tracknumber",
|
||||
"TPOS": "discnumber", "TBPM": "bpm", "TCMP": "compilation",
|
||||
}
|
||||
_VORBIS = {
|
||||
"title": "title", "artist": "artist", "album": "album", "albumartist": "albumartist",
|
||||
"genre": "genre", "comment": "comment", "description": "comment", "date": "date",
|
||||
"composer": "composer", "grouping": "grouping", "copyright": "copyright",
|
||||
"lyrics": "lyrics", "unsyncedlyrics": "lyrics", "initialkey": "key", "key": "key",
|
||||
"label": "label", "organization": "label", "publisher": "label", "remixer": "remixer",
|
||||
"producer": "producer", "mixname": "mix", "isrc": "isrc", "tracknumber": "tracknumber",
|
||||
"discnumber": "discnumber", "bpm": "bpm", "compilation": "compilation",
|
||||
}
|
||||
|
||||
|
||||
def _first(values) -> str | None:
|
||||
for v in values or []:
|
||||
s = str(v).strip()
|
||||
if s:
|
||||
return s
|
||||
return None
|
||||
|
||||
|
||||
def _read_id3(tags) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for frame_id, field in _ID3_TEXT.items():
|
||||
frame = tags.get(frame_id)
|
||||
if frame is not None and field not in out:
|
||||
val = _first(getattr(frame, "text", []))
|
||||
if val:
|
||||
out[field] = val
|
||||
for frame in tags.getall("TXXX"):
|
||||
if frame.desc.upper() == "PRODUCER" and "producer" not in out:
|
||||
out["producer"] = _first(frame.text) or ""
|
||||
comm = [f for f in tags.getall("COMM") if _first(f.text)]
|
||||
if comm: # the untitled comment first: that is the one players show
|
||||
comm.sort(key=lambda f: f.desc != "")
|
||||
out["comment"] = _first(comm[0].text)
|
||||
uslt = tags.getall("USLT")
|
||||
if uslt and getattr(uslt[0], "text", ""):
|
||||
out["lyrics"] = str(uslt[0].text)
|
||||
return {k: v for k, v in out.items() if v}
|
||||
|
||||
|
||||
def _read_vorbis(tags) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for key, values in tags.items():
|
||||
field = _VORBIS.get(key.lower())
|
||||
if field and field not in out:
|
||||
val = _first(values)
|
||||
if val:
|
||||
out[field] = val
|
||||
lower = {k.lower(): v for k, v in tags.items()}
|
||||
for field, total in (("tracknumber", "tracktotal"), ("discnumber", "disctotal")):
|
||||
if field in out and "/" not in out[field] and _first(lower.get(total)):
|
||||
out[field] = f"{out[field]}/{_first(lower[total])}"
|
||||
return out
|
||||
|
||||
|
||||
def _read_mp4(tags) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for field, atom in _MP4_ATOMS.items():
|
||||
val = _first(tags.get(atom))
|
||||
if val:
|
||||
out[field] = val
|
||||
for field, name in _FREEFORM.items():
|
||||
raw = tags.get(f"----:com.apple.iTunes:{name}")
|
||||
if raw:
|
||||
val = bytes(raw[0]).decode("utf-8", "replace").strip()
|
||||
if val:
|
||||
out[field] = val
|
||||
for field, atom in (("tracknumber", "trkn"), ("discnumber", "disk")):
|
||||
pair = (tags.get(atom) or [None])[0]
|
||||
if pair and pair[0]:
|
||||
out[field] = f"{pair[0]}/{pair[1]}" if pair[1] else str(pair[0])
|
||||
if tags.get("tmpo"):
|
||||
out["bpm"] = str(tags["tmpo"][0])
|
||||
if tags.get("cpil"):
|
||||
out["compilation"] = "1" if tags["cpil"] else "0"
|
||||
return out
|
||||
|
||||
|
||||
def read_tags(path: Path | str) -> dict[str, str]:
|
||||
"""The canonical fields a file carries, whatever its tag format; `{}` for a
|
||||
file with none or one mutagen cannot read."""
|
||||
import mutagen
|
||||
from mutagen.id3 import ID3
|
||||
from mutagen.mp4 import MP4Tags
|
||||
|
||||
try:
|
||||
audio = mutagen.File(str(path))
|
||||
except Exception: # noqa: BLE001 — an unreadable tag is no tags, not a failure
|
||||
return {}
|
||||
tags = getattr(audio, "tags", None)
|
||||
if tags is None:
|
||||
return {}
|
||||
if isinstance(tags, ID3):
|
||||
return _read_id3(tags)
|
||||
if isinstance(tags, MP4Tags):
|
||||
return _read_mp4(tags)
|
||||
if hasattr(tags, "items"): # Vorbis comments (FLAC, Ogg, Opus)
|
||||
return _read_vorbis(tags)
|
||||
return {}
|
||||
|
||||
|
||||
# ---- writing ---------------------------------------------------------------
|
||||
def _number_pair(value: str) -> tuple[int, int] | None:
|
||||
head, _, tail = value.partition("/")
|
||||
try:
|
||||
return int(head), int(tail) if tail.strip() else 0
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def write_mp4_tags(path: Path | str, fields: dict[str, str],
|
||||
cover: tuple[bytes, str] | None = None) -> None:
|
||||
"""Write canonical `fields` (and a cover) into an MP4 file, replacing nothing
|
||||
it does not name. Values that cannot be represented (a BPM that is not a
|
||||
number) are skipped rather than written wrong.
|
||||
|
||||
Opened as `MP4` explicitly, never by suffix: a conversion writes into a
|
||||
`*.konduktor-partial` file, which `audio_tags.write_cover` would refuse as
|
||||
an unsupported format — silently losing the art."""
|
||||
from mutagen.mp4 import MP4, MP4Cover, MP4FreeForm
|
||||
|
||||
audio = MP4(str(path))
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
t = audio.tags
|
||||
for field, atom in _MP4_ATOMS.items():
|
||||
if fields.get(field):
|
||||
t[atom] = [fields[field]]
|
||||
for field, name in _FREEFORM.items():
|
||||
if fields.get(field):
|
||||
t[f"----:com.apple.iTunes:{name}"] = [MP4FreeForm(fields[field].encode("utf-8"))]
|
||||
for field, atom in (("tracknumber", "trkn"), ("discnumber", "disk")):
|
||||
pair = _number_pair(fields.get(field, "")) if fields.get(field) else None
|
||||
if pair:
|
||||
t[atom] = [pair]
|
||||
if fields.get("bpm"):
|
||||
try:
|
||||
bpm = round(float(fields["bpm"]))
|
||||
if 0 < bpm < 65536:
|
||||
t["tmpo"] = [bpm]
|
||||
except ValueError:
|
||||
pass
|
||||
if fields.get("compilation"):
|
||||
t["cpil"] = fields["compilation"].strip() not in ("", "0", "false", "False")
|
||||
if cover is not None:
|
||||
data, mime = cover
|
||||
fmt = MP4Cover.FORMAT_PNG if mime == "image/png" else MP4Cover.FORMAT_JPEG
|
||||
t["covr"] = [MP4Cover(data, imageformat=fmt)]
|
||||
audio.save()
|
||||
|
||||
|
||||
def copy_tags(source: Path | str, target: Path | str) -> dict[str, str]:
|
||||
"""Copy every canonical tag and the cover art from `source` into the MP4
|
||||
`target`. Returns the fields copied (for reporting and tests)."""
|
||||
fields = read_tags(source)
|
||||
cover = audio_tags.read_cover(Path(source))
|
||||
if fields or cover is not None:
|
||||
write_mp4_tags(target, fields, cover)
|
||||
return fields
|
||||
@@ -0,0 +1,198 @@
|
||||
"""What a track's waveform is made of — measured once, drawn by whoever needs it.
|
||||
|
||||
Platform-independent on purpose: this decodes and measures, and stops there. How
|
||||
a measurement becomes pixels — Pioneer's 5-bit heights, 3-band bytes, colour
|
||||
bits — is the target's business (`adapters/rekordbox/anlz_writer.py`).
|
||||
|
||||
Two resolutions, from ONE decode:
|
||||
|
||||
* `columns` — `n` equal slices of the whole track (loudness + brightness), for
|
||||
an overview such as Pioneer's blue `PWAV` preview;
|
||||
* `frames` — 150 per second, each split into low / mid / high band energy,
|
||||
for a detail waveform and a 3-band overview (Pioneer's `PWV3`-`PWV7`).
|
||||
|
||||
The bands cross over at 200 Hz and 2.5 kHz: fitted against rekordbox's own 3-band
|
||||
waveforms for ten local tracks (correlation 0.89 / 0.80 / 0.77 per band). Energy
|
||||
is left unscaled — each target normalises it its own way.
|
||||
|
||||
Decoding goes through PyAV (FFmpeg, bundled in its wheel) and falls back to
|
||||
`librosa`, like grid detection: libsndfile for most formats
|
||||
and, for AAC (every Traktor `.stem.m4a`), `audioread`'s CoreAudio backend on macOS.
|
||||
Where nothing can decode a file, `analyse()` returns None and the caller decides
|
||||
what a missing waveform means.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: BUMP THIS whenever `analyse()`'s output changes (a constant below, the
|
||||
#: decoder, the maths). Exports cache these measurements on the stick
|
||||
#: (`analysis_cache`), keyed by this number — so an unbumped change keeps
|
||||
#: serving the old measurement to every re-export.
|
||||
ANALYSIS_VERSION = 1
|
||||
|
||||
#: Plenty for a waveform, and half the decode cost of 44.1 kHz. The high band
|
||||
#: runs to 11 kHz, which is where most of its visible energy is anyway.
|
||||
SR = 22050
|
||||
#: Detail resolution. Pioneer's detail tags are 150 entries per second.
|
||||
FPS = 150
|
||||
N_FFT = 1024
|
||||
#: Band crossovers, Hz.
|
||||
LOW_MAX, MID_MAX = 200.0, 2500.0
|
||||
#: "Bright" (for `columns`) = share of spectral energy above this.
|
||||
_BRIGHT_HZ = 2500.0
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@dataclass
|
||||
class Frames:
|
||||
"""150-per-second band energies, low / mid / high, shape (n, 3).
|
||||
|
||||
Frame i covers `[i/150, (i+1)/150)` seconds on the clock the caller asked
|
||||
for — see `analyse(lead=…)`.
|
||||
"""
|
||||
|
||||
bands: np.ndarray
|
||||
#: Decoded length in seconds (of the audio, not counting any lead).
|
||||
duration: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class Analysis:
|
||||
columns: Columns
|
||||
frames: Frames
|
||||
|
||||
@property
|
||||
def duration(self) -> float:
|
||||
return self.columns.duration
|
||||
|
||||
|
||||
def _decode_pyav(path: Path) -> np.ndarray:
|
||||
"""Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel.
|
||||
|
||||
The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY
|
||||
OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured
|
||||
to start on exactly the same sample as librosa's decode for MP3 and AAC, so
|
||||
switching decoders moves nothing against the beats.
|
||||
"""
|
||||
import av
|
||||
|
||||
with av.open(str(path)) as container:
|
||||
stream = container.streams.audio[0]
|
||||
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR)
|
||||
chunks = []
|
||||
for frame in container.decode(stream):
|
||||
for out in resampler.resample(frame):
|
||||
chunks.append(out.to_ndarray().reshape(-1))
|
||||
for out in resampler.resample(None): # flush
|
||||
chunks.append(out.to_ndarray().reshape(-1))
|
||||
return np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32)
|
||||
|
||||
|
||||
def even_slices(n: int, k: int) -> list[slice]:
|
||||
"""`k` slices of `range(n)`, each starting where its share of the whole
|
||||
begins — so column `i` holds exactly the audio at `i/k` of the track.
|
||||
|
||||
NOT `np.array_split`: that gives the FIRST `n % k` chunks one extra element,
|
||||
which pushes every early column's content later than its position — up to
|
||||
~1.8 s by column 420 of a 1200-column overview (24,420 frames), shrinking
|
||||
back to 0 at the end. Rekordbox drew such an overview a bar ahead of the
|
||||
playhead mid-track, and closer to right near the end.
|
||||
"""
|
||||
edges = np.round(np.linspace(0, n, k + 1)).astype(int)
|
||||
return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])]
|
||||
|
||||
|
||||
def _decode(path: Path) -> np.ndarray | None:
|
||||
try:
|
||||
return _decode_pyav(path)
|
||||
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
|
||||
log.debug("PyAV could not decode %s (%s); trying librosa", path, ex)
|
||||
try:
|
||||
import librosa
|
||||
|
||||
y, _ = librosa.load(str(path), sr=SR, mono=True)
|
||||
return y
|
||||
except Exception as ex: # any decoder failure: no waveform, not a failed export
|
||||
log.warning("could not decode %s for a waveform: %s", path, ex)
|
||||
return None
|
||||
|
||||
|
||||
def _columns(y: np.ndarray, n: int) -> Columns:
|
||||
import librosa
|
||||
|
||||
rms = np.array([float(np.sqrt(np.mean(y[s] * y[s]))) for s in even_slices(len(y), n)])
|
||||
spec = np.abs(librosa.stft(y, n_fft=N_FFT, hop_length=N_FFT)) ** 2
|
||||
freqs = librosa.fft_frequencies(sr=SR, n_fft=N_FFT)
|
||||
share = spec[freqs > _BRIGHT_HZ].sum(0) / (spec.sum(0) + 1e-12)
|
||||
brightness = np.array([float(c.mean()) if len(c) else 0.0
|
||||
for c in (share[s] for s in even_slices(len(share), n))])
|
||||
return Columns(rms=rms, brightness=brightness, duration=len(y) / SR)
|
||||
|
||||
|
||||
def _frames(y: np.ndarray, lead: float) -> Frames:
|
||||
"""Band energies at 150/s, with the frame grid starting `lead` s BEFORE the
|
||||
audio — how a target whose clock runs behind the decoded audio (rekordbox on
|
||||
MP3/AAC) gets frames that line up with its own positions."""
|
||||
import librosa
|
||||
|
||||
duration = len(y) / SR
|
||||
pad = int(round(max(0.0, lead) * SR))
|
||||
padded = np.concatenate([np.zeros(pad, dtype=y.dtype), y]) if pad else y
|
||||
n = int(np.ceil((len(padded) / SR) * FPS))
|
||||
hop = SR / FPS # 147 samples at 22050 Hz
|
||||
spec = np.abs(librosa.stft(padded, n_fft=N_FFT, hop_length=int(round(hop)),
|
||||
center=True)) ** 2
|
||||
f = librosa.fft_frequencies(sr=SR, n_fft=N_FFT)
|
||||
bands = np.stack([
|
||||
np.sqrt(spec[f < LOW_MAX].sum(0)),
|
||||
np.sqrt(spec[(f >= LOW_MAX) & (f < MID_MAX)].sum(0)),
|
||||
np.sqrt(spec[f >= MID_MAX].sum(0)),
|
||||
], axis=1)[:n]
|
||||
if len(bands) < n:
|
||||
bands = np.vstack([bands, np.zeros((n - len(bands), 3))])
|
||||
return Frames(bands=bands, duration=duration)
|
||||
|
||||
|
||||
def analyse(path: Path, *, n_columns: int = 400, lead: float = 0.0) -> Analysis | None:
|
||||
"""Decode `path` once and measure both resolutions; None if undecodable."""
|
||||
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))
|
||||
|
||||
|
||||
def columns(path: Path, n: int) -> Columns | None:
|
||||
"""Just the overview columns — for a caller that needs no detail."""
|
||||
y = _decode(path)
|
||||
if y is None or len(y) < n:
|
||||
return None
|
||||
return _columns(y, n)
|
||||
+361
-65
@@ -19,38 +19,82 @@ in-flight one behind, which is a bug the import feature had and was fixed there.
|
||||
|
||||
## Konduktor only deletes what Konduktor wrote
|
||||
|
||||
A re-export clears its destination first, which combined with "the user picks
|
||||
A re-export clears its previous export first, which combined with "the user picks
|
||||
the destination" is a folder-deletion hazard: point an export at `~/Documents`
|
||||
and a confirm dialog is the only thing between a click and real loss. So every
|
||||
export writes a **manifest** of what it put there, and a destination that is
|
||||
non-empty without one is REFUSED rather than confirmed. Clearing then removes
|
||||
exactly the manifest's files — anything the user added themselves survives.
|
||||
|
||||
## Mirror layout
|
||||
## A re-export copies only what changed
|
||||
|
||||
The manifest also records, per copied file, the SOURCE's path, size and mtime
|
||||
and the COPY's size and mtime as read back. A re-export keeps a previous copy
|
||||
when all four still match — the same quick check rsync makes, and no
|
||||
checksums: hashing the copy means reading it back over USB, which costs about
|
||||
what copying it again does. A tag edit rewrites the source file, so its mtime
|
||||
moves and the file is copied again. Copies are matched by SOURCE path, not by
|
||||
where they sit, because adding a track from another folder moves the shared
|
||||
root below and with it every destination path; a kept copy whose path changed
|
||||
is renamed, not copied. No record, or an unreadable one, means copy everything.
|
||||
|
||||
The ORDER keeps the safety properties: the previous export's libraries and
|
||||
every file not kept go first, then the kept copies are moved, then what
|
||||
changed is copied (under a temporary name, renamed into place), and the
|
||||
libraries are written last. A cancel removes what THIS run wrote and rewrites
|
||||
the manifest around what it kept — deleting the manifest with kept files still
|
||||
there would leave a folder the next export refuses as not ours.
|
||||
|
||||
Decoding every track for its Pioneer waveforms is the other slow part, so the
|
||||
measurements are cached on the drive too (`core/analysis_cache.py`), keyed by
|
||||
the same source facts.
|
||||
|
||||
## Several targets, one copy of the audio
|
||||
|
||||
An export can target several platforms at once. The audio is copied ONCE and
|
||||
every target's library is written over the same files, one after another. If
|
||||
any of them fails, EVERYTHING is undone — the audio and the libraries already
|
||||
written — because "the libraries' absence marks an export unfinished" only
|
||||
holds if a half-finished multi-target export also leaves none behind.
|
||||
|
||||
## Mirror layout, under `Contents/`
|
||||
|
||||
Audio is laid out mirroring the source tree, relative to the deepest folder all
|
||||
the tracks share (`common_dir_prefix`). Mirroring absolute paths would put the
|
||||
user's home directory on the stick; mirroring relative to the common root keeps
|
||||
the structure recognisable and makes filename collisions impossible, since two
|
||||
distinct source paths cannot share a relative path.
|
||||
the tracks share (`common_dir_prefix`), inside a `Contents/` folder — the name
|
||||
rekordbox itself uses on a stick. Mirroring absolute paths would put the user's
|
||||
home directory on the stick; mirroring relative to the common root keeps the
|
||||
structure recognisable and makes filename collisions impossible, since two
|
||||
distinct source paths cannot share a relative path. `Contents/` is what keeps
|
||||
the AUDIO from colliding with the LIBRARIES: without it, a music folder with a
|
||||
top-level `PIONEER/` or `share/`, or a file called `master.db`, would land on
|
||||
top of one.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from . import exports
|
||||
from .core import registry
|
||||
from .core.analysis_cache import CACHE_DIR, AnalysisCache, fingerprint
|
||||
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform
|
||||
from .core.pathmap import common_dir_prefix
|
||||
from .core.places import is_os_housekeeping
|
||||
from .core.places import is_drive_root, is_os_housekeeping
|
||||
from .importer import SPACE_HEADROOM, copy_file, free_bytes
|
||||
from .jobs import JobHandle
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
MANIFEST_NAME = ".konduktor-export.json"
|
||||
#: Every exported audio file lives under this folder, never at the root.
|
||||
AUDIO_DIR = "Contents"
|
||||
#: Where kept copies wait while being moved, and the suffix a copy is written
|
||||
#: under until it is complete. Both are listed in the manifest while in use.
|
||||
MOVING_DIR = ".konduktor-moving"
|
||||
PARTIAL_SUFFIX = ".konduktor-partial"
|
||||
|
||||
#: Why an export cannot run. The UI words these; they are facts, not sentences.
|
||||
BLOCKED_OCCUPIED = "destination_not_empty"
|
||||
@@ -66,6 +110,12 @@ class PlannedTrack:
|
||||
destination: Path | None
|
||||
size: int = 0
|
||||
missing: bool = False
|
||||
#: The source's mtime when planned, recorded in the manifest with `size`.
|
||||
mtime_ns: int = 0
|
||||
#: Where the previous export's copy of this very file sits, when it can be
|
||||
#: kept instead of copied again — possibly a different path from
|
||||
#: `destination`, in which case it is moved. None means copy.
|
||||
reuse: Path | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -77,6 +127,10 @@ class ExportPlan:
|
||||
blocked: str | None = None
|
||||
#: Whether the destination already holds a Konduktor export to replace.
|
||||
replacing: bool = False
|
||||
#: Targets whose library is only found at a drive's root, when the
|
||||
#: destination is not one. A warning, not a block: the other targets are
|
||||
#: fine anywhere, and the user may be staging a stick's contents on purpose.
|
||||
not_drive_root: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def exportable(self) -> list[PlannedTrack]:
|
||||
@@ -84,12 +138,19 @@ class ExportPlan:
|
||||
|
||||
@property
|
||||
def total_bytes(self) -> int:
|
||||
return sum(t.size for t in self.exportable)
|
||||
"""What will actually be COPIED — a kept file costs neither time nor
|
||||
space, since the previous export's other files are removed first."""
|
||||
return sum(t.size for t in self.exportable if t.reuse is None)
|
||||
|
||||
@property
|
||||
def unchanged(self) -> int:
|
||||
return sum(1 for t in self.exportable if t.reuse is not None)
|
||||
|
||||
def as_dict(self, free: int | None = None) -> dict:
|
||||
return {
|
||||
"tracks": len(self.tracks),
|
||||
"exportable": len(self.exportable),
|
||||
"unchanged": self.unchanged,
|
||||
"missing": [t.title for t in self.tracks if t.missing],
|
||||
"playlists": [p.name for p in self.playlists],
|
||||
"total_bytes": self.total_bytes,
|
||||
@@ -100,6 +161,7 @@ class ExportPlan:
|
||||
),
|
||||
"blocked": self.blocked,
|
||||
"replacing": self.replacing,
|
||||
"not_drive_root": list(self.not_drive_root),
|
||||
}
|
||||
|
||||
|
||||
@@ -141,8 +203,9 @@ def destination_blocked(destination: Path) -> str | None:
|
||||
return BLOCKED_OCCUPIED
|
||||
|
||||
|
||||
def _clear(destination: Path) -> None:
|
||||
"""Remove the previous export, and only it.
|
||||
def _clear(destination: Path, keep: set[Path] = frozenset()) -> None:
|
||||
"""Remove the previous export, and only it — except the audio in `keep`,
|
||||
which this export reuses.
|
||||
|
||||
Driven by the manifest rather than by wiping the folder: the manifest lists
|
||||
everything the last export wrote, so anything the user put there themselves
|
||||
@@ -151,11 +214,16 @@ def _clear(destination: Path) -> None:
|
||||
"""
|
||||
data = _read_manifest(destination)
|
||||
for name in data.get("files", []):
|
||||
path = destination / name
|
||||
if path in keep:
|
||||
continue
|
||||
try:
|
||||
(destination / name).unlink()
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
for name in (data.get("library"), MANIFEST_NAME):
|
||||
# `library` is the single-target manifest an older export left behind.
|
||||
libraries = list(data.get("libraries") or []) + [data.get("library")]
|
||||
for name in (*libraries, MANIFEST_NAME):
|
||||
if name:
|
||||
try:
|
||||
(destination / name).unlink()
|
||||
@@ -186,7 +254,8 @@ def _read_manifest(destination: Path) -> dict:
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _write_manifest(destination: Path, *, library: str, files: list[str], name: str) -> None:
|
||||
def _write_manifest(destination: Path, *, libraries: list[str], files: list[str],
|
||||
audio: dict[str, dict], name: str) -> None:
|
||||
from . import paths
|
||||
|
||||
paths.write_json(
|
||||
@@ -196,12 +265,66 @@ def _write_manifest(destination: Path, *, library: str, files: list[str], name:
|
||||
"so re-exporting can replace exactly those files.",
|
||||
"export": name,
|
||||
"written": time.time(),
|
||||
"library": library,
|
||||
"libraries": libraries,
|
||||
"files": files,
|
||||
"audio": audio,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _record(planned: PlannedTrack, copy: Path) -> dict:
|
||||
"""What the manifest remembers about one copied file.
|
||||
|
||||
The SOURCE's size and mtime as planned — if it changed during the copy, the
|
||||
next export sees a mismatch and copies again, which is the safe direction —
|
||||
and the COPY's as read back now, never assumed equal to the source's: a
|
||||
FAT32 stick keeps mtimes to 2 s, so `copystat` does not round-trip there.
|
||||
"""
|
||||
st = copy.stat()
|
||||
return {
|
||||
"source": str(planned.source_path),
|
||||
"size": planned.size,
|
||||
"mtime_ns": planned.mtime_ns,
|
||||
"copy_size": st.st_size,
|
||||
"copy_mtime_ns": st.st_mtime_ns,
|
||||
}
|
||||
|
||||
|
||||
def _previous_copies(destination: Path) -> dict[str, tuple[Path, dict]]:
|
||||
"""The last export's copies, by SOURCE path — not by where they sit, since
|
||||
adding a track from another folder moves the shared root and with it every
|
||||
destination path. No record (none yet, an older manifest, an unreadable
|
||||
one) means nothing is reused: never guess from the files on disk."""
|
||||
if not is_ours(destination):
|
||||
return {}
|
||||
audio = _read_manifest(destination).get("audio")
|
||||
out: dict[str, tuple[Path, dict]] = {}
|
||||
if isinstance(audio, dict):
|
||||
for rel, record in audio.items():
|
||||
if isinstance(record, dict) and isinstance(record.get("source"), str):
|
||||
out[record["source"]] = (destination / rel, record)
|
||||
return out
|
||||
|
||||
|
||||
def _reusable(planned: PlannedTrack, previous: dict[str, tuple[Path, dict]]) -> Path | None:
|
||||
"""The previous copy of this file, if neither it nor its source changed."""
|
||||
found = previous.get(str(planned.source_path))
|
||||
if found is None:
|
||||
return None
|
||||
copy, record = found
|
||||
if (record.get("size"), record.get("mtime_ns")) != (planned.size, planned.mtime_ns):
|
||||
return None
|
||||
try:
|
||||
st = copy.stat()
|
||||
except OSError:
|
||||
return None
|
||||
# The copy is checked too: a file edited or replaced ON the stick is not
|
||||
# the one this export would have written.
|
||||
if (st.st_size, st.st_mtime_ns) != (record.get("copy_size"), record.get("copy_mtime_ns")):
|
||||
return None
|
||||
return copy
|
||||
|
||||
|
||||
# ---- planning ----------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -210,7 +333,8 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
destination = Path(export_set.destination).expanduser()
|
||||
built = ExportPlan(destination=destination)
|
||||
|
||||
if for_platform(export_set.target) is None:
|
||||
exporters = [for_platform(t) for t in export_set.targets]
|
||||
if not exporters or None in exporters:
|
||||
built.blocked = BLOCKED_NO_TARGET
|
||||
return built
|
||||
|
||||
@@ -228,25 +352,36 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
present = [str(p) for p in sources.values() if p]
|
||||
root = common_dir_prefix(present) if present else ""
|
||||
|
||||
previous = _previous_copies(destination)
|
||||
claimed: set[Path] = set()
|
||||
for track in tracks:
|
||||
source = sources[track.id]
|
||||
exists = False
|
||||
size = 0
|
||||
size = mtime_ns = 0
|
||||
try:
|
||||
exists = bool(source and source.is_file())
|
||||
size = source.stat().st_size if exists else 0
|
||||
if exists:
|
||||
st = source.stat()
|
||||
size, mtime_ns = st.st_size, st.st_mtime_ns
|
||||
except OSError:
|
||||
exists = False
|
||||
built.tracks.append(
|
||||
PlannedTrack(
|
||||
track_id=track.id,
|
||||
title=track.title or (source.name if source else track.id),
|
||||
source_path=source,
|
||||
destination=(destination / _relative(source, root)) if exists else None,
|
||||
size=size,
|
||||
missing=not exists,
|
||||
)
|
||||
planned = PlannedTrack(
|
||||
track_id=track.id,
|
||||
title=track.title or (source.name if source else track.id),
|
||||
source_path=source,
|
||||
destination=(destination / AUDIO_DIR / _relative(source, root)) if exists else None,
|
||||
size=size,
|
||||
mtime_ns=mtime_ns,
|
||||
missing=not exists,
|
||||
)
|
||||
if exists:
|
||||
reuse = _reusable(planned, previous)
|
||||
# One kept copy can serve one planned file: two entries sharing a
|
||||
# source would otherwise both try to move it.
|
||||
if reuse is not None and reuse not in claimed:
|
||||
planned.reuse = reuse
|
||||
claimed.add(reuse)
|
||||
built.tracks.append(planned)
|
||||
|
||||
names = {p.id: p for p in resolved.playlists}
|
||||
folders = _folder_paths(adapter)
|
||||
@@ -266,6 +401,8 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
else:
|
||||
built.blocked = destination_blocked(destination)
|
||||
built.replacing = is_ours(destination)
|
||||
if not is_drive_root(destination):
|
||||
built.not_drive_root = [e.platform for e in exporters if e.drive_root]
|
||||
return built
|
||||
|
||||
|
||||
@@ -299,105 +436,264 @@ def _folder_paths(adapter) -> dict[str, list[str]]:
|
||||
|
||||
|
||||
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
"""Copy the audio, then write the library. Rolls back everything on cancel."""
|
||||
exporter = for_platform(export_set.target)
|
||||
if exporter is None:
|
||||
raise ValueError(f"Konduktor cannot export to {export_set.target}")
|
||||
"""Copy what changed, then write every target's library over the audio.
|
||||
|
||||
Rolls back EVERYTHING this run wrote on cancel or on any failure —
|
||||
including the libraries of targets that had already been written when a
|
||||
later one failed. What it KEPT from the previous export stays, and the
|
||||
manifest is rewritten to say so: deleting the manifest with kept files
|
||||
still there would leave a folder the next export refuses as not ours.
|
||||
"""
|
||||
exporters = [for_platform(t) for t in export_set.targets]
|
||||
if not exporters or None in exporters:
|
||||
raise ValueError(f"Konduktor cannot export to {', '.join(export_set.targets)}")
|
||||
if built.blocked:
|
||||
raise ValueError(f"This export cannot run: {built.blocked}")
|
||||
|
||||
destination = Path(built.destination)
|
||||
items = built.exportable
|
||||
total = sum(t.size for t in items)
|
||||
handle.progress(done=0, total=total, message="Preparing…")
|
||||
handle.progress(done=0, total=built.total_bytes, unit="bytes", message="Preparing…")
|
||||
cache = AnalysisCache(destination / CACHE_DIR)
|
||||
|
||||
# Registered BEFORE each write, so a cancel mid-file removes the partial one
|
||||
# too. Cleaning up only completed copies leaves debris the retry then
|
||||
# suffixes around — a bug the import feature had.
|
||||
created: list[Path] = []
|
||||
# The previous export's copies this one keeps, by where they are NOW — so a
|
||||
# rollback during the moves still records each at its real location.
|
||||
kept: dict[Path, dict] = {}
|
||||
# What was on disk before the libraries were written. An exporter that
|
||||
# raises midway has written files it never got to REPORT (a OneLibrary
|
||||
# drive's analysis files, say), so rollback also removes anything that
|
||||
# appeared after this snapshot. Safe because the destination is known to
|
||||
# hold only our files and the user's, and the user's predate it.
|
||||
before: set[Path] | None = None
|
||||
done = 0
|
||||
try:
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
if is_ours(destination):
|
||||
handle.progress(message="Replacing the previous export…")
|
||||
_clear(destination)
|
||||
old = _read_manifest(destination).get("audio") or {}
|
||||
for planned in items:
|
||||
if planned.reuse is not None:
|
||||
record = old.get(_rel(planned.reuse, destination))
|
||||
if record is None:
|
||||
# The manifest changed since the plan: copy after all.
|
||||
planned.reuse = None
|
||||
else:
|
||||
kept[planned.reuse] = record
|
||||
_clear(destination, keep=set(kept))
|
||||
else:
|
||||
for planned in items:
|
||||
planned.reuse = None
|
||||
reused = [t for t in items if t.reuse is not None]
|
||||
handle.progress(total=built.total_bytes)
|
||||
# Written before anything moves or is copied, listing every path this
|
||||
# run may leave behind, so even a crash (not a cancel — nothing gets to
|
||||
# clean up after a crash) leaves a folder the next export can clear.
|
||||
_write_manifest(
|
||||
destination, libraries=[], name=export_set.name,
|
||||
files=sorted({_rel(p, destination) for p in (*kept, *(t.destination for t in items))}
|
||||
| {_rel(_partial(t.destination), destination) for t in items}
|
||||
| {_rel(_staging(destination, i), destination) for i in range(len(reused))}),
|
||||
audio={_rel(p, destination): r for p, r in kept.items()},
|
||||
)
|
||||
if reused:
|
||||
handle.progress(message=f"Keeping {len(reused)} unchanged track{'' if len(reused) == 1 else 's'}…")
|
||||
_move_kept(destination, reused, kept)
|
||||
|
||||
payload_tracks: list[ExportTrack] = []
|
||||
for planned in items:
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message=f"Copying {planned.title}")
|
||||
target = Path(planned.destination)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
created.append(target)
|
||||
if planned.reuse is None:
|
||||
handle.progress(message=f"Copying {planned.title}")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Copied beside the target and renamed into place, so a cancel
|
||||
# can never leave a half-written file under a real track's name.
|
||||
partial = _partial(target)
|
||||
created += [partial, target]
|
||||
|
||||
def advance(n: int) -> None:
|
||||
nonlocal done
|
||||
done += n
|
||||
handle.progress(done=done)
|
||||
def advance(n: int) -> None:
|
||||
nonlocal done
|
||||
done += n
|
||||
handle.progress(done=done)
|
||||
|
||||
copy_file(planned.source_path, target, handle, advance)
|
||||
copy_file(planned.source_path, partial, handle, advance)
|
||||
os.replace(partial, target)
|
||||
payload_tracks.append(
|
||||
ExportTrack(
|
||||
track=adapter.track(planned.track_id),
|
||||
destination=target,
|
||||
cues=adapter.track_cues(planned.track_id),
|
||||
art=_cover(adapter, planned.track_id),
|
||||
fingerprint=_fingerprint(planned),
|
||||
analysis_cache=cache,
|
||||
)
|
||||
)
|
||||
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message=f"Writing the {export_set.target} library…")
|
||||
written = exporter.write(
|
||||
ExportPayload(
|
||||
name=export_set.name,
|
||||
tracks=payload_tracks,
|
||||
playlists=built.playlists,
|
||||
),
|
||||
destination,
|
||||
)
|
||||
# Everything the exporter reported, not just the library: a target can
|
||||
# write a database PLUS a per-track analysis file, and anything left out
|
||||
# here is an orphan the next re-export cannot clear.
|
||||
created.extend(written.all_paths)
|
||||
def checkpoint(message: str, step: int | None = None, of: int | None = None) -> None:
|
||||
handle.raise_if_cancelled()
|
||||
if step is not None and of:
|
||||
# The bar follows the library being written, in tracks: after
|
||||
# the copy, the slow part is decoding — and a re-export may
|
||||
# have copied nothing at all.
|
||||
handle.progress(done=step - 1, total=of, unit="tracks", message=message)
|
||||
else:
|
||||
handle.progress(message=message)
|
||||
|
||||
library = written.library
|
||||
payload = ExportPayload(
|
||||
name=export_set.name,
|
||||
tracks=payload_tracks,
|
||||
playlists=built.playlists,
|
||||
checkpoint=checkpoint,
|
||||
)
|
||||
before = _files(destination)
|
||||
libraries: list[tuple[str, Path]] = []
|
||||
for exporter in exporters:
|
||||
handle.raise_if_cancelled()
|
||||
# Indeterminate until the writer reports its tracks.
|
||||
handle.progress(done=0, total=0, unit="tracks",
|
||||
message=f"Writing the {_display_name(exporter.platform)} library…")
|
||||
written = exporter.write(payload, destination)
|
||||
# Everything the exporter reported, not just the library: a target
|
||||
# can write a database PLUS a per-track analysis file, and anything
|
||||
# left out here is an orphan the next re-export cannot clear.
|
||||
created.extend(written.all_paths)
|
||||
libraries.append((exporter.platform, written.library))
|
||||
|
||||
library_paths = {path for _, path in libraries}
|
||||
audio_paths = {Path(t.destination) for t in items}
|
||||
_write_manifest(
|
||||
destination,
|
||||
library=str(library.relative_to(destination)),
|
||||
libraries=[_rel(p, destination) for _, p in libraries],
|
||||
files=sorted(
|
||||
{str(p.relative_to(destination)) for p in created if p != library}
|
||||
{_rel(p, destination) for p in (*created, *audio_paths)
|
||||
if p not in library_paths and p.exists()}
|
||||
),
|
||||
audio={_rel(Path(t.destination), destination): _record(t, Path(t.destination))
|
||||
for t in items},
|
||||
name=export_set.name,
|
||||
)
|
||||
# Only what this export's tracks need; an unticked Pioneer target
|
||||
# keeps its entries, since they are keyed by source, not by target.
|
||||
cache.prune({_fingerprint(t) for t in items})
|
||||
return {
|
||||
"tracks": len(payload_tracks),
|
||||
"unchanged": len(reused),
|
||||
"playlists": len(built.playlists),
|
||||
"skipped": len(built.tracks) - len(items),
|
||||
"destination": str(destination),
|
||||
"library": str(library),
|
||||
"libraries": [
|
||||
{"platform": platform, "library": _rel(path, destination)}
|
||||
for platform, path in libraries
|
||||
],
|
||||
}
|
||||
except BaseException:
|
||||
# Cancelled or failed: leave no library file and no half-written copies.
|
||||
# Matches import, deliberately — two features whose cancel means
|
||||
# different things is worse than either behaviour on its own.
|
||||
for path in created:
|
||||
leftovers = (_files(destination) - before) if before is not None else set()
|
||||
for path in (*created, *leftovers):
|
||||
if CACHE_DIR in path.relative_to(destination).parts:
|
||||
continue # measurements of the SOURCE: still true, and ours
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
manifest_path(destination).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
if kept:
|
||||
# The previous export's files this one kept are still here, so the
|
||||
# folder must still say it is ours — with no library, which is what
|
||||
# marks an export unfinished.
|
||||
_write_manifest(
|
||||
destination, libraries=[], name=export_set.name,
|
||||
files=sorted(_rel(p, destination) for p in kept),
|
||||
audio={_rel(p, destination): r for p, r in kept.items()},
|
||||
)
|
||||
else:
|
||||
# Nothing kept: the folder goes back to having no export in it at
|
||||
# all, cache included, as a first export's cancel always has.
|
||||
cache.clear()
|
||||
try:
|
||||
manifest_path(destination).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
_prune_empty(destination)
|
||||
raise
|
||||
|
||||
|
||||
def _move_kept(destination: Path, reused: list[PlannedTrack], kept: dict[Path, dict]) -> None:
|
||||
"""Rename each kept copy to where this export puts it — instant on one drive.
|
||||
|
||||
In two steps, through a staging folder, because one kept file's new path
|
||||
can be another's old one (the shared root moved), and a direct rename
|
||||
would overwrite a copy that has not moved out of the way yet. `kept` is
|
||||
updated after every rename, so a failure part-way still knows where each
|
||||
file really is.
|
||||
"""
|
||||
moving = [t for t in reused if t.reuse != Path(t.destination)]
|
||||
staged: list[tuple[Path, PlannedTrack]] = []
|
||||
for i, planned in enumerate(moving):
|
||||
stage = _staging(destination, i)
|
||||
stage.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(planned.reuse, stage)
|
||||
kept[stage] = kept.pop(planned.reuse)
|
||||
staged.append((stage, planned))
|
||||
for stage, planned in staged:
|
||||
target = Path(planned.destination)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(stage, target)
|
||||
kept[target] = kept.pop(stage)
|
||||
if staged:
|
||||
_prune_empty(destination)
|
||||
|
||||
|
||||
def _staging(destination: Path, i: int) -> Path:
|
||||
return destination / MOVING_DIR / str(i)
|
||||
|
||||
|
||||
def _partial(target: Path) -> Path:
|
||||
return target.with_name(target.name + PARTIAL_SUFFIX)
|
||||
|
||||
|
||||
def _rel(path: Path, destination: Path) -> str:
|
||||
return str(Path(path).relative_to(destination))
|
||||
|
||||
|
||||
def _fingerprint(planned: PlannedTrack) -> str:
|
||||
return fingerprint(planned.source_path, planned.size, planned.mtime_ns)
|
||||
|
||||
|
||||
def _cover(adapter, track_id: str):
|
||||
"""The source's cover art, or None. A missing or unreadable cover costs the
|
||||
artwork on the stick, never the export."""
|
||||
try:
|
||||
return adapter.cover_art(track_id)
|
||||
except Exception as ex: # noqa: BLE001
|
||||
log.warning("no cover art for %s: %s", track_id, ex)
|
||||
return None
|
||||
|
||||
|
||||
def _files(root: Path) -> set[Path]:
|
||||
try:
|
||||
return {p for p in root.rglob("*") if p.is_file()}
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
|
||||
def _display_name(platform: str) -> str:
|
||||
try:
|
||||
return registry.driver_by_platform(platform).display_name
|
||||
except registry.LibraryNotSupported:
|
||||
return platform
|
||||
|
||||
|
||||
def space_for(built: ExportPlan) -> int | None:
|
||||
return free_bytes(Path(built.destination)) if built.destination else None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BLOCKED_EMPTY", "BLOCKED_NO_TARGET", "BLOCKED_OCCUPIED", "ExportPlan",
|
||||
"AUDIO_DIR", "BLOCKED_EMPTY", "BLOCKED_NO_TARGET", "BLOCKED_OCCUPIED", "ExportPlan",
|
||||
"MANIFEST_NAME", "PlannedTrack", "destination_blocked", "is_ours", "plan",
|
||||
"run", "space_for",
|
||||
]
|
||||
@@ -1,7 +1,12 @@
|
||||
"""Export sets: a named, persisted slice of the library, bound to a destination.
|
||||
|
||||
An export set is what the user curates before exporting — a name, a target
|
||||
platform, a destination folder, and the tracks and playlists to include. It is
|
||||
An export set is what the user curates before exporting — a name, one or more
|
||||
target platforms, a destination folder, and the tracks and playlists to include.
|
||||
|
||||
**Several targets share one destination and one copy of the audio.** Each
|
||||
target's library references the same files, and none of their layouts collide
|
||||
(`collection.nml`; `PIONEER/…`; `master.db` + `share/…`), so a stick carrying
|
||||
both a Traktor collection and a OneLibrary library costs one copy, not two. It is
|
||||
**Konduktor's own data**, never written into the user's library: a Traktor
|
||||
collection has nowhere to put this, and putting it there would mean a concept
|
||||
only Konduktor understands living in a file Traktor rewrites.
|
||||
@@ -51,8 +56,10 @@ class ExportSet:
|
||||
|
||||
id: str
|
||||
name: str
|
||||
target: str # platform id of the export TARGET, e.g. "traktor"
|
||||
destination: str # OS path of the folder the export is written into
|
||||
#: Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
|
||||
#: empty; ordered as the user ticked them, which is the order they are written.
|
||||
targets: list[str] = field(default_factory=lambda: ["traktor"])
|
||||
destination: str = "" # OS path of the folder the export is written into
|
||||
playlist_ids: list[str] = field(default_factory=list)
|
||||
track_ids: list[str] = field(default_factory=list) # loose tracks only
|
||||
created: float = 0.0
|
||||
@@ -128,7 +135,7 @@ def _load(library_id: str) -> dict[str, ExportSet]:
|
||||
out[set_id] = ExportSet(
|
||||
id=set_id,
|
||||
name=values.get("name") or "Untitled",
|
||||
target=values.get("target") or "traktor",
|
||||
targets=_targets(values),
|
||||
destination=values.get("destination") or "",
|
||||
playlist_ids=list(values.get("playlist_ids") or []),
|
||||
track_ids=list(values.get("track_ids") or []),
|
||||
@@ -140,6 +147,16 @@ def _load(library_id: str) -> dict[str, ExportSet]:
|
||||
return out
|
||||
|
||||
|
||||
def _targets(values: dict) -> list[str]:
|
||||
"""The set's targets, reading the single `target` sets were saved with first."""
|
||||
raw = values.get("targets")
|
||||
if isinstance(raw, list):
|
||||
found = [t for t in raw if isinstance(t, str) and t]
|
||||
if found:
|
||||
return found
|
||||
return [values.get("target") or "traktor"]
|
||||
|
||||
|
||||
def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
|
||||
paths.write_json(
|
||||
_store_path(library_id),
|
||||
@@ -186,13 +203,13 @@ def _normalise(destination: str) -> str:
|
||||
# ---- writing -----------------------------------------------------------------
|
||||
|
||||
|
||||
def create(library_id: str, *, name: str, target: str, destination: str) -> ExportSet:
|
||||
def create(library_id: str, *, name: str, targets: list[str], destination: str) -> ExportSet:
|
||||
sets = _load(library_id)
|
||||
now = time.time()
|
||||
created = ExportSet(
|
||||
id=uuid.uuid4().hex,
|
||||
name=name.strip() or "Untitled",
|
||||
target=target,
|
||||
targets=list(dict.fromkeys(targets)),
|
||||
destination=destination,
|
||||
created=now,
|
||||
modified=now,
|
||||
@@ -208,9 +225,11 @@ def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
|
||||
found = sets.get(set_id)
|
||||
if found is None:
|
||||
return None
|
||||
for key in ("name", "target", "destination"):
|
||||
for key in ("name", "destination"):
|
||||
if key in fields and fields[key] is not None:
|
||||
setattr(found, key, fields[key])
|
||||
if fields.get("targets"):
|
||||
found.targets = list(dict.fromkeys(fields["targets"]))
|
||||
found.modified = time.time()
|
||||
_save(library_id, sets)
|
||||
return found
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -49,12 +49,25 @@ class Job:
|
||||
# the UI is expected to show an indeterminate bar until it is positive.
|
||||
total: int = 0
|
||||
done: int = 0
|
||||
#: What `done`/`total` count — "bytes" while copying, "tracks" while a
|
||||
#: library is written — so the UI can word them. Empty = unspecified.
|
||||
unit: str = ""
|
||||
message: str = ""
|
||||
#: How far the CURRENT unit of work has got, 0..1 — so the overall bar can
|
||||
#: move within a long item: at 99 % of the first of two tracks it reads
|
||||
#: ~50 %, not 0. Reset whenever `done` advances.
|
||||
fraction: float = 0.0
|
||||
#: What the current item is doing ("separating 41 %"), shown beside its name
|
||||
#: and never truncated in its place. Reset whenever `done` advances.
|
||||
status: str = ""
|
||||
result: Any = None
|
||||
error: str | None = None
|
||||
started_at: float = field(default_factory=time.time)
|
||||
finished_at: float | None = None
|
||||
_cancel: threading.Event = field(default_factory=threading.Event, repr=False)
|
||||
#: Set once the thread has finished — cancelled, failed or done — so a caller
|
||||
#: that cancels can WAIT for the work to actually stop touching things.
|
||||
_done: threading.Event = field(default_factory=threading.Event, repr=False)
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
@@ -67,7 +80,10 @@ class Job:
|
||||
"state": self.state,
|
||||
"total": self.total,
|
||||
"done": self.done,
|
||||
"unit": self.unit,
|
||||
"message": self.message,
|
||||
"fraction": self.fraction,
|
||||
"status": self.status,
|
||||
"result": self.result,
|
||||
"error": self.error,
|
||||
"started_at": self.started_at,
|
||||
@@ -87,9 +103,19 @@ class JobHandle:
|
||||
self._job = job
|
||||
|
||||
def progress(self, done: int | None = None, total: int | None = None,
|
||||
message: str | None = None) -> None:
|
||||
message: str | None = None, unit: str | None = None,
|
||||
fraction: float | None = None, status: str | None = None) -> None:
|
||||
if unit is not None:
|
||||
self._job.unit = unit
|
||||
if done is not None:
|
||||
if done != self._job.done: # a new item: its progress starts over
|
||||
self._job.fraction = 0.0
|
||||
self._job.status = ""
|
||||
self._job.done = done
|
||||
if fraction is not None:
|
||||
self._job.fraction = max(0.0, min(1.0, fraction))
|
||||
if status is not None:
|
||||
self._job.status = status
|
||||
if total is not None:
|
||||
self._job.total = total
|
||||
if message is not None:
|
||||
@@ -112,14 +138,26 @@ class JobCancelled(Exception):
|
||||
"""
|
||||
|
||||
|
||||
class JobBusy(Exception):
|
||||
"""`submit(..., exclusive_with=...)` found one of those kinds running."""
|
||||
|
||||
|
||||
class JobRegistry:
|
||||
def __init__(self) -> None:
|
||||
self._jobs: dict[str, Job] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def submit(self, kind: str, fn: Callable[[JobHandle], Any]) -> Job:
|
||||
def submit(self, kind: str, fn: Callable[[JobHandle], Any], *,
|
||||
exclusive_with: tuple[str, ...] = ()) -> Job:
|
||||
"""Start `fn` on its own thread. With `exclusive_with`, refuse (JobBusy)
|
||||
if a job of any of those kinds is still running — checked and registered
|
||||
under ONE lock, so two requests arriving together cannot both start."""
|
||||
job = Job(id=uuid.uuid4().hex, kind=kind)
|
||||
with self._lock:
|
||||
if exclusive_with and any(
|
||||
not j.finished and j.kind in exclusive_with for j in self._jobs.values()
|
||||
):
|
||||
raise JobBusy(kind)
|
||||
self._jobs[job.id] = job
|
||||
self._prune()
|
||||
|
||||
@@ -136,6 +174,7 @@ class JobRegistry:
|
||||
job.error = str(ex) or ex.__class__.__name__
|
||||
finally:
|
||||
job.finished_at = time.time()
|
||||
job._done.set()
|
||||
|
||||
threading.Thread(target=run, name=f"job-{kind}-{job.id[:8]}", daemon=True).start()
|
||||
return job
|
||||
@@ -156,6 +195,12 @@ class JobRegistry:
|
||||
job._cancel.set()
|
||||
return True
|
||||
|
||||
def wait(self, job_id: str, timeout: float | None = None) -> bool:
|
||||
"""Block until the job has finished; False on timeout. An unknown id
|
||||
counts as finished (pruned jobs are long done)."""
|
||||
job = self.get(job_id)
|
||||
return True if job is None else job._done.wait(timeout)
|
||||
|
||||
def active(self, kind: str | None = None) -> list[Job]:
|
||||
with self._lock:
|
||||
return [
|
||||
|
||||
+397
-25
@@ -6,6 +6,7 @@ in the environment auto-loads that file on startup (used by dev and tests).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
@@ -30,9 +31,14 @@ from .core.adapter import (
|
||||
Unsupported,
|
||||
)
|
||||
from .core.capabilities import Capabilities
|
||||
from .jobs import JOBS
|
||||
from .jobs import JOBS, Job, JobBusy
|
||||
from .core.pathmap import PathMapping
|
||||
from .schemas import (
|
||||
Relocation,
|
||||
RelocationApplied,
|
||||
RelocationApply,
|
||||
RelocationCandidate,
|
||||
RelocationVolume,
|
||||
AutoGridBatchRequest,
|
||||
AutoGridRequest,
|
||||
AutoCueOutcome,
|
||||
@@ -83,14 +89,20 @@ from .schemas import (
|
||||
SourceCandidate,
|
||||
SourceStatus,
|
||||
SetCue,
|
||||
SetCueColor,
|
||||
SetCueType,
|
||||
SetGridLock,
|
||||
Stats,
|
||||
Track,
|
||||
TrackCues,
|
||||
TrackPage,
|
||||
StemEngineInstall,
|
||||
StemSideLoad,
|
||||
StemConvert,
|
||||
)
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI(title="Konduktor API", version=__version__)
|
||||
|
||||
app.add_middleware(
|
||||
@@ -154,10 +166,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
|
||||
# This checks only that the path is there at all; `can_open()` decides.
|
||||
if not path.exists():
|
||||
raise HTTPException(400, f"Not found: {path}")
|
||||
# A running analysis writes into the library being replaced; stop it.
|
||||
for kind in BATCH_JOBS:
|
||||
for job in JOBS.active(kind):
|
||||
JOBS.cancel(job.id)
|
||||
_stop_batches()
|
||||
try:
|
||||
STATE.open(path)
|
||||
except AdapterError as ex:
|
||||
@@ -209,6 +218,7 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
|
||||
"""Set (or, with blank prefixes, clear) the current collection's remapping.
|
||||
Persists to userprefs AND updates the live store so playback/analysis
|
||||
re-resolve immediately — no reopen needed. Never touches the .nml."""
|
||||
_require_no_pending_stems("Changing the path mapping")
|
||||
a = require_adapter()
|
||||
mapping = PathMapping.make(body.from_, body.to)
|
||||
prefs.set_path_mapping(
|
||||
@@ -244,6 +254,7 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
|
||||
playlist references that join to them) to the `to` prefix, then save (a
|
||||
version-history commit is written). Destructive and OS-specific — the UI
|
||||
warns accordingly."""
|
||||
_require_no_pending_stems("Rewriting paths")
|
||||
mapping = PathMapping.make(body.from_, body.to)
|
||||
if mapping.empty:
|
||||
raise HTTPException(400, "Both a `from` and `to` prefix are required")
|
||||
@@ -265,6 +276,58 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
|
||||
return RemapResult(rewritten=len(moved), commit=commit)
|
||||
|
||||
|
||||
@app.get("/api/library/relocation", response_model=Relocation)
|
||||
def get_relocation() -> Relocation:
|
||||
"""The open-time missing-files check: every stored volume in which NO track
|
||||
resolves, and where the search found its tracks. Empty once answered, so the
|
||||
UI can refetch freely without re-asking.
|
||||
|
||||
Waits briefly for the search, then reports `scanning` so a slow drive
|
||||
cannot hold a request open; the UI polls until it is done.
|
||||
"""
|
||||
require_adapter()
|
||||
check = STATE.relocation
|
||||
if check is None:
|
||||
return Relocation()
|
||||
if not check.wait(timeout=10):
|
||||
return Relocation(scanning=True)
|
||||
return Relocation(
|
||||
volumes=[
|
||||
RelocationVolume(
|
||||
label=p.label,
|
||||
root=p.root,
|
||||
total=p.total,
|
||||
status=p.status,
|
||||
candidates=[
|
||||
RelocationCandidate.model_validate(
|
||||
{"from": c.mapping.from_prefix, "to": c.mapping.to_prefix, "found": c.found}
|
||||
)
|
||||
for c in p.candidates
|
||||
],
|
||||
)
|
||||
for p in check.pending
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/library/relocation", response_model=RelocationApplied)
|
||||
def answer_relocation(body: RelocationApply) -> RelocationApplied:
|
||||
"""Answer the check: apply the chosen mappings for THIS SESSION only (no
|
||||
mappings = "Not now"). Nothing is written to the library or to prefs, and a
|
||||
reopen asks again."""
|
||||
_require_no_pending_stems("Relocating files")
|
||||
require_adapter()
|
||||
check = STATE.relocation
|
||||
if check is None:
|
||||
raise HTTPException(409, "There is no missing-files check to answer")
|
||||
mappings = [PathMapping.make(m.from_, m.to) for m in body.mappings]
|
||||
try:
|
||||
tracks = check.answer(mappings)
|
||||
except ValueError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
return RelocationApplied(mappings=len(mappings), tracks=tracks)
|
||||
|
||||
|
||||
@app.get("/api/prefs")
|
||||
def get_prefs() -> dict:
|
||||
"""The full persisted user-preferences blob (UI layout, last collection…)."""
|
||||
@@ -386,12 +449,11 @@ def create_export(body: CreateExportSet) -> ExportSetOut:
|
||||
# Only platforms that can actually be WRITTEN may be targets. Gating here as
|
||||
# well as in the UI, because a set persists: one created against a target
|
||||
# that later stops being supported would otherwise fail at export time.
|
||||
if body.target not in _export_targets():
|
||||
raise HTTPException(422, f"Konduktor cannot export to {body.target} yet")
|
||||
_check_targets(body.targets)
|
||||
created = exports.create(
|
||||
_require_library_id(),
|
||||
name=body.name,
|
||||
target=body.target,
|
||||
targets=body.targets,
|
||||
destination=body.destination,
|
||||
)
|
||||
return ExportSetOut(**created.as_dict())
|
||||
@@ -400,13 +462,13 @@ def create_export(body: CreateExportSet) -> ExportSetOut:
|
||||
@app.patch("/api/exports/{set_id}", response_model=ExportSetOut)
|
||||
def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut:
|
||||
_require_set(set_id)
|
||||
if body.target is not None and body.target not in _export_targets():
|
||||
raise HTTPException(422, f"Konduktor cannot export to {body.target} yet")
|
||||
if body.targets is not None:
|
||||
_check_targets(body.targets)
|
||||
updated = exports.update(
|
||||
_require_library_id(),
|
||||
set_id,
|
||||
name=body.name,
|
||||
target=body.target,
|
||||
targets=body.targets,
|
||||
destination=body.destination,
|
||||
)
|
||||
return ExportSetOut(**updated.as_dict())
|
||||
@@ -544,6 +606,19 @@ def _export_targets() -> set[str]:
|
||||
return core_export.targets()
|
||||
|
||||
|
||||
def _check_targets(targets: list[str]) -> None:
|
||||
"""Refuse a set with no targets, or one naming a platform with no exporter.
|
||||
|
||||
Checked when the set is saved: a target that later stops being supported
|
||||
would otherwise fail at export time.
|
||||
"""
|
||||
if not targets:
|
||||
raise HTTPException(400, "An export needs at least one platform to export for")
|
||||
unsupported = [t for t in targets if t not in _export_targets()]
|
||||
if unsupported:
|
||||
raise HTTPException(422, f"Konduktor cannot export to {', '.join(unsupported)} yet")
|
||||
|
||||
|
||||
@app.get("/api/export-targets", response_model=list[PlatformOption])
|
||||
def export_targets() -> list[PlatformOption]:
|
||||
"""Every platform, flagged by whether it can be an export TARGET.
|
||||
@@ -553,18 +628,41 @@ def export_targets() -> list[PlatformOption]:
|
||||
absent option reads as a missing feature; a disabled one reads as a roadmap.
|
||||
"""
|
||||
supported = _export_targets()
|
||||
return [
|
||||
PlatformOption(
|
||||
options = []
|
||||
for d in registry.drivers():
|
||||
exporter = core_export.for_platform(d.platform)
|
||||
options.append(PlatformOption(
|
||||
platform=d.platform,
|
||||
name=d.display_name,
|
||||
name=getattr(exporter, "display_name", None) or d.display_name,
|
||||
library_label=getattr(d, "library_label", ""),
|
||||
selects="directory", # an export destination is always a folder
|
||||
installed=d.platform in supported,
|
||||
found=0,
|
||||
removable=bool(getattr(d, "removable", False)),
|
||||
)
|
||||
for d in registry.drivers()
|
||||
]
|
||||
drive_root=bool(getattr(exporter, "drive_root", False)),
|
||||
computer_only=bool(getattr(exporter, "computer_only", False)),
|
||||
))
|
||||
# Targets with no reader of their own (the stick's legacy Device Library):
|
||||
# listed too, or registering one would not make it selectable.
|
||||
readers = {d.platform for d in registry.drivers()}
|
||||
order = {e.platform: getattr(e, "menu_order", 1000) for e in core_export.exporters()}
|
||||
for exporter in core_export.exporters():
|
||||
if exporter.platform in readers:
|
||||
continue
|
||||
options.append(PlatformOption(
|
||||
platform=exporter.platform,
|
||||
name=getattr(exporter, "display_name", exporter.platform),
|
||||
library_label="",
|
||||
selects="directory",
|
||||
installed=True,
|
||||
found=0,
|
||||
removable=bool(getattr(exporter, "drive_root", False)),
|
||||
drive_root=bool(getattr(exporter, "drive_root", False)),
|
||||
computer_only=bool(getattr(exporter, "computer_only", False)),
|
||||
))
|
||||
# Each exporter states its own place; a platform with no exporter (not yet a
|
||||
# target, shown disabled) goes last. Stable, so equal places keep their order.
|
||||
return sorted(options, key=lambda o: order.get(o.platform, 1000))
|
||||
|
||||
|
||||
# ---- health / state ---------------------------------------------------
|
||||
@@ -636,11 +734,196 @@ def capabilities() -> Capabilities:
|
||||
|
||||
@app.get("/api/state", response_model=EditState)
|
||||
def state() -> EditState:
|
||||
return EditState(dirty=require_adapter().dirty, library=_library_info())
|
||||
stem_job = JOBS.active(STEM_JOB)
|
||||
pending = STATE.pending.summary() if STATE.pending is not None else None
|
||||
return EditState(dirty=require_adapter().dirty, library=_library_info(),
|
||||
pending_stems=pending if pending and pending["tracks"] else None,
|
||||
stem_job=stem_job[0].id if stem_job else None,
|
||||
stem_recovery=STATE.recovery)
|
||||
|
||||
|
||||
# ---- stem engine (download / side-load / remove) --------------------------
|
||||
# The engine and its weights live outside the app (see stems/engine_manager.py).
|
||||
ENGINE_JOB = "stem-engine-install"
|
||||
STEM_JOB = "stem-conversion"
|
||||
|
||||
|
||||
@app.get("/api/stems/engine")
|
||||
def stem_engine_status() -> dict:
|
||||
"""What is installed, what this computer can run, and what a download costs."""
|
||||
from .stems import engine_manager as em
|
||||
|
||||
mgr = em.default_manager()
|
||||
running = JOBS.active(ENGINE_JOB)
|
||||
return {**mgr.status(), "device": prefs.load_prefs().get("stemDevice", "auto"),
|
||||
"install_job": running[0].id if running else None}
|
||||
|
||||
|
||||
@app.post("/api/stems/engine/install", response_model=JobStatus)
|
||||
def install_stem_engine(body: StemEngineInstall) -> JobStatus:
|
||||
"""Download the engine (and the weights) as a job, in bytes."""
|
||||
from .jobs import JobCancelled
|
||||
from .stems import download
|
||||
from .stems import engine_manager as em
|
||||
|
||||
mgr = em.default_manager()
|
||||
if mgr.base_target is None:
|
||||
raise HTTPException(422, "There is no stem engine for this computer")
|
||||
target = body.target or mgr.base_target
|
||||
if target not in mgr.status(network=False)["offered_targets"]:
|
||||
raise HTTPException(400, f"The {target} engine is not offered on this computer")
|
||||
|
||||
def run(handle):
|
||||
info = mgr.target_info(target)
|
||||
if info is None:
|
||||
raise em.EngineError("Could not reach the engine download — check the internet connection")
|
||||
installed = mgr.installed()
|
||||
need_engine = not (installed and installed["target"] == target)
|
||||
need_weights = body.weights and not mgr.weights_installed()
|
||||
total = (info["size"] if need_engine else 0) + (mgr.weights_size() if need_weights else 0)
|
||||
handle.progress(done=0, total=total, unit="bytes", message="Downloading the stem engine…")
|
||||
done = [0]
|
||||
|
||||
def on_bytes(n: int) -> None:
|
||||
done[0] += n
|
||||
handle.progress(done=done[0])
|
||||
|
||||
try:
|
||||
if need_engine:
|
||||
mgr.install_engine(target, on_bytes=on_bytes, cancelled=lambda: handle.cancelled)
|
||||
if need_weights:
|
||||
handle.progress(message="Downloading the separation model…")
|
||||
mgr.install_weights(on_bytes=on_bytes, cancelled=lambda: handle.cancelled)
|
||||
except download.DownloadCancelled:
|
||||
raise JobCancelled()
|
||||
return {"target": target, "ready": mgr.ready()}
|
||||
|
||||
try:
|
||||
job = JOBS.submit(ENGINE_JOB, run, exclusive_with=(ENGINE_JOB, STEM_JOB))
|
||||
except JobBusy:
|
||||
raise HTTPException(409, "The stem engine is already downloading, or a conversion is running")
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
def _require_no_pending_stems(what: str) -> None:
|
||||
"""Refuse an operation that would SAVE or DROP a stem conversion's swap as a
|
||||
side effect — import and remap save pending edits, reload and restore drop
|
||||
them — while converted tracks await Save/Discard or a conversion runs."""
|
||||
if JOBS.active(STEM_JOB):
|
||||
raise HTTPException(409, f"{what} is not possible while tracks are being converted to stems")
|
||||
if STATE.pending is not None and STATE.pending.blocking():
|
||||
raise HTTPException(409, f"{what} is not possible until the converted tracks are saved or discarded")
|
||||
|
||||
|
||||
def _stem_options(body):
|
||||
from .stems import convert
|
||||
|
||||
return convert.Options(
|
||||
mode=body.mode, destination=Path(body.destination).expanduser() if body.destination else None,
|
||||
collection=body.collection, playlist_id=body.playlist_id, new_playlist=body.new_playlist,
|
||||
device=prefs.load_prefs().get("stemDevice", "auto"),
|
||||
)
|
||||
|
||||
|
||||
def _stem_plan(body):
|
||||
from .stems import convert
|
||||
|
||||
adapter = require_adapter()
|
||||
caps = adapter.capabilities()
|
||||
if not (caps.writable and caps.tracks.stem_convertible):
|
||||
raise HTTPException(422, "This library cannot hold stem files")
|
||||
try:
|
||||
return adapter, convert.plan(adapter, body.track_ids, _stem_options(body), STATE.pending)
|
||||
except convert.ConvertError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
|
||||
|
||||
@app.post("/api/tracks/stems/preview")
|
||||
def preview_stem_conversion(body: StemConvert) -> dict:
|
||||
"""What a conversion would do — converted, skipped (and why), disk space."""
|
||||
_adapter, planned = _stem_plan(body)
|
||||
return planned.as_dict()
|
||||
|
||||
|
||||
@app.post("/api/tracks/stems/convert", response_model=JobStatus)
|
||||
def convert_to_stems(body: StemConvert) -> JobStatus:
|
||||
"""Convert tracks to stem files as a job; the swap lands at its end."""
|
||||
from .stems import convert
|
||||
from .stems import engine_manager as em
|
||||
|
||||
_require_no_batch()
|
||||
if JOBS.active("import"):
|
||||
raise HTTPException(409, "Wait for the import to finish")
|
||||
adapter, planned = _stem_plan(body)
|
||||
if planned.blocked:
|
||||
raise HTTPException(409, planned.blocked)
|
||||
if not planned.items:
|
||||
raise HTTPException(400, "None of these tracks can be converted")
|
||||
if any(p.reuse is None for p in planned.items) and not em.default_manager().ready():
|
||||
raise HTTPException(409, "The stem engine is not installed")
|
||||
opts = _stem_options(body)
|
||||
|
||||
def run(handle):
|
||||
return convert.run(handle, adapter, planned, opts, STATE.pending, mutation=STATE.mutation,
|
||||
still_current=lambda: STATE.adapter is adapter)
|
||||
|
||||
try:
|
||||
job = JOBS.submit(STEM_JOB, run, exclusive_with=BATCH_JOBS + (ENGINE_JOB, "import"))
|
||||
except JobBusy:
|
||||
raise HTTPException(409, "Another batch, download or import is running")
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
@app.post("/api/stems/engine/sideload")
|
||||
def side_load_stem_engine(body: StemSideLoad) -> dict:
|
||||
"""Install the engine or the weights from files the user already has."""
|
||||
from .stems import engine_manager as em
|
||||
|
||||
if JOBS.active(ENGINE_JOB) or JOBS.active(STEM_JOB):
|
||||
raise HTTPException(409, "Wait for the running download or conversion to finish")
|
||||
mgr = em.default_manager()
|
||||
path = Path(body.path).expanduser()
|
||||
if not path.exists():
|
||||
raise HTTPException(400, f"Not found: {path}")
|
||||
try:
|
||||
if body.kind == "engine":
|
||||
mgr.side_load_engine(path)
|
||||
else:
|
||||
mgr.side_load_weights(path)
|
||||
except em.EngineError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
return stem_engine_status()
|
||||
|
||||
|
||||
@app.delete("/api/stems/engine")
|
||||
def remove_stem_engine() -> dict:
|
||||
from .stems import engine_manager as em
|
||||
|
||||
if JOBS.active(ENGINE_JOB) or JOBS.active(STEM_JOB):
|
||||
raise HTTPException(409, "Wait for the running download or conversion to finish")
|
||||
em.default_manager().remove()
|
||||
return stem_engine_status()
|
||||
|
||||
|
||||
@app.post("/api/discard", response_model=EditState)
|
||||
def discard_changes() -> EditState:
|
||||
"""Drop every unsaved edit — the library re-reads itself from disk.
|
||||
|
||||
A running batch is stopped first (and waited for): it writes into the
|
||||
library being discarded, so it would otherwise keep adding edits to the
|
||||
freshly reloaded one.
|
||||
"""
|
||||
adapter = require_adapter()
|
||||
if not adapter.capabilities().writable:
|
||||
raise HTTPException(409, "This library cannot be edited, so there is nothing to discard")
|
||||
_stop_batches()
|
||||
STATE.discard()
|
||||
return state()
|
||||
|
||||
|
||||
@app.post("/api/reload")
|
||||
def reload_collection() -> dict:
|
||||
_require_no_pending_stems("Reloading")
|
||||
if not STATE.loaded:
|
||||
raise HTTPException(409, "No collection loaded")
|
||||
STATE.open(STATE.path) # re-parse current file from disk
|
||||
@@ -797,14 +1080,47 @@ _AUDIO_MIME = {
|
||||
}
|
||||
|
||||
|
||||
def _stem_audio(path: Path, stem: int) -> FileResponse:
|
||||
"""One stem of a stem file as a file of its own (see stems/stream_cache.py):
|
||||
a browser only ever decodes an MP4's first stream, which is the mix."""
|
||||
from .core import stem_file
|
||||
from .stems import stream_cache
|
||||
|
||||
layout = stem_file.stem_layout(path)
|
||||
if layout is None or not 0 <= stem < len(layout):
|
||||
raise HTTPException(404, "That file has no such stem")
|
||||
try:
|
||||
return FileResponse(stream_cache.stem_file_for(path, stem), media_type="audio/mp4")
|
||||
except (stem_file.StemFileError, OSError) as ex:
|
||||
raise HTTPException(500, f"Could not read the stem: {ex}")
|
||||
|
||||
|
||||
def _stem_layout_of(path: Path | None) -> dict:
|
||||
from .core import stem_file
|
||||
|
||||
if path is None or not path.exists():
|
||||
raise HTTPException(404, "Audio file not found")
|
||||
return {"stems": stem_file.stem_layout(path) or []}
|
||||
|
||||
|
||||
@app.get("/api/tracks/stems")
|
||||
def track_stems(track_id: str) -> dict:
|
||||
"""The stems a track's FILE carries for playback — `[{name, color}]`, empty
|
||||
for anything that is not a stem file (whatever the library says)."""
|
||||
return _stem_layout_of(require_adapter().audio_path(track_id))
|
||||
|
||||
|
||||
@app.get("/api/tracks/audio")
|
||||
def track_audio(track_id: str) -> FileResponse:
|
||||
"""Stream a track's audio file for playback (supports HTTP Range/seeking)."""
|
||||
def track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
"""Stream a track's audio file for playback (supports HTTP Range/seeking);
|
||||
with `stem`, that stem of a stem file (0-based) instead."""
|
||||
path = require_adapter().audio_path(track_id)
|
||||
if path is None:
|
||||
raise HTTPException(404, "Track not found")
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"Audio file not found: {path}")
|
||||
if stem is not None:
|
||||
return _stem_audio(path, stem)
|
||||
# .stem.m4a and other MP4s serve as audio/mp4; browsers play the first track.
|
||||
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
|
||||
# Cacheable so the waveform's decode-fetch and the <audio> element can share
|
||||
@@ -936,14 +1252,39 @@ class _AnalysisError(Exception):
|
||||
# beats that no longer exist.
|
||||
GRID_JOB = "grid-analysis"
|
||||
CUE_JOB = "auto-hotcues"
|
||||
BATCH_JOBS = (GRID_JOB, CUE_JOB)
|
||||
BATCH_JOBS = (GRID_JOB, CUE_JOB, STEM_JOB)
|
||||
|
||||
|
||||
def _stop_batches() -> None:
|
||||
"""Cancel every running batch analysis and WAIT for it to stop.
|
||||
|
||||
Used wherever the library is about to be replaced or reloaded: a job still
|
||||
finishing its current track would otherwise keep writing into it (or, for
|
||||
file work, keep moving files) afterwards. Batches check for a cancel
|
||||
between tracks, so this is short.
|
||||
"""
|
||||
stopping = [job for kind in BATCH_JOBS for job in JOBS.active(kind)]
|
||||
for job in stopping:
|
||||
JOBS.cancel(job.id)
|
||||
for job in stopping:
|
||||
if not JOBS.wait(job.id, timeout=60):
|
||||
log.warning("batch %s (%s) still running after cancel; continuing", job.id, job.kind)
|
||||
|
||||
|
||||
def _require_no_batch() -> None:
|
||||
"""An early, friendly refusal. Not race-free on its own — the batch routes
|
||||
START through `_submit_batch`, which re-checks under the registry's lock."""
|
||||
if any(JOBS.active(k) for k in BATCH_JOBS):
|
||||
raise HTTPException(409, "A batch analysis is already running")
|
||||
|
||||
|
||||
def _submit_batch(kind: str, run) -> "Job":
|
||||
try:
|
||||
return JOBS.submit(kind, run, exclusive_with=BATCH_JOBS)
|
||||
except JobBusy:
|
||||
raise HTTPException(409, "A batch analysis is already running")
|
||||
|
||||
|
||||
def _analyse_grid(a, track_id: str) -> TrackCues:
|
||||
"""Detect and write one track's grid — shared by the deck's Analyze and the
|
||||
batch job, so the two cannot come to mean different things."""
|
||||
@@ -999,7 +1340,7 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
|
||||
handle.progress(done=i + 1)
|
||||
return result
|
||||
|
||||
job = JOBS.submit(GRID_JOB, run)
|
||||
job = _submit_batch(GRID_JOB, run)
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
@@ -1050,7 +1391,7 @@ def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus:
|
||||
handle.progress(done=i + 1)
|
||||
return result
|
||||
|
||||
job = JOBS.submit(CUE_JOB, run)
|
||||
job = _submit_batch(CUE_JOB, run)
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
@@ -1060,6 +1401,12 @@ def edit_cue_type(body: SetCueType) -> TrackCues:
|
||||
return require_adapter().set_cue_type(body.track_id, body.slot, body.type)
|
||||
|
||||
|
||||
@app.patch("/api/tracks/cue/color", response_model=TrackCues)
|
||||
def edit_cue_color(body: SetCueColor) -> TrackCues:
|
||||
"""Recolour an existing cue from the platform's palette (None = uncoloured)."""
|
||||
return require_adapter().set_cue_color(body.track_id, body.slot, body.color)
|
||||
|
||||
|
||||
@app.delete("/api/tracks/cue", response_model=TrackCues)
|
||||
def delete_cue(track_id: str, slot: int) -> TrackCues:
|
||||
"""Remove the hotcue in a slot."""
|
||||
@@ -1222,6 +1569,7 @@ def restore_version(commit_id: str) -> CollectionStatus:
|
||||
"""Restore the collection to a past version. Writes that version back as a
|
||||
NEW forward save (a fresh commit on top of history — never a rewind), then
|
||||
reloads. The user should close Traktor first (it overwrites on exit)."""
|
||||
_require_no_pending_stems("Restoring a version")
|
||||
require_adapter()
|
||||
data = history.read_version(STATE.path, commit_id)
|
||||
if data is None:
|
||||
@@ -1390,7 +1738,7 @@ def source_track_cues(track_id: str) -> TrackCues:
|
||||
|
||||
|
||||
@app.get("/api/source/tracks/audio")
|
||||
def source_track_audio(track_id: str) -> FileResponse:
|
||||
def source_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
"""Stream a track's audio straight off the source drive.
|
||||
|
||||
So the deck can audition a track BEFORE importing it, which is most of the
|
||||
@@ -1402,10 +1750,17 @@ def source_track_audio(track_id: str) -> FileResponse:
|
||||
raise HTTPException(404, "Track not found")
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"Audio file not found: {path}")
|
||||
if stem is not None:
|
||||
return _stem_audio(path, stem)
|
||||
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
|
||||
return FileResponse(path, media_type=mime)
|
||||
|
||||
|
||||
@app.get("/api/source/tracks/stems")
|
||||
def source_track_stems(track_id: str) -> dict:
|
||||
return _stem_layout_of(require_source().audio_path(track_id))
|
||||
|
||||
|
||||
# ---- drives and folders -----------------------------------------------
|
||||
#
|
||||
# The sidebar's Devices and Local Storage trees. Browsing a folder is READ-ONLY
|
||||
@@ -1505,16 +1860,30 @@ def folder_track_cues(track_id: str) -> TrackCues:
|
||||
|
||||
|
||||
@app.get("/api/folder/tracks/audio")
|
||||
def folder_track_audio(track_id: str) -> FileResponse:
|
||||
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
path = _folder_track(track_id).audio_path(track_id)
|
||||
if path is None or not path.is_file():
|
||||
raise HTTPException(404, "Audio file not found")
|
||||
if stem is not None:
|
||||
return _stem_audio(path, stem)
|
||||
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
|
||||
return FileResponse(path, media_type=mime)
|
||||
|
||||
|
||||
@app.get("/api/folder/tracks/stems")
|
||||
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)
|
||||
@@ -1554,6 +1923,7 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
@app.post("/api/folder/add", response_model=JobStatus)
|
||||
def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
"""Add browsed files to the collection. A job, like import: copying can be long."""
|
||||
_require_no_pending_stems("Adding files")
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
if not plan.importable and not plan.existing:
|
||||
raise HTTPException(400, "Nothing to add (none of those files exist)")
|
||||
@@ -1594,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,
|
||||
@@ -1618,6 +1989,7 @@ def import_preview(body: ImportRequest) -> dict:
|
||||
@app.post("/api/import", response_model=JobStatus)
|
||||
def start_import(body: ImportRequest) -> JobStatus:
|
||||
"""Start an import. Returns immediately; poll the job for progress."""
|
||||
_require_no_pending_stems("Importing")
|
||||
source, dest, destination, plan = _import_plan(body)
|
||||
if not plan.importable:
|
||||
raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)")
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""The open-time missing-files check: search on open, ask once, apply for the session.
|
||||
|
||||
When a library opens, a thread asks the adapter which stored volumes resolve
|
||||
nothing and searches for where their tracks went (`core/relocate.py`). The
|
||||
result waits here until the user answers the confirmation dialog — Apply or
|
||||
Not now — and is then settled for the rest of this open. Reopening the library
|
||||
creates a new adapter and so a new check, which is how "ask again when the
|
||||
library is reopened" holds without anything being remembered.
|
||||
|
||||
It lives on `AppState` rather than in the UI because "once per open" is a fact
|
||||
about the open, which happens here: a UI deciding it would re-ask on every
|
||||
refetch of the query that shows the dialog.
|
||||
|
||||
The mappings it applies are session-only by design. They are never written to
|
||||
the library (that would change every Traktor track id) nor to prefs; the saved
|
||||
mapping in the Path Remapping dialog is the way to make one stick.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from .core import places
|
||||
from .core.pathmap import PathMapping
|
||||
from .core.relocate import Proposal, search
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def candidate_roots() -> list[Path]:
|
||||
"""Where a library's missing audio might now be: every drive, plus the
|
||||
user's home and Music folders (a library copied into ~/Music keeps its own
|
||||
layout beneath it)."""
|
||||
roots = [Path(d["path"]) for d in places.drives()]
|
||||
roots += [Path(p["path"]) for p in places.user_places() if p["kind"] in ("home", "music")]
|
||||
return roots
|
||||
|
||||
|
||||
class RelocationCheck:
|
||||
"""One library open's check. Starts searching as soon as it is made."""
|
||||
|
||||
def __init__(self, adapter) -> None:
|
||||
self.adapter = adapter
|
||||
self._done = threading.Event()
|
||||
self._proposals: list[Proposal] = []
|
||||
self._answered = False
|
||||
self._lock = threading.Lock()
|
||||
threading.Thread(target=self._run, name="relocation-check", daemon=True).start()
|
||||
|
||||
def _run(self) -> None:
|
||||
try:
|
||||
groups = self.adapter.unresolved_path_groups()
|
||||
if groups:
|
||||
self._proposals = search(groups, candidate_roots())
|
||||
except Exception: # noqa: BLE001 — a failed check must never break an open
|
||||
log.exception("missing-files check failed")
|
||||
finally:
|
||||
self._done.set()
|
||||
|
||||
def wait(self, timeout: float) -> bool:
|
||||
"""Whether the search has finished, waiting up to `timeout` seconds."""
|
||||
return self._done.wait(timeout)
|
||||
|
||||
@property
|
||||
def pending(self) -> list[Proposal]:
|
||||
"""What still needs the user's answer: nothing once answered."""
|
||||
if not self._done.is_set() or self._answered:
|
||||
return []
|
||||
return self._proposals
|
||||
|
||||
def answer(self, mappings: list[PathMapping]) -> int:
|
||||
"""Apply the user's choice (empty = Not now) and settle the check.
|
||||
|
||||
Returns how many tracks the applied mappings resolve. Refuses a mapping
|
||||
the search did not propose, and two for one volume.
|
||||
"""
|
||||
with self._lock:
|
||||
if not self._done.is_set():
|
||||
raise ValueError("The missing-files check is still running")
|
||||
if self._answered:
|
||||
raise ValueError("The missing-files check has already been answered")
|
||||
chosen = []
|
||||
volumes: set[str] = set()
|
||||
for m in mappings:
|
||||
match = next(
|
||||
(
|
||||
(p, c)
|
||||
for p in self._proposals
|
||||
for c in p.candidates
|
||||
if c.mapping == m
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise ValueError(f"Not a proposed mapping: {m.from_prefix} → {m.to_prefix}")
|
||||
if match[0].root in volumes:
|
||||
raise ValueError(f"Two mappings chosen for {match[0].label}")
|
||||
volumes.add(match[0].root)
|
||||
chosen.append(match[1])
|
||||
self.adapter.set_session_mappings([c.mapping for c in chosen])
|
||||
self._answered = True
|
||||
return sum(c.found for c in chosen)
|
||||
@@ -146,9 +146,47 @@ class SetCueType(BaseModel):
|
||||
type: CueType
|
||||
|
||||
|
||||
class SetCueColor(BaseModel):
|
||||
track_id: str
|
||||
slot: int
|
||||
color: str | None = None # a capabilities.cues.palette entry; None = uncoloured
|
||||
|
||||
|
||||
class StemEngineInstall(BaseModel):
|
||||
# None = this computer's default engine; "windows-x64-cuda" to take the GPU one.
|
||||
target: str | None = None
|
||||
# Also fetch the model weights (the engine is useless without them).
|
||||
weights: bool = True
|
||||
|
||||
|
||||
class StemSideLoad(BaseModel):
|
||||
path: str
|
||||
kind: Literal["engine", "weights"]
|
||||
|
||||
|
||||
class StemConvert(BaseModel):
|
||||
track_ids: list[str]
|
||||
# "replace": the stem file supersedes the original where it lives (the
|
||||
# original is parked until Save deletes it); "destination": a chosen folder,
|
||||
# originals never touched.
|
||||
mode: Literal["replace", "destination"]
|
||||
destination: str | None = None
|
||||
# "repoint": the entry now names the stem file; "add": a new entry beside it
|
||||
# (destination mode only).
|
||||
collection: Literal["repoint", "add"] = "repoint"
|
||||
playlist_id: str | None = None # add mode: into this existing playlist…
|
||||
new_playlist: str | None = None # …or a new one with this name
|
||||
|
||||
|
||||
class EditState(BaseModel):
|
||||
dirty: bool # unsaved in-memory changes exist
|
||||
library: LibraryInfo
|
||||
# Converted tracks awaiting Save/Discard: {tracks, parked, bytes}.
|
||||
pending_stems: dict | None = None
|
||||
# A running stem conversion's job id, so a reloaded page finds it again.
|
||||
stem_job: str | None = None
|
||||
# What this open's crash recovery did about an interrupted conversion.
|
||||
stem_recovery: dict | None = None
|
||||
|
||||
|
||||
# ---- collection selection ----
|
||||
@@ -196,7 +234,7 @@ class CollectionOptions(BaseModel):
|
||||
class ExportSetOut(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
target: str # platform id of the export TARGET
|
||||
targets: list[str] # platform ids of the export TARGETS, never empty
|
||||
destination: str
|
||||
playlist_ids: list[str] = []
|
||||
track_ids: list[str] = [] # loose tracks only
|
||||
@@ -206,13 +244,13 @@ class ExportSetOut(BaseModel):
|
||||
|
||||
class CreateExportSet(BaseModel):
|
||||
name: str
|
||||
target: str = "traktor"
|
||||
targets: list[str] = ["traktor"]
|
||||
destination: str
|
||||
|
||||
|
||||
class UpdateExportSet(BaseModel):
|
||||
name: str | None = None
|
||||
target: str | None = None
|
||||
targets: list[str] | None = None
|
||||
destination: str | None = None
|
||||
|
||||
|
||||
@@ -258,6 +296,9 @@ class ExportPreview(BaseModel):
|
||||
blocked: str | None = None
|
||||
#: The destination already holds a Konduktor export, which will be replaced.
|
||||
replacing: bool = False
|
||||
#: Targets whose library is only found at a drive's root, when the
|
||||
#: destination is not one. A warning — the export can still run.
|
||||
not_drive_root: list[str] = []
|
||||
|
||||
|
||||
class FsPlace(BaseModel):
|
||||
@@ -299,6 +340,16 @@ class PathMappingInfo(BaseModel):
|
||||
to: str = ""
|
||||
|
||||
|
||||
class RelocationApply(BaseModel):
|
||||
"""The user's answer to the open-time missing-files check. Empty = "Not now".
|
||||
|
||||
Each mapping must be one the check proposed: this route applies an answer,
|
||||
it is not a second way to set an arbitrary mapping.
|
||||
"""
|
||||
|
||||
mappings: list[PathMappingInfo] = []
|
||||
|
||||
|
||||
class RemapResult(BaseModel):
|
||||
rewritten: int # tracks whose LOCATION was rewritten
|
||||
commit: str | None = None # sha of the version-history commit for the rewrite
|
||||
@@ -318,6 +369,10 @@ from .core.model import ( # noqa: E402,F401
|
||||
PlaylistNode,
|
||||
PrefixGroup,
|
||||
PrefixSuggestions,
|
||||
Relocation,
|
||||
RelocationApplied,
|
||||
RelocationCandidate,
|
||||
RelocationVolume,
|
||||
RemapPreview,
|
||||
RemapSample,
|
||||
Stats,
|
||||
@@ -429,7 +484,14 @@ class JobStatus(BaseModel):
|
||||
state: str # running | done | failed | cancelled
|
||||
total: int
|
||||
done: int
|
||||
# What done/total count ("bytes" / "tracks"; "" when unspecified). Declared
|
||||
# here or the response model silently drops the one field the status bar
|
||||
# needs to tell a byte count from a track count.
|
||||
unit: str = ""
|
||||
message: str
|
||||
# The current item's own progress (0..1) and what it is doing — see jobs.Job.
|
||||
fraction: float = 0.0
|
||||
status: str = ""
|
||||
result: dict | None = None
|
||||
error: str | None = None
|
||||
started_at: float
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Convert to Stems: everything outside the stem FILE itself.
|
||||
|
||||
`core/stem_file.py` writes a stem file from a separation callback; the Traktor
|
||||
adapter swaps it into the collection (`apply_stem_swaps`). This package is what
|
||||
sits around them: the downloadable engine and weights (`engine_manager`), the
|
||||
engine process (`engine_process`), and — next — the batch and the parked-
|
||||
originals lifecycle.
|
||||
"""
|
||||
@@ -0,0 +1,379 @@
|
||||
"""The Convert to Stems batch: plan it, run it, swap it in.
|
||||
|
||||
**The collection is untouched while tracks convert** — for hours, on a big batch
|
||||
— so edits made meanwhile carry over, and Cancel only deletes new files. Each
|
||||
track becomes a verified `<target>.konduktor-partial`. Then one short END STEP,
|
||||
under the app's mutation lock, publishes each file (a rename that refuses to
|
||||
overwrite), parks each original in Replace mode, and swaps every entry at once
|
||||
(`adapter.apply_stem_swaps`). From there the swap is an unsaved edit that Save
|
||||
commits and Discard undoes (`pending.py`).
|
||||
|
||||
Skipped and reported, never failed (decided): a file that is already a stem
|
||||
container (by its CONTENTS — the collection's `<STEMS>` element is on some
|
||||
plain MP3s), a missing file, a target that already exists, two sources that
|
||||
would write one target, a target the collection already names. A track that
|
||||
fails keeps its original and is reported; the rest carry on.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import shutil
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from .. import paths
|
||||
from ..core import stem_file as sf
|
||||
from ..core.adapter import AdapterError, StemSwap
|
||||
from ..core.pathmap import common_dir_prefix
|
||||
from ..importer import SPACE_HEADROOM, free_bytes
|
||||
from . import engine_manager as em
|
||||
from .engine_process import EngineCancelled, EngineProcess, keep_awake
|
||||
from .pending import Pending, _replace_no_overwrite, _retrying, parked_name, partial_name, source_facts
|
||||
|
||||
_LOSSLESS = (".wav", ".aif", ".aiff", ".flac")
|
||||
#: Five AAC streams at up to 320 kbps plus container overhead.
|
||||
_BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 * 1.03}
|
||||
#: Raw float32 stereo, mix + four stems, while a track is being separated.
|
||||
_WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR
|
||||
|
||||
|
||||
#: Shares of ONE track's conversion time, for the status bar's within-track
|
||||
#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode +
|
||||
#: verify ~4 s for a 4-minute track).
|
||||
_DECODE_SHARE = 0.03
|
||||
_SEPARATE_SHARE = 0.90
|
||||
|
||||
|
||||
class ConvertError(Exception):
|
||||
"""User-facing; refuses the whole batch."""
|
||||
|
||||
|
||||
class _Cancel(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Options:
|
||||
mode: str # "replace" | "destination"
|
||||
destination: Path | None = None
|
||||
collection: str = "repoint" # "repoint" | "add"
|
||||
playlist_id: str | None = None # add mode: an existing playlist
|
||||
new_playlist: str | None = None # add mode: create one with this name
|
||||
device: str = "auto"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Planned:
|
||||
track_id: str
|
||||
title: str
|
||||
source: Path
|
||||
target: Path
|
||||
seconds: float
|
||||
reuse: dict | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Plan:
|
||||
items: list[Planned] = field(default_factory=list)
|
||||
skipped: list[dict] = field(default_factory=list)
|
||||
space: list[dict] = field(default_factory=list)
|
||||
blocked: str | None = None
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {"convert": [{"track_id": p.track_id, "title": p.title, "target": str(p.target),
|
||||
"reuse": p.reuse is not None} for p in self.items],
|
||||
"skipped": self.skipped, "space": self.space, "blocked": self.blocked,
|
||||
# For the dialog's estimate: audio still to SEPARATE (reused
|
||||
# leftovers cost nothing), and what the new files will take.
|
||||
"seconds": sum(p.seconds for p in self.items if p.reuse is None),
|
||||
"bytes": sum(e["bytes"] for e in self.space),
|
||||
# What Save would delete in Replace mode — the dialog says so.
|
||||
"original_bytes": sum(p.source.stat().st_size for p in self.items if p.source.exists())}
|
||||
|
||||
|
||||
def _title(track) -> str:
|
||||
"""How a track is named in progress, skip lists and reports: the track's
|
||||
name FIRST — it is what tells one track from another when the end is cut
|
||||
off in the status bar."""
|
||||
if track is None:
|
||||
return "?"
|
||||
if track.artist and track.title:
|
||||
return f"{track.title} - {track.artist}"
|
||||
return track.title or Path(track.filepath or "").name or track.id
|
||||
|
||||
|
||||
def _mirror(sources: list[Path], destination: Path) -> dict[Path, Path]:
|
||||
"""Target folder per source: the source tree under `destination`, relative
|
||||
to the sources' common folder, so same-named files cannot collide. Tracks
|
||||
on different drives share no folder; each then keeps its full path (drive
|
||||
or volume first)."""
|
||||
prefix = common_dir_prefix([str(s) for s in sources])
|
||||
out: dict[Path, Path] = {}
|
||||
for s in sources:
|
||||
if prefix:
|
||||
rel = Path(str(s.parent)[len(prefix):].lstrip("/\\"))
|
||||
else:
|
||||
parts = s.parent.parts[1:]
|
||||
head = s.drive.rstrip(":") if s.drive else ""
|
||||
rel = Path(head, *parts) if head else Path(*parts)
|
||||
out[s] = destination / rel
|
||||
return out
|
||||
|
||||
|
||||
def _output_rate(track, source: Path) -> int:
|
||||
if source.suffix.lower() in _LOSSLESS:
|
||||
return 320_000
|
||||
bitrate = getattr(track, "bitrate", None) or 0
|
||||
return 256_000 if 0 < bitrate < 256_000 else 320_000
|
||||
|
||||
|
||||
def plan(adapter, track_ids: list[str], opts: Options, pending: Pending | None) -> Plan:
|
||||
"""What the batch would do, without touching anything."""
|
||||
result = Plan()
|
||||
if opts.mode not in ("replace", "destination"):
|
||||
raise ConvertError(f"Unknown mode {opts.mode!r}")
|
||||
if opts.mode == "replace" and opts.collection != "repoint":
|
||||
raise ConvertError("Replace mode replaces the entry; adding a second one needs a destination folder")
|
||||
if opts.mode == "destination" and not opts.destination:
|
||||
raise ConvertError("Choose a destination folder")
|
||||
|
||||
in_library = {str(p) for t in adapter.tracks if (p := adapter.audio_path(t.id)) is not None}
|
||||
candidates: list[tuple[str, object, Path]] = []
|
||||
for tid in dict.fromkeys(track_ids):
|
||||
track = adapter.track(tid)
|
||||
src = adapter.audio_path(tid) if track is not None else None
|
||||
if track is None:
|
||||
result.skipped.append({"track_id": tid, "title": tid, "reason": "not in the library"})
|
||||
elif src is None or not Path(src).is_file():
|
||||
result.skipped.append({"track_id": tid, "title": _title(track), "reason": "the file is missing"})
|
||||
elif sf.is_stem_file(src):
|
||||
result.skipped.append({"track_id": tid, "title": _title(track), "reason": "already a stem file"})
|
||||
else:
|
||||
candidates.append((tid, track, Path(src)))
|
||||
|
||||
folders = ({s: s.parent for _, _, s in candidates} if opts.mode == "replace"
|
||||
else _mirror([s for _, _, s in candidates], Path(opts.destination)))
|
||||
claimed: set[str] = set()
|
||||
need: dict[str, dict] = {}
|
||||
for tid, track, src in candidates:
|
||||
target = folders[src] / sf.stem_target_name(src.name)
|
||||
key = str(target).casefold() # APFS and NTFS are case-insensitive by default
|
||||
reuse = pending.find_leftover(src) if pending is not None else None
|
||||
if reuse is not None and Path(reuse["partial"]) != partial_name(target):
|
||||
reuse = None
|
||||
if key in claimed:
|
||||
reason = "another selected track converts to the same file"
|
||||
elif target.exists():
|
||||
reason = f"a stem file already exists: {target.name}"
|
||||
elif str(target) in in_library:
|
||||
reason = f"the collection already has {target.name}"
|
||||
else:
|
||||
reason = None
|
||||
if reason:
|
||||
result.skipped.append({"track_id": tid, "title": _title(track), "reason": reason})
|
||||
continue
|
||||
claimed.add(key)
|
||||
seconds = float(getattr(track, "length", 0) or 0) or src.stat().st_size / (320_000 / 8)
|
||||
result.items.append(Planned(tid, _title(track), src, target, seconds, reuse))
|
||||
vol = _volume_key(target)
|
||||
entry = need.setdefault(vol, {"folder": str(target.parent), "bytes": 0})
|
||||
entry["bytes"] += int(seconds * _BYTES_PER_SECOND[_output_rate(track, src)]) if reuse is None else 0
|
||||
|
||||
# Both copies coexist until Save, so every target volume needs the stem files'
|
||||
# room on top of what is there; the work folder needs the largest track's.
|
||||
for vol, entry in need.items():
|
||||
free = free_bytes(Path(entry["folder"]))
|
||||
entry.update(volume=vol, free=free)
|
||||
result.space.append(entry)
|
||||
if free is not None and entry["bytes"] + SPACE_HEADROOM > free:
|
||||
result.blocked = (f"Not enough space on {vol}: the stem files need about "
|
||||
f"{entry['bytes'] / 1e9:.1f} GB and {free / 1e9:.1f} GB is free")
|
||||
if result.items and result.blocked is None:
|
||||
work = work_root()
|
||||
biggest = max(p.seconds for p in result.items) * _WORK_BYTES_PER_SECOND
|
||||
free = free_bytes(work)
|
||||
if free is not None and biggest + SPACE_HEADROOM > free:
|
||||
result.blocked = (f"Not enough space for working files: about {biggest / 1e9:.1f} GB is "
|
||||
f"needed while a track converts, {free / 1e9:.1f} GB is free")
|
||||
return result
|
||||
|
||||
|
||||
def _volume_key(path: Path) -> str:
|
||||
p = path
|
||||
while not p.exists() and p != p.parent:
|
||||
p = p.parent
|
||||
if sys.platform == "win32":
|
||||
return (p.drive or str(p))
|
||||
parts = p.parts
|
||||
return f"/{parts[1]}/{parts[2]}" if len(parts) > 2 and parts[1] == "Volumes" else "this computer"
|
||||
|
||||
|
||||
def work_root() -> Path:
|
||||
root = paths.app_data_dir() / "stems" / "work"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
|
||||
mutation, still_current: Callable[[], bool], manager: em.EngineManager | None = None) -> dict:
|
||||
"""The job. Returns the result dict; the job's state says cancelled/done."""
|
||||
mgr = manager or em.default_manager()
|
||||
result = {"converted": [], "renamed": {}, "added": {}, "skipped": list(planned.skipped),
|
||||
"failed": [], "clamped": {}, "cancelled": False}
|
||||
items = planned.items
|
||||
handle.progress(done=0, total=len(items), unit="tracks", message="Starting the stem engine…")
|
||||
work = work_root() / f"batch-{id(handle):x}"
|
||||
finished: list[tuple[Planned, dict, sf.Written]] = []
|
||||
needs_engine = any(p.reuse is None for p in items)
|
||||
if needs_engine and not mgr.ready():
|
||||
raise ConvertError("The stem engine is not installed")
|
||||
|
||||
def checkpoint() -> None:
|
||||
if handle.cancelled:
|
||||
raise _Cancel()
|
||||
|
||||
with contextlib.ExitStack() as stack:
|
||||
engine: EngineProcess | None = None
|
||||
try:
|
||||
for i, item in enumerate(items):
|
||||
checkpoint()
|
||||
handle.progress(done=i, message=item.title, fraction=0.0, status="")
|
||||
partial = partial_name(item.target)
|
||||
if item.reuse is not None:
|
||||
written = sf.Written(path=partial, **{k: item.reuse["written"][k] for k in ("bit_rate", "duration", "size")},
|
||||
tags={})
|
||||
pitem = pending.add({"track_id": item.track_id, "mode": opts.collection, "source": str(item.source),
|
||||
"stem": str(item.target), "state": "converted", "facts": source_facts(item.source),
|
||||
"written": item.reuse["written"]})
|
||||
pending.forget_leftover(item.reuse, delete=False)
|
||||
finished.append((item, pitem, written))
|
||||
continue
|
||||
if engine is None:
|
||||
handle.progress(status="starting…")
|
||||
engine = stack.enter_context(EngineProcess(mgr.executable(), mgr.weights_dir(), device=opts.device))
|
||||
stack.enter_context(keep_awake(engine.proc.pid))
|
||||
pitem = pending.add({"track_id": item.track_id, "mode": opts.collection, "source": str(item.source),
|
||||
"stem": str(item.target), "state": "converting", "facts": source_facts(item.source)})
|
||||
item.target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Of a TRACK's time, separation is nearly all (~90 % on MPS);
|
||||
# decoding before it and encoding + verifying after share the rest.
|
||||
def on_progress(f: float) -> None:
|
||||
frac = _DECODE_SHARE + f * (_SEPARATE_SHARE)
|
||||
handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
|
||||
|
||||
def separate(pcm):
|
||||
handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %")
|
||||
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
|
||||
done_at = _DECODE_SHARE + _SEPARATE_SHARE
|
||||
handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %")
|
||||
return stems
|
||||
|
||||
handle.progress(status="decoding 0 %")
|
||||
try:
|
||||
written = sf.build(item.source, partial, separate, checkpoint=checkpoint)
|
||||
except (_Cancel, EngineCancelled):
|
||||
partial.unlink(missing_ok=True)
|
||||
pending.drop([pitem])
|
||||
raise
|
||||
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
|
||||
partial.unlink(missing_ok=True)
|
||||
pending.drop([pitem])
|
||||
result["failed"].append({"track_id": item.track_id, "title": item.title, "reason": str(ex) or type(ex).__name__})
|
||||
if isinstance(ex, em.EngineError) and engine.proc.poll() is not None:
|
||||
engine = None # it died: the next track starts a fresh one
|
||||
continue
|
||||
pending.update(pitem, state="converted",
|
||||
written={"bit_rate": written.bit_rate, "duration": written.duration, "size": written.size})
|
||||
finished.append((item, pitem, written))
|
||||
except (_Cancel, EngineCancelled):
|
||||
# Cancel = delete what this run made; nothing else was touched.
|
||||
for _item, pitem, written in finished:
|
||||
if pitem.get("state") == "converted":
|
||||
Path(written.path).unlink(missing_ok=True)
|
||||
pending.drop([p for _, p, _ in finished])
|
||||
result["cancelled"] = True
|
||||
return result
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
handle.progress(done=len(items), message="Swapping the converted tracks into the collection…", status="")
|
||||
with mutation:
|
||||
if not still_current():
|
||||
for _item, pitem, written in finished:
|
||||
Path(written.path).unlink(missing_ok=True)
|
||||
pending.drop([p for _, p, _ in finished])
|
||||
raise ConvertError("The library changed while converting; nothing was swapped in")
|
||||
_end_step(adapter, finished, opts, pending, result)
|
||||
return result
|
||||
|
||||
|
||||
def _end_step(adapter, finished, opts: Options, pending: Pending, result: dict) -> None:
|
||||
swaps: list[StemSwap] = []
|
||||
staged: list[tuple[Planned, dict]] = []
|
||||
for item, pitem, written in finished:
|
||||
partial = Path(written.path)
|
||||
try:
|
||||
_replace_no_overwrite(partial, item.target)
|
||||
except FileExistsError:
|
||||
partial.unlink(missing_ok=True)
|
||||
pending.drop([pitem])
|
||||
result["failed"].append({"track_id": item.track_id, "title": item.title,
|
||||
"reason": f"a file appeared at {item.target.name} while converting"})
|
||||
continue
|
||||
pending.update(pitem, state="published")
|
||||
original_now = item.source
|
||||
if opts.mode == "replace":
|
||||
parked = parked_name(item.source)
|
||||
try:
|
||||
_retrying(lambda: _replace_no_overwrite(item.source, parked))
|
||||
except OSError as ex:
|
||||
item.target.unlink(missing_ok=True)
|
||||
pending.drop([pitem])
|
||||
result["failed"].append({"track_id": item.track_id, "title": item.title,
|
||||
"reason": f"the original could not be moved aside (in use?): {ex}"})
|
||||
continue
|
||||
_hide(parked)
|
||||
pending.update(pitem, state="parked", parked=str(parked))
|
||||
original_now = parked
|
||||
swaps.append(StemSwap(item.track_id, item.target, opts.collection, original_now,
|
||||
written.bit_rate, written.duration, written.size))
|
||||
staged.append((item, pitem))
|
||||
if not swaps:
|
||||
return
|
||||
playlist = opts.playlist_id
|
||||
try:
|
||||
if opts.collection == "add" and opts.new_playlist:
|
||||
playlist = adapter.create_playlist(opts.new_playlist)
|
||||
elif playlist is not None and adapter.playlist_entries(playlist) is None:
|
||||
result["playlist_missing"] = True # deleted while converting: the tracks are still added
|
||||
playlist = None
|
||||
res = adapter.apply_stem_swaps(swaps, add_to_playlist=playlist if opts.collection == "add" else None)
|
||||
except AdapterError as ex:
|
||||
# Nothing was swapped (the command validates everything first): undo the files.
|
||||
for item, pitem in staged:
|
||||
pending._undo(pitem, keep_leftover=False)
|
||||
pending.drop([pitem])
|
||||
result["failed"].append({"track_id": item.track_id, "title": item.title, "reason": str(ex)})
|
||||
return
|
||||
for item, pitem in staged:
|
||||
new_id = res.renamed[item.track_id]
|
||||
pending.update(pitem, state="swapped", new_id=new_id)
|
||||
result["converted"].append({"track_id": item.track_id, "new_id": new_id, "title": item.title})
|
||||
(result["renamed"] if opts.collection == "repoint" else result["added"])[item.track_id] = new_id
|
||||
result["clamped"] = res.clamped
|
||||
|
||||
|
||||
def _hide(path: Path) -> None:
|
||||
"""Windows ignores dot-names; set the hidden attribute so a parked original
|
||||
does not show in Explorer (or a naive folder scan)."""
|
||||
if sys.platform != "win32":
|
||||
return
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
ctypes.windll.kernel32.SetFileAttributesW(str(path), 0x02)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
@@ -0,0 +1,99 @@
|
||||
"""A resumable, verified download — the engine's parts and the weights.
|
||||
|
||||
Big files over home connections get interrupted, so a download resumes from
|
||||
its `.part` file with an HTTP `Range` request (and starts over if the server
|
||||
ignores it), and a file only takes its final name once its SHA-256 matches.
|
||||
GitHub release assets and Hugging Face files both redirect to a CDN; urllib
|
||||
carries the `Range` header across the redirect.
|
||||
|
||||
TLS uses certifi's bundle: a frozen Python on macOS has no system CA store of
|
||||
its own, so the default context would reject every HTTPS certificate.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import ssl
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
CHUNK = 1 << 20
|
||||
_UA = "Konduktor (stem engine download)"
|
||||
|
||||
|
||||
class DownloadError(Exception):
|
||||
"""User-facing."""
|
||||
|
||||
|
||||
class DownloadCancelled(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def ssl_context() -> ssl.SSLContext:
|
||||
try:
|
||||
import certifi
|
||||
|
||||
return ssl.create_default_context(cafile=certifi.where())
|
||||
except Exception: # noqa: BLE001 — fall back to the platform's own store
|
||||
return ssl.create_default_context()
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(CHUNK), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def fetch(url: str, dest: Path, *, sha256: str, size: int | None = None,
|
||||
on_bytes: Callable[[int], None] = lambda n: None,
|
||||
cancelled: Callable[[], bool] = lambda: False,
|
||||
context: ssl.SSLContext | None = None, timeout: float = 60) -> None:
|
||||
"""Download `url` to `dest`, resuming a previous `.part`, verified.
|
||||
|
||||
`on_bytes` is told about every chunk INCLUDING what an earlier attempt
|
||||
already fetched (once, up front), so a progress bar resumes where it was.
|
||||
"""
|
||||
dest = Path(dest)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
if dest.exists() and (size is None or dest.stat().st_size == size) and sha256_file(dest) == sha256:
|
||||
on_bytes(dest.stat().st_size)
|
||||
return
|
||||
partial = dest.with_name(dest.name + ".part")
|
||||
have = partial.stat().st_size if partial.exists() else 0
|
||||
if size is not None and have > size:
|
||||
partial.unlink()
|
||||
have = 0
|
||||
if have:
|
||||
on_bytes(have)
|
||||
if size is None or have < size:
|
||||
headers = {"User-Agent": _UA}
|
||||
if have:
|
||||
headers["Range"] = f"bytes={have}-"
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout, context=context) as r:
|
||||
if have and r.status != 206:
|
||||
# The server ignored the range: start over, and un-count it.
|
||||
on_bytes(-have)
|
||||
have = 0
|
||||
with open(partial, "ab" if have else "wb") as f:
|
||||
while True:
|
||||
if cancelled():
|
||||
raise DownloadCancelled()
|
||||
chunk = r.read(CHUNK)
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
on_bytes(len(chunk))
|
||||
except DownloadCancelled:
|
||||
raise
|
||||
except OSError as ex: # URLError, timeouts, connection resets
|
||||
raise DownloadError(f"Could not download {dest.name}: {ex}") from ex
|
||||
got = sha256_file(partial)
|
||||
if got != sha256:
|
||||
partial.unlink(missing_ok=True)
|
||||
raise DownloadError(f"{dest.name} did not arrive intact (checksum mismatch); try again")
|
||||
os.replace(partial, dest)
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"comment": "The stem engine THIS app build needs. Engines are released on their own channel (engine-v<version>, .github/workflows/engine.yml); the manifest lists each target's archive parts and hashes. `cuda` is the CUDA engine's floor, used to decide whether to OFFER it; the engine's own `info` confirms the card once installed.",
|
||||
"version": "1.0.0",
|
||||
"manifest_url": "https://github.com/MrPatben8/konduktor/releases/download/engine-v{version}/engine-manifest.json",
|
||||
"asset_url": "https://github.com/MrPatben8/konduktor/releases/download/engine-v{version}/{name}",
|
||||
"cuda": {"min_driver": 580, "min_capability": 7.5}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
"""The stem engine and its weights on THIS machine: what is installed, getting
|
||||
it, getting rid of it.
|
||||
|
||||
The engine is a separate frozen program, released on its own channel
|
||||
(`engine-v<version>`; see `engine/` and `.github/workflows/engine.yml`) and
|
||||
named by `engine.json` — the version this app build needs. The weights are
|
||||
pinned by revision and SHA-256 in `weights.json` (a copy of
|
||||
`engine/weights.json`; a test keeps them equal) and fetched from Hugging Face,
|
||||
never re-hosted.
|
||||
|
||||
Layout under `root` — app-data on macOS; on Windows a SHORT root,
|
||||
`%LOCALAPPDATA%\\Konduktor\\engine`, because torch's tree is deep and Windows
|
||||
paths stop at 260 characters:
|
||||
|
||||
<root>/<version>/<target>/konduktor-engine/konduktor-engine[.exe]
|
||||
<root>/installed.json what is installed, written LAST
|
||||
<root>/weights/<revision>/... the four .safetensors + htdemucs_ft.yaml
|
||||
<root>/downloads/ resumable .part files
|
||||
|
||||
An install is verified three times before it counts: each part's SHA-256, the
|
||||
whole archive's, and — once unpacked into a temporary folder — the engine
|
||||
actually starting and reporting the expected version. Only then is it moved
|
||||
into place and `installed.json` written, so a half-finished or corrupt install
|
||||
can never look like a working one. One engine is installed at a time (on
|
||||
Windows the CUDA engine also runs on the CPU, so it replaces the CPU one).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from .. import paths
|
||||
from . import download
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
CONFIG = json.loads((_HERE / "engine.json").read_text())
|
||||
WEIGHTS = json.loads((_HERE / "weights.json").read_text())
|
||||
|
||||
TARGETS = ("macos-arm64", "windows-x64-cpu", "windows-x64-cuda")
|
||||
|
||||
|
||||
class EngineError(Exception):
|
||||
"""User-facing."""
|
||||
|
||||
|
||||
def default_root() -> Path:
|
||||
override = os.environ.get("KONDUKTOR_DATA_DIR")
|
||||
if override:
|
||||
return Path(override) / "engine"
|
||||
if sys.platform == "win32" and os.environ.get("LOCALAPPDATA"):
|
||||
return Path(os.environ["LOCALAPPDATA"]) / "Konduktor" / "engine"
|
||||
return paths.app_data_dir() / "engine"
|
||||
|
||||
|
||||
def base_target() -> str | None:
|
||||
"""The engine this computer can run at all; None = no engine for it
|
||||
(Intel Macs, Linux)."""
|
||||
machine = platform.machine().lower()
|
||||
if sys.platform == "darwin" and machine in ("arm64", "aarch64"):
|
||||
return "macos-arm64"
|
||||
if sys.platform == "win32" and machine in ("amd64", "x86_64"):
|
||||
return "windows-x64-cpu"
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NvidiaGpu:
|
||||
name: str
|
||||
driver: str
|
||||
capability: float
|
||||
|
||||
|
||||
def detect_nvidia() -> list[NvidiaGpu]:
|
||||
"""NVIDIA cards per `nvidia-smi` (installed with the driver). Empty when
|
||||
there is none, or no driver — the case for every Mac."""
|
||||
if sys.platform != "win32":
|
||||
return []
|
||||
try:
|
||||
out = subprocess.run(
|
||||
["nvidia-smi", "--query-gpu=name,driver_version,compute_cap", "--format=csv,noheader"],
|
||||
capture_output=True, text=True, timeout=10,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||
).stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return []
|
||||
gpus = []
|
||||
for line in out.splitlines():
|
||||
parts = [p.strip() for p in line.split(",")]
|
||||
if len(parts) == 3:
|
||||
try:
|
||||
gpus.append(NvidiaGpu(parts[0], parts[1], float(parts[2])))
|
||||
except ValueError:
|
||||
continue
|
||||
return gpus
|
||||
|
||||
|
||||
def cuda_suitable(gpus: list[NvidiaGpu], config: dict = CONFIG) -> NvidiaGpu | None:
|
||||
"""The first card the CUDA engine can use: a new enough driver and compute
|
||||
capability. Offering it to anyone else would be offering gigabytes for an
|
||||
engine that falls back to the CPU."""
|
||||
floor = config.get("cuda", {})
|
||||
for g in gpus:
|
||||
try:
|
||||
major = int(g.driver.split(".")[0])
|
||||
except ValueError:
|
||||
continue
|
||||
if major >= floor.get("min_driver", 0) and g.capability >= floor.get("min_capability", 0):
|
||||
return g
|
||||
return None
|
||||
|
||||
|
||||
class EngineManager:
|
||||
def __init__(self, root: Path | None = None, config: dict | None = None,
|
||||
weights: dict | None = None, target: str | None = "auto") -> None:
|
||||
self.root = Path(root) if root else default_root()
|
||||
self.config = config or CONFIG
|
||||
self.weights = weights or WEIGHTS
|
||||
self._base_target = base_target() if target == "auto" else target
|
||||
self._manifest: dict | None = None
|
||||
|
||||
# ---- where things are --------------------------------------------------
|
||||
@property
|
||||
def version(self) -> str:
|
||||
return self.config["version"]
|
||||
|
||||
@property
|
||||
def base_target(self) -> str | None:
|
||||
return self._base_target
|
||||
|
||||
def _installed_record(self) -> dict | None:
|
||||
return paths.read_json(self.root / "installed.json", None)
|
||||
|
||||
def installed(self) -> dict | None:
|
||||
"""The installed engine, if it is this app's version and still there."""
|
||||
rec = self._installed_record()
|
||||
if not rec or rec.get("version") != self.version:
|
||||
return None
|
||||
exe = Path(rec.get("executable", ""))
|
||||
return rec if exe.is_file() else None
|
||||
|
||||
def executable(self) -> Path | None:
|
||||
rec = self.installed()
|
||||
return Path(rec["executable"]) if rec else None
|
||||
|
||||
def weights_dir(self) -> Path:
|
||||
return self.root / "weights" / self.weights["revision"]
|
||||
|
||||
def weights_installed(self) -> bool:
|
||||
"""Present at the right sizes. (Hashes were checked when they arrived;
|
||||
re-hashing 337 MB on every status call is not worth it.)"""
|
||||
d = self.weights_dir()
|
||||
return all((d / f["name"]).is_file() and (d / f["name"]).stat().st_size == f["size"]
|
||||
for f in self.weights["files"])
|
||||
|
||||
def weights_size(self) -> int:
|
||||
return sum(f["size"] for f in self.weights["files"])
|
||||
|
||||
# ---- manifest ------------------------------------------------------------
|
||||
def manifest(self, *, fetch: bool = True) -> dict | None:
|
||||
"""The release's manifest (each target's parts and hashes). Cached on
|
||||
disk: once fetched, an install or side-load needs no network for it."""
|
||||
if self._manifest is not None:
|
||||
return self._manifest
|
||||
cached = self.root / f"manifest-{self.version}.json"
|
||||
data = paths.read_json(cached, None)
|
||||
if data is None and fetch:
|
||||
url = self.config["manifest_url"].format(version=self.version)
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Konduktor"})
|
||||
with urllib.request.urlopen(req, timeout=20, context=download.ssl_context()) as r:
|
||||
data = json.loads(r.read())
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if data.get("version") != self.version:
|
||||
return None
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
paths.write_json(cached, data)
|
||||
self._manifest = data
|
||||
return data
|
||||
|
||||
def target_info(self, target: str) -> dict | None:
|
||||
m = self.manifest()
|
||||
return (m or {}).get("targets", {}).get(target)
|
||||
|
||||
# ---- status ----------------------------------------------------------------
|
||||
def status(self, *, network: bool = True) -> dict:
|
||||
installed = self.installed()
|
||||
gpus = detect_nvidia()
|
||||
cuda = cuda_suitable(gpus, self.config)
|
||||
offered = [self.base_target] if self.base_target else []
|
||||
if self.base_target == "windows-x64-cpu" and cuda is not None:
|
||||
offered.append("windows-x64-cuda")
|
||||
manifest = self.manifest(fetch=network) if offered else None
|
||||
sizes = {t: (manifest or {}).get("targets", {}).get(t, {}).get("size") for t in offered}
|
||||
return {
|
||||
"supported": self.base_target is not None,
|
||||
"required_version": self.version,
|
||||
"installed": ({k: installed[k] for k in ("version", "target", "size")} if installed else None),
|
||||
"offered_targets": offered,
|
||||
"download_sizes": sizes,
|
||||
"manifest_available": manifest is not None,
|
||||
"nvidia": ({"name": cuda.name, "driver": cuda.driver, "capability": cuda.capability} if cuda else None),
|
||||
"weights": {"installed": self.weights_installed(), "size": self.weights_size(),
|
||||
"revision": self.weights["revision"]},
|
||||
"root": str(self.root),
|
||||
}
|
||||
|
||||
def ready(self) -> bool:
|
||||
return self.executable() is not None and self.weights_installed()
|
||||
|
||||
# ---- installing the engine ---------------------------------------------------
|
||||
def install_engine(self, target: str | None = None, *,
|
||||
on_bytes: Callable[[int], None] = lambda n: None,
|
||||
cancelled: Callable[[], bool] = lambda: False) -> dict:
|
||||
target = target or self.base_target
|
||||
if target is None or target not in TARGETS:
|
||||
raise EngineError("There is no stem engine for this computer")
|
||||
info = self.target_info(target)
|
||||
if info is None:
|
||||
raise EngineError("Could not reach the engine download — check the internet connection")
|
||||
downloads = self.root / "downloads"
|
||||
ctx = download.ssl_context()
|
||||
for part in info["parts"]:
|
||||
url = self.config["asset_url"].format(version=self.version, name=part["name"])
|
||||
download.fetch(url, downloads / part["name"], sha256=part["sha256"], size=part["size"],
|
||||
on_bytes=on_bytes, cancelled=cancelled, context=ctx)
|
||||
archive = self._join_parts(info, downloads)
|
||||
rec = self._install_archive(archive, target, info)
|
||||
for part in info["parts"]:
|
||||
(downloads / part["name"]).unlink(missing_ok=True)
|
||||
archive.unlink(missing_ok=True)
|
||||
return rec
|
||||
|
||||
def _join_parts(self, info: dict, folder: Path) -> Path:
|
||||
parts = [folder / p["name"] for p in info["parts"]]
|
||||
if len(parts) == 1:
|
||||
archive = parts[0]
|
||||
else:
|
||||
archive = folder / info["archive"]
|
||||
with open(archive, "wb") as out:
|
||||
for p in parts:
|
||||
with open(p, "rb") as f:
|
||||
shutil.copyfileobj(f, out, 1 << 20)
|
||||
if download.sha256_file(archive) != info["sha256"]:
|
||||
raise EngineError("The engine download is damaged (checksum mismatch); try again")
|
||||
return archive
|
||||
|
||||
def _install_archive(self, archive: Path, target: str, info: dict) -> dict:
|
||||
"""Unpack, prove the engine starts, THEN move it into place."""
|
||||
final = self.root / self.version / target
|
||||
staging = self.root / self.version / f".{target}.installing"
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
staging.mkdir(parents=True)
|
||||
try:
|
||||
with tarfile.open(archive, "r:gz") as tar:
|
||||
tar.extractall(staging, filter="tar")
|
||||
exe = staging / "konduktor-engine" / ("konduktor-engine.exe" if sys.platform == "win32" else "konduktor-engine")
|
||||
if not exe.is_file():
|
||||
raise EngineError("The engine archive does not contain the engine")
|
||||
reported = probe(exe)
|
||||
if reported.get("version") != self.version:
|
||||
raise EngineError(f"The engine reports version {reported.get('version')!r}, "
|
||||
f"this app needs {self.version}")
|
||||
shutil.rmtree(final, ignore_errors=True)
|
||||
os.replace(staging, final)
|
||||
except BaseException:
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
raise
|
||||
rec = {"version": self.version, "target": target, "size": info.get("unpacked_size"),
|
||||
"executable": str(final / "konduktor-engine" / exe.name), "info": reported}
|
||||
paths.write_json(self.root / "installed.json", rec)
|
||||
self._remove_others(keep=final)
|
||||
return rec
|
||||
|
||||
def _remove_others(self, keep: Path) -> None:
|
||||
"""One engine at a time: other targets and older versions go."""
|
||||
for version_dir in self.root.iterdir():
|
||||
if not version_dir.is_dir() or version_dir.name in ("weights", "downloads"):
|
||||
continue
|
||||
for target_dir in version_dir.iterdir():
|
||||
if target_dir != keep and target_dir.is_dir():
|
||||
shutil.rmtree(target_dir, ignore_errors=True)
|
||||
if not any(version_dir.iterdir()):
|
||||
version_dir.rmdir()
|
||||
|
||||
# ---- installing the weights ------------------------------------------------------
|
||||
def install_weights(self, *, on_bytes: Callable[[int], None] = lambda n: None,
|
||||
cancelled: Callable[[], bool] = lambda: False) -> None:
|
||||
folder = self.weights_dir()
|
||||
ctx = download.ssl_context()
|
||||
for f in self.weights["files"]:
|
||||
url = self.weights["url"].format(repo=self.weights["repo"], revision=self.weights["revision"],
|
||||
name=f["name"])
|
||||
download.fetch(url, folder / f["name"], sha256=f["sha256"], size=f["size"],
|
||||
on_bytes=on_bytes, cancelled=cancelled, context=ctx)
|
||||
|
||||
# ---- side-loading (offline machines) ------------------------------------------
|
||||
def side_load_engine(self, path: Path | str, target: str | None = None) -> dict:
|
||||
"""Install from an engine archive the user already has — the `.tar.gz`,
|
||||
or a folder holding all of its parts. Its hash must match the release
|
||||
manifest (fetched now, or cached from an earlier look)."""
|
||||
target = target or self.base_target
|
||||
info = self.target_info(target) if target else None
|
||||
if info is None:
|
||||
raise EngineError("The engine's checksums are not known yet — connect once, or open the "
|
||||
"Stems panel while online, so the file can be verified")
|
||||
src = Path(path)
|
||||
if src.is_dir():
|
||||
archive = self._join_parts(info, src)
|
||||
else:
|
||||
if download.sha256_file(src) != info["sha256"]:
|
||||
raise EngineError("That file is not the engine this app needs (checksum mismatch)")
|
||||
archive = src
|
||||
return self._install_archive(archive, target, info)
|
||||
|
||||
def side_load_weights(self, folder: Path | str) -> None:
|
||||
"""Copy the weights from a folder the user supplies, each file verified."""
|
||||
src = Path(folder)
|
||||
dest = self.weights_dir()
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
for f in self.weights["files"]:
|
||||
p = src / f["name"]
|
||||
if not p.is_file() or download.sha256_file(p) != f["sha256"]:
|
||||
raise EngineError(f"{f['name']} is missing from that folder or is not the right file")
|
||||
for f in self.weights["files"]:
|
||||
shutil.copy2(src / f["name"], dest / f["name"])
|
||||
|
||||
# ---- removal -------------------------------------------------------------------
|
||||
def remove(self) -> None:
|
||||
"""The engine, its weights and any unfinished downloads."""
|
||||
(self.root / "installed.json").unlink(missing_ok=True)
|
||||
if self.root.exists():
|
||||
for child in self.root.iterdir():
|
||||
if child.is_dir():
|
||||
shutil.rmtree(child, ignore_errors=True)
|
||||
elif child.name != "installed.json":
|
||||
child.unlink(missing_ok=True)
|
||||
|
||||
|
||||
_DEFAULT: "EngineManager | None" = None
|
||||
|
||||
|
||||
def default_manager() -> EngineManager:
|
||||
"""The app's one manager (the routes and the batch share it)."""
|
||||
global _DEFAULT
|
||||
if _DEFAULT is None:
|
||||
_DEFAULT = EngineManager()
|
||||
return _DEFAULT
|
||||
|
||||
|
||||
def probe(executable: Path, timeout: float = 120) -> dict:
|
||||
"""Run `engine info` — proves the unpacked engine actually starts."""
|
||||
try:
|
||||
out = subprocess.run([str(executable), "info"], capture_output=True, text=True, timeout=timeout,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
except (OSError, subprocess.SubprocessError) as ex:
|
||||
raise EngineError(f"The engine would not start: {ex}") from ex
|
||||
for line in out.stdout.splitlines():
|
||||
try:
|
||||
msg = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if msg.get("event") == "info":
|
||||
return msg
|
||||
raise EngineError("The engine started but did not identify itself")
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Driving the stem engine: one `serve` process per batch.
|
||||
|
||||
The engine's protocol is documented in `engine/konduktor_engine/serve.py`.
|
||||
Audio crosses as raw planar float32 files in a work folder.
|
||||
|
||||
Lifetime is the part that must not go wrong — a batch can run for hours:
|
||||
* The engine ends itself when its stdin closes, so if this backend dies the
|
||||
engine follows. On Windows it is ALSO put in a Job Object that kills it
|
||||
when the last handle closes, which covers a hard kill of the backend.
|
||||
* Cancel is a message (the model stays loaded); `close()` ends the process.
|
||||
* The machine is kept awake for the batch — macOS `caffeinate` tied to the
|
||||
engine's pid, Windows `SetThreadExecutionState` on the calling thread —
|
||||
or a laptop sleeping at 1 am stops a 4-hour conversion at track 30.
|
||||
* stderr is drained on a thread (a full pipe would block the engine) and its
|
||||
tail kept, so an engine crash can be reported with its reason.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import json
|
||||
import queue
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .engine_manager import EngineError
|
||||
|
||||
SOURCES = ("drums", "bass", "other", "vocals")
|
||||
|
||||
|
||||
class EngineCancelled(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _job_object_kill_on_close(pid_handle) -> object | None:
|
||||
"""Windows: a Job Object with KILL_ON_JOB_CLOSE holding the engine. The
|
||||
returned handle must stay referenced for as long as the engine may live."""
|
||||
if sys.platform != "win32":
|
||||
return None
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
k32 = ctypes.windll.kernel32
|
||||
|
||||
class IO_COUNTERS(ctypes.Structure):
|
||||
_fields_ = [(n, ctypes.c_ulonglong) for n in (
|
||||
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
|
||||
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
|
||||
|
||||
class BASIC(ctypes.Structure):
|
||||
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64),
|
||||
("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
|
||||
("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD),
|
||||
("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD),
|
||||
("SchedulingClass", wintypes.DWORD)]
|
||||
|
||||
class EXTENDED(ctypes.Structure):
|
||||
_fields_ = [("BasicLimitInformation", BASIC), ("IoInfo", IO_COUNTERS),
|
||||
("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
|
||||
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
|
||||
|
||||
job = k32.CreateJobObjectW(None, None)
|
||||
info = EXTENDED()
|
||||
info.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
k32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)) # ExtendedLimitInformation
|
||||
k32.AssignProcessToJobObject(job, int(pid_handle))
|
||||
return job
|
||||
except Exception: # noqa: BLE001 — the stdin watchdog still covers the common case
|
||||
return None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def keep_awake(pid: int | None = None):
|
||||
"""Stop the computer sleeping while a batch runs (not the display)."""
|
||||
proc = None
|
||||
if sys.platform == "darwin" and pid:
|
||||
try:
|
||||
proc = subprocess.Popen(["caffeinate", "-i", "-w", str(pid)],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
except OSError:
|
||||
proc = None
|
||||
elif sys.platform == "win32":
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
ES_CONTINUOUS, ES_SYSTEM_REQUIRED = 0x80000000, 0x00000001
|
||||
ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if proc is not None:
|
||||
proc.terminate()
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
class EngineProcess:
|
||||
"""One running `serve`. Not thread-safe: one batch drives it."""
|
||||
|
||||
def __init__(self, executable: Path | str, weights: Path | str, *, device: str = "auto",
|
||||
ready_timeout: float = 180) -> None:
|
||||
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||
self.proc = subprocess.Popen(
|
||||
[str(executable), "serve", "--weights", str(weights), "--device", device],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=True, bufsize=1, creationflags=flags,
|
||||
)
|
||||
self._job = _job_object_kill_on_close(getattr(self.proc, "_handle", 0))
|
||||
self._messages: "queue.Queue[dict | None]" = queue.Queue()
|
||||
self._stderr: collections.deque[str] = collections.deque(maxlen=40)
|
||||
threading.Thread(target=self._read_stdout, daemon=True, name="engine-stdout").start()
|
||||
threading.Thread(target=self._read_stderr, daemon=True, name="engine-stderr").start()
|
||||
self.device = device
|
||||
msg = self._next(ready_timeout)
|
||||
if msg is None or msg.get("event") != "ready":
|
||||
self.close()
|
||||
raise EngineError(f"The stem engine did not start: {self._reason(msg)}")
|
||||
self.device = msg.get("device", device)
|
||||
self._n = 0
|
||||
|
||||
# ---- plumbing ---------------------------------------------------------------
|
||||
def _read_stdout(self) -> None:
|
||||
for line in self.proc.stdout:
|
||||
try:
|
||||
self._messages.put(json.loads(line))
|
||||
except ValueError:
|
||||
self._stderr.append(line.rstrip())
|
||||
self._messages.put(None) # the engine closed its output: it has exited
|
||||
|
||||
def _read_stderr(self) -> None:
|
||||
for line in self.proc.stderr:
|
||||
self._stderr.append(line.rstrip())
|
||||
|
||||
def _next(self, timeout: float | None) -> dict | None:
|
||||
try:
|
||||
return self._messages.get(timeout=timeout)
|
||||
except queue.Empty:
|
||||
return {"event": "timeout"}
|
||||
|
||||
def _reason(self, msg: dict | None) -> str:
|
||||
if msg and msg.get("message"):
|
||||
return msg["message"]
|
||||
tail = [l for l in self._stderr if l.strip()][-3:]
|
||||
return " / ".join(tail) or "no reason given"
|
||||
|
||||
def _send(self, **msg) -> None:
|
||||
try:
|
||||
self.proc.stdin.write(json.dumps(msg) + "\n")
|
||||
self.proc.stdin.flush()
|
||||
except (BrokenPipeError, OSError, ValueError) as ex:
|
||||
raise EngineError(f"The stem engine has stopped: {self._reason(None)}") from ex
|
||||
|
||||
# ---- the one command ------------------------------------------------------------
|
||||
def separate(self, pcm: np.ndarray, work: Path | str, *, seed: int = 0,
|
||||
on_progress: Callable[[float], None] = lambda f: None,
|
||||
cancelled: Callable[[], bool] = lambda: False) -> list[np.ndarray]:
|
||||
"""Four stems in `SOURCES` order, each shaped like `pcm` (2, n)."""
|
||||
work = Path(work)
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
self._n += 1
|
||||
rid = f"t{self._n}"
|
||||
mix = work / f"{rid}.f32"
|
||||
np.ascontiguousarray(pcm, dtype=np.float32).tofile(mix)
|
||||
out = work / rid
|
||||
self._send(cmd="separate", id=rid, input=str(mix), samples=int(pcm.shape[1]),
|
||||
output_dir=str(out), seed=seed)
|
||||
asked_to_stop = False
|
||||
try:
|
||||
while True:
|
||||
if cancelled() and not asked_to_stop:
|
||||
self._send(cmd="cancel", id=rid)
|
||||
asked_to_stop = True
|
||||
msg = self._next(0.5)
|
||||
if msg is None:
|
||||
raise EngineError(f"The stem engine stopped: {self._reason(None)}")
|
||||
if msg.get("event") == "timeout" or msg.get("id") not in (rid, None):
|
||||
continue
|
||||
event = msg.get("event")
|
||||
if event == "progress":
|
||||
on_progress(float(msg.get("fraction", 0.0)))
|
||||
elif event == "done":
|
||||
stems = [np.fromfile(out / f"{name}.f32", dtype=np.float32).reshape(2, -1)
|
||||
for name in SOURCES]
|
||||
# ~100 MB of raw float per minute of audio: never leave it.
|
||||
shutil.rmtree(out, ignore_errors=True)
|
||||
return stems
|
||||
elif event == "cancelled":
|
||||
raise EngineCancelled()
|
||||
elif event == "error":
|
||||
raise EngineError(f"Separation failed: {self._reason(msg)}")
|
||||
finally:
|
||||
mix.unlink(missing_ok=True)
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
if self.proc.stdin:
|
||||
self.proc.stdin.close() # the engine ends itself on EOF
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
self.proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.proc.kill()
|
||||
self.proc.wait(timeout=5)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.close()
|
||||
|
||||
|
||||
def wait_until(predicate: Callable[[], bool], timeout: float) -> bool:
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
if predicate():
|
||||
return True
|
||||
time.sleep(0.02)
|
||||
return predicate()
|
||||
@@ -0,0 +1,237 @@
|
||||
"""Conversions that are done on disk but not yet committed by a Save.
|
||||
|
||||
A Convert to Stems batch leaves, per track: a stem file, and — in Replace mode —
|
||||
the original PARKED beside it (`.<name>.<ext>.konduktor-parked`, the same
|
||||
folder, so the rename is atomic and nothing looks like audio). The collection
|
||||
swap itself is an ordinary unsaved edit. So the files must follow what happens
|
||||
to the edits:
|
||||
|
||||
* **Save** commits them: parked originals are deleted (the user chose Replace,
|
||||
and was told Save deletes them), export sets follow the new ids.
|
||||
* **Discard** — or opening another library, after its confirm — undoes them:
|
||||
originals go back under their own names, the stem files are removed.
|
||||
* **A crash** leaves this ledger on disk. The next open of the library
|
||||
decides each item from the SAVED collection: if it names the stem file the
|
||||
swap was committed (finish deleting the original), otherwise it was not
|
||||
(put the original back). Verified stem files of an uncommitted item are
|
||||
kept — renamed to their `.konduktor-partial` name, so neither the user nor
|
||||
Traktor mistakes them for finished files — and a later batch converting the
|
||||
same source reuses one instead of spending minutes separating it again.
|
||||
|
||||
The ledger is Konduktor's own curated state, written atomically
|
||||
(`paths.write_json`), one file per library id. Every step is taken from what is
|
||||
actually ON DISK, never from the recorded state alone: a crash can fall between
|
||||
any two renames.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .. import paths
|
||||
|
||||
PARTIAL = ".konduktor-partial"
|
||||
PARKED = ".konduktor-parked"
|
||||
|
||||
|
||||
def parked_name(original: Path) -> Path:
|
||||
return original.with_name(f".{original.name}{PARKED}")
|
||||
|
||||
|
||||
def partial_name(stem: Path) -> Path:
|
||||
return stem.with_name(stem.name + PARTIAL)
|
||||
|
||||
|
||||
def source_facts(path: Path) -> dict | None:
|
||||
try:
|
||||
st = path.stat()
|
||||
except OSError:
|
||||
return None
|
||||
return {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
|
||||
|
||||
|
||||
def _replace_no_overwrite(src: Path, dst: Path) -> None:
|
||||
"""Rename refusing to overwrite: POSIX link+unlink (link fails if dst
|
||||
exists), Windows rename (which already refuses)."""
|
||||
if os.name == "nt":
|
||||
os.rename(src, dst)
|
||||
return
|
||||
os.link(src, dst)
|
||||
os.unlink(src)
|
||||
|
||||
|
||||
def _retrying(fn, *, attempts: int = 6, delay: float = 0.25):
|
||||
"""Windows cannot rename a file another process has open (Traktor, the
|
||||
deck's stream, an antivirus scan of a file just written): retry briefly."""
|
||||
for i in range(attempts):
|
||||
try:
|
||||
return fn()
|
||||
except PermissionError:
|
||||
if os.name != "nt" or i == attempts - 1:
|
||||
raise
|
||||
time.sleep(delay * (2 ** i))
|
||||
|
||||
|
||||
class Pending:
|
||||
"""The ledger for ONE library."""
|
||||
|
||||
def __init__(self, library_id: str | None) -> None:
|
||||
self.library_id = library_id
|
||||
self._lock = threading.RLock()
|
||||
self._path = (paths.app_data_dir() / "stems" / f"pending-{library_id}.json") if library_id else None
|
||||
data = paths.read_json(self._path, None) if self._path else None
|
||||
self.items: list[dict] = (data or {}).get("items", [])
|
||||
self.leftovers: list[dict] = (data or {}).get("leftovers", [])
|
||||
|
||||
# ---- persistence ----------------------------------------------------------
|
||||
def _write(self) -> None:
|
||||
if self._path is None:
|
||||
return
|
||||
if not self.items and not self.leftovers:
|
||||
self._path.unlink(missing_ok=True)
|
||||
return
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
paths.write_json(self._path, {"items": self.items, "leftovers": self.leftovers})
|
||||
|
||||
def add(self, item: dict) -> dict:
|
||||
with self._lock:
|
||||
self.items.append(item)
|
||||
self._write()
|
||||
return item
|
||||
|
||||
def update(self, item: dict, **fields) -> None:
|
||||
with self._lock:
|
||||
item.update(fields)
|
||||
self._write()
|
||||
|
||||
def drop(self, items: list[dict]) -> None:
|
||||
with self._lock:
|
||||
ids = {id(i) for i in items}
|
||||
self.items = [i for i in self.items if id(i) not in ids]
|
||||
self._write()
|
||||
|
||||
# ---- what the rest of the app asks ----------------------------------------------
|
||||
def swapped(self) -> list[dict]:
|
||||
return [i for i in self.items if i.get("state") == "swapped"]
|
||||
|
||||
def blocking(self) -> bool:
|
||||
"""Conversions awaiting Save or Discard — while there are any, import,
|
||||
remap, reload and history restore must refuse: each would save or drop
|
||||
the swap as a side effect."""
|
||||
return bool(self.swapped())
|
||||
|
||||
def summary(self) -> dict:
|
||||
parked = [Path(i["parked"]) for i in self.swapped() if i.get("parked")]
|
||||
return {"tracks": len(self.swapped()),
|
||||
"parked": len(parked),
|
||||
"bytes": sum(p.stat().st_size for p in parked if p.exists())}
|
||||
|
||||
# ---- leftovers (reuse after a crash) -----------------------------------------------
|
||||
def find_leftover(self, source: Path) -> dict | None:
|
||||
facts = source_facts(source)
|
||||
for lo in self.leftovers:
|
||||
if lo["source"] == str(source) and lo.get("facts") == facts and Path(lo["partial"]).is_file():
|
||||
return lo
|
||||
return None
|
||||
|
||||
def forget_leftover(self, leftover: dict, *, delete: bool) -> None:
|
||||
with self._lock:
|
||||
if delete:
|
||||
Path(leftover["partial"]).unlink(missing_ok=True)
|
||||
self.leftovers = [lo for lo in self.leftovers if lo is not leftover]
|
||||
self._write()
|
||||
|
||||
def _keep_as_leftover(self, item: dict) -> None:
|
||||
"""A verified stem file whose swap was not committed: keep it under its
|
||||
partial name for reuse (rather than hours of separation lost)."""
|
||||
stem = Path(item["stem"])
|
||||
partial = partial_name(stem)
|
||||
try:
|
||||
if _published(item) and stem.is_file() and not partial.exists():
|
||||
os.replace(stem, partial)
|
||||
except OSError:
|
||||
return
|
||||
if partial.is_file() and item.get("written"):
|
||||
self.leftovers.append({"source": item["source"], "facts": item.get("facts"),
|
||||
"partial": str(partial), "written": item["written"]})
|
||||
|
||||
# ---- Save / Discard / recovery ---------------------------------------------------
|
||||
def commit(self) -> dict[str, str]:
|
||||
"""After a successful Save: delete what the swap replaced. Returns the
|
||||
repoint renames so the caller retargets export sets."""
|
||||
renames: dict[str, str] = {}
|
||||
with self._lock:
|
||||
for item in self.swapped():
|
||||
if item.get("parked"):
|
||||
try:
|
||||
Path(item["parked"]).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass # a file still open on Windows: recovery tries again
|
||||
if item.get("mode") == "repoint" and item.get("new_id"):
|
||||
renames[item["track_id"]] = item["new_id"]
|
||||
item["state"] = "committed"
|
||||
self.items = [i for i in self.items if i.get("state") != "committed"
|
||||
or (i.get("parked") and Path(i["parked"]).exists())]
|
||||
self._write()
|
||||
return renames
|
||||
|
||||
def restore(self) -> int:
|
||||
"""Undo every uncommitted conversion: originals back, stem files gone.
|
||||
Returns how many originals were put back."""
|
||||
restored = 0
|
||||
with self._lock:
|
||||
for item in list(self.items):
|
||||
restored += self._undo(item, keep_leftover=False)
|
||||
self.items = []
|
||||
self._write()
|
||||
return restored
|
||||
|
||||
def recover(self, is_committed) -> dict:
|
||||
"""At open, after a crash: decide each leftover item from the SAVED
|
||||
collection (`is_committed(item)` — does it name the stem file?)."""
|
||||
report = {"committed": 0, "restored": 0, "kept": 0}
|
||||
with self._lock:
|
||||
before = len(self.leftovers)
|
||||
for item in list(self.items):
|
||||
if item.get("new_id") and is_committed(item):
|
||||
if item.get("parked"):
|
||||
Path(item["parked"]).unlink(missing_ok=True)
|
||||
report["committed"] += 1
|
||||
else:
|
||||
report["restored"] += self._undo(item, keep_leftover=True)
|
||||
report["kept"] = len(self.leftovers) - before
|
||||
self.items = []
|
||||
self._write()
|
||||
return report
|
||||
|
||||
def _undo(self, item: dict, *, keep_leftover: bool) -> int:
|
||||
"""Put one item's files back as they were. Filesystem-driven."""
|
||||
restored = 0
|
||||
original = Path(item["source"])
|
||||
parked = Path(item["parked"]) if item.get("parked") else None
|
||||
if parked is not None and parked.exists() and not original.exists():
|
||||
_retrying(lambda: _replace_no_overwrite(parked, original))
|
||||
restored = 1
|
||||
stem = Path(item["stem"])
|
||||
if keep_leftover and item.get("written"):
|
||||
self._keep_as_leftover(item)
|
||||
else:
|
||||
try:
|
||||
# Only a stem file THIS batch published is ours to delete: before
|
||||
# that, a file at the target name belongs to someone else.
|
||||
if _published(item):
|
||||
stem.unlink(missing_ok=True)
|
||||
partial_name(stem).unlink(missing_ok=True) # unverified: worthless
|
||||
except OSError:
|
||||
pass
|
||||
return restored
|
||||
|
||||
|
||||
def _published(item: dict) -> bool:
|
||||
return item.get("state") in ("published", "parked", "swapped", "committed")
|
||||
|
||||
|
||||
__all__ = ["PARKED", "PARTIAL", "Pending", "parked_name", "partial_name", "source_facts",
|
||||
"_replace_no_overwrite", "_retrying"]
|
||||
@@ -0,0 +1,75 @@
|
||||
"""The deck's stem audio: one stream of a stem file, as a file of its own.
|
||||
|
||||
A browser decodes only the FIRST audio stream of an MP4, so the deck cannot get
|
||||
at a stem file's stems from the file itself. Each is copied out (packets, not
|
||||
re-encoded — `stem_file.extract_stream`) into a small cache in app-data, keyed
|
||||
by the source's path, size and mtime, so an edited or replaced file is never
|
||||
served stale and loading the same track twice costs nothing the second time.
|
||||
|
||||
The cache is bounded (`LIMIT` bytes, least recently used first) — a stem is
|
||||
2-10 MB, so the limit holds a few hundred tracks' worth. Files are written as a
|
||||
partial then renamed, so two requests racing for the same stem, or a crash
|
||||
mid-write, can never serve a truncated file.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from .. import paths
|
||||
from ..core import stem_file
|
||||
|
||||
LIMIT = 2 * 1024 ** 3
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def root() -> Path:
|
||||
d = paths.app_data_dir() / "stems" / "playback"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def _key(path: Path, stream: int) -> str:
|
||||
st = path.stat()
|
||||
raw = f"{path.resolve()}\0{st.st_size}\0{st.st_mtime_ns}\0{stream}".encode()
|
||||
return hashlib.sha256(raw).hexdigest()[:32]
|
||||
|
||||
|
||||
def stem_file_for(path: Path, stem: int) -> Path:
|
||||
"""The cached single-stream file for stem `stem` (0-based: stream stem+1)."""
|
||||
path = Path(path)
|
||||
stream = stem + 1
|
||||
target = root() / f"{_key(path, stream)}.m4a"
|
||||
if target.exists():
|
||||
os.utime(target) # most recently used
|
||||
return target
|
||||
partial = target.with_name(f"{target.name}.{os.getpid()}.{threading.get_ident()}.part")
|
||||
try:
|
||||
with open(partial, "wb") as fp:
|
||||
stem_file.extract_stream(path, stream, fp)
|
||||
os.replace(partial, target)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
_prune(keep=target)
|
||||
return target
|
||||
|
||||
|
||||
def _prune(keep: Path) -> None:
|
||||
with _lock:
|
||||
files = []
|
||||
for p in root().glob("*.m4a"):
|
||||
try:
|
||||
st = p.stat()
|
||||
except OSError:
|
||||
continue
|
||||
files.append((st.st_mtime, st.st_size, p))
|
||||
total = sum(size for _, size, _ in files)
|
||||
for _, size, p in sorted(files):
|
||||
if total <= LIMIT:
|
||||
break
|
||||
if p == keep:
|
||||
continue
|
||||
p.unlink(missing_ok=True)
|
||||
total -= size
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"comment": "The htdemucs_ft weights, pinned. Fetched from the official Hugging Face repo on each machine and verified here; never re-hosted (their licence is ambiguous — see the stem-conversion discussion log). Konduktor's engine manager and CI both read this file.",
|
||||
"repo": "adefossez/HTDemucs-ft",
|
||||
"revision": "d74ac89c3a1e874fc78f152555cf4d8533f06cd4",
|
||||
"url": "https://huggingface.co/{repo}/resolve/{revision}/{name}",
|
||||
"files": [
|
||||
{"name": "htdemucs_ft.yaml", "size": 149, "sha256": "69470b8c1bbd674437b51bc9fb491327a10ab0396b702c93389b9cf750016346"},
|
||||
{"name": "f7e0c4bc.safetensors", "size": 84025440, "sha256": "2c85ab3c62dd6edd8e0b965e38b16fd1cdde357cc25de6b6bc9ce7c83f60925f"},
|
||||
{"name": "d12395a8.safetensors", "size": 84025440, "sha256": "5b01a97567ae9a3178a6236fb520251045c03eb8834bc8c24a4eec11d6c8fb56"},
|
||||
{"name": "92cfc3b6.safetensors", "size": 84025440, "sha256": "a241863551f30d01c42bd7b97da40839922ead3acb0f1fcab25682f55b4eeb59"},
|
||||
{"name": "04573f0d.safetensors", "size": 84025440, "sha256": "68854b0d7c2b3274723b5761f6fd9f5aec5f1bcd3f0de7c1669546fdb7871b7c"}
|
||||
]
|
||||
}
|
||||
@@ -4,6 +4,8 @@ fastapi>=0.115
|
||||
uvicorn[standard]>=0.34
|
||||
pydantic>=2.11
|
||||
mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF)
|
||||
av>=18.1 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS
|
||||
Pillow>=11 # cover art -> the 80/240 px JPEGs a Pioneer export carries
|
||||
python-multipart>=0.0.9 # multipart form parsing for cover-art upload
|
||||
# Version-history backups: a self-contained git impl (no system git needed;
|
||||
# ships prebuilt py3.14 wheels, no from-source build) + a per-OS user-writable
|
||||
@@ -29,3 +31,6 @@ traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
|
||||
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
|
||||
# running as-is — but that rename is the thing to fix before taking 0.6.
|
||||
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
|
||||
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a
|
||||
# frozen Python on macOS has no system CA bundle of its own.
|
||||
certifi>=2024.7
|
||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Test helpers for Convert to Stems: a FAKE engine and generated audio.
|
||||
|
||||
Not a test itself. The fake engine speaks the real `serve` protocol
|
||||
(`engine/konduktor_engine/serve.py`) — no torch — returning scaled copies of
|
||||
the mix as its "stems". Environment switches, read per separation:
|
||||
FAKE_DELAY seconds per progress step (10 steps) FAKE_ERROR reply "error"
|
||||
FAKE_CRASH die mid-request (stderr says why) FAKE_COUNT append a line
|
||||
per separation to this file
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import stat
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
|
||||
FAKE_ENGINE = r'''#!{python}
|
||||
import json, os, queue, sys, threading, time
|
||||
import numpy as np
|
||||
if sys.argv[1] == "info":
|
||||
print(json.dumps({{"event": "info", "version": "{version}", "devices": ["cpu"]}}))
|
||||
sys.exit(0)
|
||||
print(json.dumps({{"event": "ready", "device": "cpu"}}), flush=True)
|
||||
cancel, Q = set(), queue.Queue()
|
||||
def reader():
|
||||
for line in sys.stdin:
|
||||
m = json.loads(line)
|
||||
(cancel.add(m["id"]) if m.get("cmd") == "cancel" else Q.put(m))
|
||||
os._exit(0)
|
||||
threading.Thread(target=reader, daemon=True).start()
|
||||
while True:
|
||||
m = Q.get()
|
||||
rid = m["id"]
|
||||
x = np.fromfile(m["input"], dtype=np.float32).reshape(2, -1)
|
||||
if os.environ.get("FAKE_COUNT"):
|
||||
with open(os.environ["FAKE_COUNT"], "a") as f:
|
||||
f.write(rid + "\n")
|
||||
if os.environ.get("FAKE_CRASH"):
|
||||
print("boom: out of cheese", file=sys.stderr, flush=True); os._exit(3)
|
||||
if os.environ.get("FAKE_ERROR"):
|
||||
print(json.dumps({{"id": rid, "event": "error", "message": "bad input"}}), flush=True); continue
|
||||
stopped = False
|
||||
for i in range(10):
|
||||
time.sleep(float(os.environ.get("FAKE_DELAY", "0.005")))
|
||||
if rid in cancel:
|
||||
print(json.dumps({{"id": rid, "event": "cancelled"}}), flush=True); stopped = True; break
|
||||
print(json.dumps({{"id": rid, "event": "progress", "fraction": (i + 1) / 10}}), flush=True)
|
||||
if stopped:
|
||||
continue
|
||||
os.makedirs(m["output_dir"], exist_ok=True)
|
||||
for k, g in zip(("drums", "bass", "other", "vocals"), (0.5, 0.25, -0.2, 0.1)):
|
||||
(x * g).astype(np.float32).tofile(os.path.join(m["output_dir"], k + ".f32"))
|
||||
print(json.dumps({{"id": rid, "event": "done", "device": "cpu"}}), flush=True)
|
||||
'''
|
||||
|
||||
|
||||
def write_fake_engine(path: Path, version: str) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(FAKE_ENGINE.format(python=sys.executable, version=version))
|
||||
path.chmod(path.stat().st_mode | stat.S_IEXEC)
|
||||
return path
|
||||
|
||||
|
||||
def install_fake_engine(root: Path):
|
||||
"""An `EngineManager` whose engine is the fake one and whose weights are two
|
||||
tiny files — `ready()` without any download."""
|
||||
from konduktor.stems import engine_manager as em
|
||||
|
||||
files = [("htdemucs_ft.yaml", b"models: [a]\n"), ("a.safetensors", b"\0" * 64)]
|
||||
weights = {"repo": "x/y", "revision": "fake", "url": "http://invalid/{name}",
|
||||
"files": [{"name": n, "size": len(d), "sha256": hashlib.sha256(d).hexdigest()} for n, d in files]}
|
||||
mgr = em.EngineManager(root=root, weights=weights, target="macos-arm64")
|
||||
exe = write_fake_engine(root / mgr.version / "macos-arm64" / "konduktor-engine" / "konduktor-engine", mgr.version)
|
||||
(root / "installed.json").write_text(json.dumps(
|
||||
{"version": mgr.version, "target": "macos-arm64", "size": 1, "executable": str(exe), "info": {}}))
|
||||
wd = mgr.weights_dir()
|
||||
wd.mkdir(parents=True, exist_ok=True)
|
||||
for n, d in files:
|
||||
(wd / n).write_bytes(d)
|
||||
assert mgr.ready()
|
||||
return mgr
|
||||
|
||||
|
||||
def make_mp3(path: Path, seconds: float = 4, seed: int = 3) -> Path:
|
||||
"""An MP3 WITH a Xing/Info header (so Traktor's 2257-sample offset applies)."""
|
||||
sr = 44100
|
||||
rng = np.random.default_rng(seed)
|
||||
n = int(sr * seconds)
|
||||
x = np.zeros((2, n), np.float32)
|
||||
for start in range(sr // 2, n - sr // 10, sr // 2):
|
||||
x[:, start:start + 2000] = rng.uniform(-0.5, 0.5, (2, 2000))
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with av.open(str(path), "w", format="mp3") as c:
|
||||
s = c.add_stream("libmp3lame", rate=sr, layout="stereo")
|
||||
s.bit_rate = 320_000
|
||||
for o in range(0, n, 1152):
|
||||
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
|
||||
f.sample_rate, f.pts = sr, o
|
||||
for p in s.encode(f):
|
||||
c.mux(p)
|
||||
for p in s.encode(None):
|
||||
c.mux(p)
|
||||
return path
|
||||
@@ -0,0 +1,232 @@
|
||||
"""The "Rekordbox Export" target: a stick's legacy Device Library (`export.pdb`).
|
||||
|
||||
What Rekordbox lists as a stick's Device Library and pre-OneLibrary players
|
||||
read. There is no public spec, so this pins the writer to bytes REKORDBOX wrote:
|
||||
rows and a whole page taken from a real rekordbox 7 device export
|
||||
(`fixtures/rekordbox/device/reference_rows.json`) must be reproduced exactly.
|
||||
Then the structure a player walks (page chains, allocation, row indexes), and
|
||||
an export end to end — including that alongside the OneLibrary target the stick
|
||||
carries ONE set of analysis files and artwork, as a rekordbox-made stick does.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-test-"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import numpy as np # noqa: E402
|
||||
import soundfile as sf # noqa: E402
|
||||
from PIL import Image # noqa: E402
|
||||
|
||||
import konduktor.adapters # noqa: E402,F401 — registers every target
|
||||
from konduktor.adapters.rekordbox import pdb as P # 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 CuePoint, GridMarker, Track, TrackCues # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
REF = json.loads((P.TEMPLATE_DIR / "reference_rows.json").read_text())
|
||||
|
||||
print("== rows are rekordbox's bytes ==")
|
||||
fields = REF["track_row_demo_track_2_fields"]
|
||||
ours = P.track_row({k: v for k, v in fields.items() if k not in P.TRACK_STRINGS},
|
||||
{k: fields[k] for k in P.TRACK_STRINGS})
|
||||
check("a track row is byte-identical to rekordbox's", ours.hex() == REF["track_row_demo_track_2"])
|
||||
# rekordbox leaves variable slack after a row on its page (6-9 bytes, sometimes
|
||||
# stale data); readers find rows through the page's index, never by size. So a
|
||||
# row is compared over its own bytes.
|
||||
artist = P.artist_row(1, "Loopmasters").rstrip(b"\0")
|
||||
check("an artist row is byte-identical", REF["artist_row_loopmasters"].startswith(artist.hex()))
|
||||
plist = P.playlist_tree_row(1, 0, 1, "demos", folder=False).rstrip(b"\0")
|
||||
check("a playlist row is byte-identical", REF["playlist_row_demos"].startswith(plist.hex()))
|
||||
|
||||
print("== a page is rekordbox's bytes ==")
|
||||
page = bytes.fromhex(REF["keys_page"])
|
||||
n = (page[0x19] >> 5) | (page[0x1A] << 3)
|
||||
used = struct.unpack_from("<H", page, 0x1E)[0]
|
||||
offs = [struct.unpack_from("<H", page, P.PAGE - 6 - 2 * r)[0] for r in range(n)] + [used]
|
||||
rows = [page[0x28 + offs[r]:0x28 + offs[r + 1]] for r in range(n)]
|
||||
rebuilt = P._data_page(REF["keys_page_index"], P.KEYS, struct.unpack_from("<I", page, 12)[0], rows,
|
||||
struct.unpack_from("<I", page, 16)[0], shift_at=None)
|
||||
check("a data page rebuilt from its rows is byte-identical (header, heap, row index)", rebuilt == page)
|
||||
|
||||
print("== strings ==")
|
||||
for text in ("", "Am", "x" * 126, "x" * 127, "Café del Mar", "日本語"):
|
||||
enc = P.dsql(text)
|
||||
check(f"{text[:12]!r} ({len(text)} chars) round-trips", P.read_dsql(enc, 0) == text)
|
||||
check("up to 126 ASCII chars is a short string", P.dsql("x" * 126)[0] & 1 == 1)
|
||||
check("127+ ASCII chars is a long ASCII string (0x40)", P.dsql("x" * 127)[0] == 0x40)
|
||||
check("non-ASCII is UTF-16LE (0x90)", P.dsql("Café")[0] == 0x90)
|
||||
|
||||
print("== the writer follows rekordbox's allocation ==")
|
||||
tmpl = P.template()
|
||||
w = P.PdbWriter(tmpl)
|
||||
_slot, candidate, first, _last = w.tables[P.TRACKS]
|
||||
start_unused = w.next_unused
|
||||
many = [P.track_row({"subtype": 0x24, "id": i}, {"title": f"Track {i} " + "x" * 200,
|
||||
"file_path": f"/Contents/{i}.mp3"}) for i in range(1, 41)]
|
||||
w.fill(P.TRACKS, many)
|
||||
w.fill(P.ARTISTS, [P.artist_row(1, "A")])
|
||||
out = w.render()
|
||||
lib = P.read(out)
|
||||
check("all 40 tracks read back, in order", [t["id"] for t in lib.tracks] == list(range(1, 41)))
|
||||
tpages = [p for p in lib.pages[P.TRACKS] if not p["flags"] & 0x40]
|
||||
check("they span several pages", len(tpages) > 1, len(tpages))
|
||||
check("the first data page is the table's reserved candidate", tpages[0]["index"] == candidate)
|
||||
check("further pages come from the next-unused counter",
|
||||
all(p["index"] >= start_unused for p in tpages[1:]))
|
||||
check("the chain ends in a fresh reserved candidate beyond every data page",
|
||||
tpages[-1]["next"] >= max(p["index"] for p in tpages))
|
||||
check("the header page still starts the chain", lib.pages[P.TRACKS][0]["index"] == first)
|
||||
check("every page's free space follows rekordbox's arithmetic",
|
||||
all(p["free"] == P.PAGE - 0x28 - p["used"] - (2 * p["rows"] + 4 * ((p["rows"] + 15) // 16)) for p in tpages))
|
||||
check("tracks pages carry flags 0x34, others 0x24",
|
||||
all(p["flags"] == 0x34 for p in tpages)
|
||||
and all(p["flags"] == 0x24 for p in lib.pages[P.ARTISTS] if not p["flags"] & 0x40))
|
||||
fixed_pages = (13, 14, 33, 34, 35, 36, 37, 38)
|
||||
check("the fixed tables (colours, columns, menus) are untouched",
|
||||
all(out[p * P.PAGE:(p + 1) * P.PAGE] == tmpl[p * P.PAGE:(p + 1) * P.PAGE] for p in fixed_pages))
|
||||
print("== header pages index their data (else rekordbox: 'Device library is corrupted') ==")
|
||||
# A header page holds an index: its own number, the FIRST DATA PAGE, ... a
|
||||
# count and entries `page << 3 | flag`. Left pointing nowhere, rekordbox 7 called
|
||||
# a Konduktor-written library corrupted. Rules read off a real export.
|
||||
w.stamp_track_count(40)
|
||||
out = w.render()
|
||||
def index(buf, table):
|
||||
_t, _e, first, _l = next(struct.unpack_from("<4I", buf, 28 + 16 * i) for i in range(20)
|
||||
if struct.unpack_from("<I", buf, 28 + 16 * i)[0] == table)
|
||||
o = first * P.PAGE
|
||||
n = struct.unpack_from("<H", buf, o + 0x38)[0]
|
||||
return (struct.unpack_from("<I", buf, o + 0x2C)[0],
|
||||
[(e >> 3, e & 7) for e in struct.unpack_from(f"<{n}I", buf, o + 0x3C)],
|
||||
struct.unpack_from("<2H", buf, o + 0x20), struct.unpack_from("<H", buf, o + 0x26)[0])
|
||||
first_data, entries, (u5, nrl), u7 = index(out, P.TRACKS)
|
||||
check("the tracks header points at its first data page", first_data == tpages[0]["index"])
|
||||
check("and lists every data page: full ones flag 0, the last (with room) flag 3",
|
||||
entries == [(p["index"], 3 if k == len(tpages) - 1 else 0) for k, p in enumerate(tpages)], entries)
|
||||
check("its u7 counts them; u5 / nrl = pages with room / the first of them",
|
||||
u7 == len(tpages) and (u5, nrl) == (1, len(tpages) - 1), (u5, nrl, u7))
|
||||
check("a non-indexed table's header still points at its data",
|
||||
index(out, P.ARTISTS)[0] == next(p["index"] for p in P.read(out).pages[P.ARTISTS] if not p["flags"] & 0x40)
|
||||
and index(out, P.ARTISTS)[1] == [])
|
||||
h_first, h_entries, _, h_u7 = index(out, P.HISTORY)
|
||||
check("with tracks, the history page is indexed too (flag 0, count 1)",
|
||||
h_entries == [(h_first, 0)] and h_u7 == 1, (h_entries, h_u7))
|
||||
hist_row = next(r for h, r in P._rows(out, *struct.unpack_from("<2I", out, 28 + 16 * 19 + 8)) if r is not None)
|
||||
check("the history row counts the tracks and flags that there are some",
|
||||
out[hist_row + 3] == 1 and struct.unpack_from("<I", out, hist_row + 4)[0] == 40)
|
||||
full = [p for p in tpages[:-1]]
|
||||
check("full tracks pages carry 0x1FFF/0x1FFF, the last rows+1 / 0",
|
||||
all(struct.unpack_from("<2H", out, p["index"] * P.PAGE + 0x20) == (0x1FFF, 0x1FFF) for p in full)
|
||||
and struct.unpack_from("<2H", out, tpages[-1]["index"] * P.PAGE + 0x20) == (tpages[-1]["rows"] + 1, 0))
|
||||
check("the file header's second counter is 1 + pages with room", struct.unpack_from("<I", out, 16)[0] == 2)
|
||||
|
||||
try:
|
||||
w.fill(P.TRACKS, many[:1])
|
||||
check("filling a table twice is refused", False, "it accepted")
|
||||
except ValueError:
|
||||
check("filling a table twice is refused", True)
|
||||
|
||||
print("== an export end to end ==")
|
||||
root = Path(tempfile.mkdtemp())
|
||||
sr = 22050
|
||||
tone = np.random.default_rng(1).uniform(-0.4, 0.4, sr * 6).astype(np.float32)
|
||||
tracks = []
|
||||
for i, (title, artist, key) in enumerate((("One", "Artist A", (8, "minor")), ("Two", "Artist B", (None, None)),
|
||||
("Três", "Artist A", (8, "minor")))):
|
||||
audio = root / "Contents" / ("House" if i < 2 else "Techno") / f"{title}.wav"
|
||||
audio.parent.mkdir(parents=True, exist_ok=True)
|
||||
sf.write(audio, tone, sr)
|
||||
png = __import__("io").BytesIO()
|
||||
Image.new("RGB", (300, 300), (40 * i, 90, 160)).save(png, format="PNG")
|
||||
t = Track(id=f"src{i}", title=title, artist=artist, album="LP", genre="House", bpm=125.0,
|
||||
key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio))
|
||||
tracks.append(ExportTrack(track=t, destination=audio, art=(png.getvalue(), "image/png"),
|
||||
cues=TrackCues(track_id=t.id, grid_markers=[GridMarker(start=0.0, bpm=125.0)],
|
||||
cues=[CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0)])))
|
||||
payload = ExportPayload(name="GIG", tracks=tracks, playlists=[
|
||||
ExportPlaylist(name="Peak", track_ids=["src0", "src1"], folders=["House"])])
|
||||
dev = core_export.for_platform("rekordbox_export")
|
||||
check("the target is registered, named 'Rekordbox Export'", dev is not None and dev.display_name == "Rekordbox Export")
|
||||
check("and the master.db target is 'Rekordbox Library'",
|
||||
core_export.for_platform("rekordbox").display_name == "Rekordbox Library")
|
||||
written = dev.write(payload, root)
|
||||
lib = P.read(written.library.read_bytes())
|
||||
check("export.pdb lands in PIONEER/rekordbox/", written.library == root / "PIONEER" / "rekordbox" / "export.pdb")
|
||||
check("with exportExt.pdb beside it", (root / "PIONEER" / "rekordbox" / "exportExt.pdb") in written.extra)
|
||||
check("three tracks, titles intact (UTF-16 included)", [t["title"] for t in lib.tracks] == ["One", "Two", "Três"])
|
||||
check("artists are shared, not duplicated", lib.artists == {1: "Artist A", 2: "Artist B"})
|
||||
check("the key is rendered in rekordbox's notation", lib.keys == {1: "Am"}, lib.keys)
|
||||
check("a track with no key has key 0", lib.tracks[1]["key_id"] == 0)
|
||||
check("bpm x100, rating, file type, bitmask as rekordbox writes them",
|
||||
all(t["tempo"] == 12500 and t["u6"] == 11 and t["bitmask"] == 0xC0700 and t["u5"] == 0x29 for t in lib.tracks)
|
||||
and [t["rating"] for t in lib.tracks] == [1, 2, 3])
|
||||
check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"])
|
||||
check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks))
|
||||
tree = {p["name"]: p for p in lib.playlists}
|
||||
check("the tree: a folder named after the export > House > Peak, plus Other for loose tracks",
|
||||
tree["GIG"]["folder"] and tree["House"]["parent"] == tree["GIG"]["id"]
|
||||
and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == tree["GIG"]["id"])
|
||||
peak = [e for e in lib.entries if e[2] == tree["Peak"]["id"]]
|
||||
check("playlist entries in order, 1-based", peak == [(1, 1, tree["Peak"]["id"]), (2, 2, tree["Peak"]["id"])], peak)
|
||||
check("every track has an analysis path, and the files exist",
|
||||
all((root / t["analyze_path"].lstrip("/")).is_file() for t in lib.tracks))
|
||||
check("artwork rows name the a<n>.jpg files, which exist",
|
||||
all((root / p.lstrip("/")).is_file() for p in lib.artwork.values()) and len(lib.artwork) == 3)
|
||||
check("every file written is reported, so a re-export can clear it",
|
||||
all(p.exists() for p in written.all_paths))
|
||||
|
||||
print("== alongside OneLibrary: one set of analysis files and artwork ==")
|
||||
both = Path(tempfile.mkdtemp())
|
||||
for t in tracks:
|
||||
dst = both / t.destination.relative_to(root)
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
dst.write_bytes(t.destination.read_bytes())
|
||||
import dataclasses # noqa: E402
|
||||
moved = [dataclasses.replace(t, destination=both / t.destination.relative_to(root)) for t in tracks]
|
||||
both_payload = ExportPayload(name="GIG", tracks=moved, playlists=payload.playlists)
|
||||
ol_written = core_export.for_platform("onelibrary").write(both_payload, both)
|
||||
stamp = {p: p.stat().st_mtime_ns for p in ol_written.extra if p.suffix in (".DAT", ".EXT", ".2EX")}
|
||||
calls = []
|
||||
both_payload.checkpoint = lambda m, **_progress: calls.append(m)
|
||||
dev_written = dev.write(both_payload, both)
|
||||
dat_files = sorted(both.rglob("*.DAT"))
|
||||
check("still one .DAT per track", len(dat_files) == 3, len(dat_files))
|
||||
check("the device library reuses the analysis OneLibrary wrote (not rewritten)",
|
||||
all(p.stat().st_mtime_ns == m for p, m in stamp.items()))
|
||||
lib2 = P.read(dev_written.library.read_bytes())
|
||||
from konduktor.adapters.onelibrary.driver import OneLibraryDriver # noqa: E402
|
||||
ol = OneLibraryDriver().open(both)
|
||||
check("both libraries point at the same analysis files",
|
||||
sorted(str(r.analysisDataFilePath) for r in ol._store.iter_content()) == sorted(t["analyze_path"] for t in lib2.tracks))
|
||||
check("the a<n>.jpg files both write are the same files",
|
||||
{p.name for p in (both / "PIONEER/Artwork/00001").iterdir()} >= {Path(v).name for v in lib2.artwork.values()})
|
||||
check("progress is reported per track", len(calls) == 3, calls)
|
||||
|
||||
print("== the export dialog lists the targets in a fixed order ==")
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
from konduktor.main import app # noqa: E402
|
||||
|
||||
names = [o["name"] for o in TestClient(app).get("/api/export-targets").json()]
|
||||
check("OneLibrary, Traktor, Rekordbox Export, Rekordbox Library",
|
||||
names[:4] == ["OneLibrary", "Traktor", "Rekordbox Export", "Rekordbox Library"], names)
|
||||
flags = {o["name"]: o for o in TestClient(app).get("/api/export-targets").json()}
|
||||
check("Rekordbox Library says it is computer-only (the dialog warns beside a stick format)",
|
||||
flags["Rekordbox Library"]["computer_only"] and not flags["Rekordbox Export"]["computer_only"]
|
||||
and flags["Rekordbox Export"]["drive_root"])
|
||||
|
||||
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Discarding unsaved edits (`POST /api/discard`, `AppState.discard`).
|
||||
|
||||
Konduktor had no discard path at all: switching library dropped edits, quitting
|
||||
killed the backend. Discard is also what a stem conversion's parked originals
|
||||
will hang on, so it has to be exact. Pins:
|
||||
|
||||
* Traktor: an edit is dropped, the library is clean, the file on disk and the
|
||||
version history are untouched — and this session's relocation answers and
|
||||
saved path mapping survive (they are not edits; reopening would lose them).
|
||||
* A running batch is stopped BEFORE the reload, so it cannot keep writing
|
||||
into the reloaded library.
|
||||
* Rekordbox: the SQLAlchemy session, the buffered ANLZ grid writes and the
|
||||
journal all go — a plain re-open left the library still "dirty" and the
|
||||
next save still writing the discarded grids.
|
||||
* A read-only library has nothing to discard (409).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-discard-appdata-")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
print("== Traktor, through the routes ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
original = work.read_bytes()
|
||||
os.environ["KONDUKTOR_NML"] = str(work)
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import konduktor.main as main
|
||||
from konduktor import history
|
||||
from konduktor.core.pathmap import PathMapping
|
||||
|
||||
with TestClient(main.app) as c:
|
||||
a = main.require_adapter()
|
||||
track = next(t for t in a.tracks if t.genre)
|
||||
genre = track.genre # a string: the index updates Track objects in place
|
||||
commits_before = len(history.list_history(work))
|
||||
r = c.patch("/api/tracks", json={"track_id": track.id, "fields": {"genre": "Discard me"}})
|
||||
check("(setup) an edit makes the library dirty", r.status_code == 200 and c.get("/api/state").json()["dirty"])
|
||||
session = [PathMapping.make("/Volumes/Gone", "/Volumes/Here")]
|
||||
a.set_session_mappings(session)
|
||||
a.set_path_mapping(PathMapping.make("/Old", "/New"))
|
||||
|
||||
r = c.post("/api/discard")
|
||||
check("discard answers with a clean state", r.status_code == 200 and r.json()["dirty"] is False, r.text[:200])
|
||||
a = main.require_adapter()
|
||||
check("the edit is gone from the projection", a.track(track.id).genre == genre, a.track(track.id).genre)
|
||||
check("the file on disk was never touched", work.read_bytes() == original)
|
||||
check("no version was recorded", len(history.list_history(work)) == commits_before)
|
||||
check("this session's relocation answers survive", a.store._session_mappings == session)
|
||||
check("…and so does the saved path mapping", not a.store._path_mapping.empty)
|
||||
check("the same adapter object: a reload, not a reopen", main.STATE.adapter is a)
|
||||
|
||||
# A running batch is stopped (and waited for) before the reload.
|
||||
main.grid_detect.detect_grid = lambda p, *x, **k: (time.sleep(0.05), SimpleNamespace(anchor=0.1, bpm=128.0))[1]
|
||||
ids = [t.id for t in a.tracks[:60]]
|
||||
jid = c.post("/api/tracks/grid/auto-batch", json={"track_ids": ids, "replace_existing": True}).json()["id"]
|
||||
time.sleep(0.2)
|
||||
r = c.post("/api/discard")
|
||||
job = main.JOBS.get(jid)
|
||||
check("a running batch has STOPPED by the time discard returns", job.finished, job.state)
|
||||
time.sleep(0.2)
|
||||
check("…and nothing it did survives the reload", c.get("/api/state").json()["dirty"] is False)
|
||||
os.environ.pop("KONDUKTOR_NML", None)
|
||||
|
||||
print("== Rekordbox: session, buffered grids and journal all go ==")
|
||||
from konduktor.adapters.rekordbox import discovery # noqa: E402
|
||||
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
|
||||
|
||||
found = discovery.detect_libraries()
|
||||
if not found:
|
||||
print(" (skipped: no Rekordbox library on this machine)")
|
||||
else:
|
||||
src = Path(found[0]["path"])
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "master.db"
|
||||
shutil.copy2(src, work)
|
||||
if (src.parent / "share").is_dir():
|
||||
shutil.copytree(src.parent / "share", Path(d) / "share")
|
||||
before = work.read_bytes()
|
||||
ad = RekordboxAdapter(work)
|
||||
track = next(t for t in ad.tracks if t.title)
|
||||
title = track.title
|
||||
ad.set_track_metadata(track.id, {"title": "Discard me"})
|
||||
cues = ad.track_cues(track.id)
|
||||
if cues is not None and cues.grid_markers:
|
||||
ad.replace_grid(track.id, [(m.start + 0.01, m.bpm) for m in cues.grid_markers])
|
||||
check("(setup) edits make it dirty", ad.dirty)
|
||||
ad.reload()
|
||||
check("after discard it is clean", ad.dirty is False)
|
||||
check("the metadata edit is gone", ad.track(track.id).title == title, ad.track(track.id).title)
|
||||
check("no buffered grid write survives for the next save", not ad._store._pending_grids)
|
||||
ad.save()
|
||||
ad.close()
|
||||
check("a save after discard writes nothing the user threw away",
|
||||
RekordboxAdapter(work).track(track.id).title == title)
|
||||
del before
|
||||
|
||||
print("== read-only ==")
|
||||
os.environ["KONDUKTOR_NML"] = ""
|
||||
with TestClient(main.app) as c:
|
||||
r = c.post("/api/library/open", json={"path": str(FIXTURE)})
|
||||
if r.status_code == 200:
|
||||
check("a read-only library has nothing to discard (409)", c.post("/api/discard").status_code == 409)
|
||||
else:
|
||||
print(f" (skipped: fixture did not open: {r.status_code})")
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,330 @@
|
||||
"""The stem engine manager and process, against a LOCAL server and a FAKE engine.
|
||||
|
||||
No network, no torch: a tiny HTTP server (Range-aware, and able to ignore Range)
|
||||
serves a fake engine archive split into parts plus fake weights, and the fake
|
||||
engine is a script speaking the real protocol. Pins what fails silently:
|
||||
|
||||
* a download resumes from its `.part`, restarts if the server ignores the
|
||||
range, and never keeps a file whose checksum is wrong;
|
||||
* an install counts only once parts, archive AND a started engine all check
|
||||
out — a corrupt part or a wrong-version engine leaves nothing installed;
|
||||
* side-loading verifies against the release manifest; weights are verified;
|
||||
* the process driver relays progress, cancels without killing the engine,
|
||||
reports a crash WITH its reason, and ends the engine on close;
|
||||
* the CUDA engine is offered only for a new enough driver and card.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import threading
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-enginemgr-appdata-")
|
||||
|
||||
import numpy as np # noqa: E402
|
||||
|
||||
from konduktor.stems import download, engine_manager as em # noqa: E402
|
||||
from konduktor.stems.engine_process import EngineCancelled, EngineProcess, keep_awake # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
from stem_test_support import FAKE_ENGINE # noqa: E402 — the one fake engine, shared
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
root: Path
|
||||
ignore_range = False
|
||||
requests: list = []
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
path = self.root / self.path.lstrip("/")
|
||||
type(self).requests.append((self.path, self.headers.get("Range")))
|
||||
if not path.is_file():
|
||||
self.send_error(404)
|
||||
return
|
||||
data = path.read_bytes()
|
||||
rng = self.headers.get("Range")
|
||||
if rng and not type(self).ignore_range:
|
||||
start = int(rng.split("=")[1].split("-")[0])
|
||||
body = data[start:]
|
||||
self.send_response(206)
|
||||
self.send_header("Content-Range", f"bytes {start}-{len(data) - 1}/{len(data)}")
|
||||
else:
|
||||
body = data
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(body)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass # the cancel test hangs up mid-download, on purpose
|
||||
|
||||
|
||||
def sha(b: bytes) -> str:
|
||||
return hashlib.sha256(b).hexdigest()
|
||||
|
||||
|
||||
tmp = Path(tempfile.mkdtemp(prefix="konduktor-enginemgr-"))
|
||||
site = tmp / "site"
|
||||
site.mkdir()
|
||||
Handler.root = site
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
BASE = f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
print("== the weights manifest ==")
|
||||
repo_copy = json.loads((Path(__file__).resolve().parents[1] / "engine" / "weights.json").read_text())
|
||||
check("the backend's weights.json is the engine's (no drift)", em.WEIGHTS == repo_copy)
|
||||
|
||||
print("== download: resume, restart, verify, cancel ==")
|
||||
blob = os.urandom(3_000_000)
|
||||
(site / "blob.bin").write_bytes(blob)
|
||||
dest = tmp / "dl" / "blob.bin"
|
||||
dest.parent.mkdir()
|
||||
(dest.parent / "blob.bin.part").write_bytes(blob[:1_000_000])
|
||||
seen = []
|
||||
Handler.requests.clear()
|
||||
download.fetch(f"{BASE}/blob.bin", dest, sha256=sha(blob), size=len(blob), on_bytes=seen.append)
|
||||
check("a download resumes from its .part with a Range request",
|
||||
Handler.requests[-1][1] == "bytes=1000000-" and dest.read_bytes() == blob, str(Handler.requests[-1]))
|
||||
check("…and progress counts the resumed bytes once", sum(seen) == len(blob), str(sum(seen)))
|
||||
dest.unlink()
|
||||
(dest.parent / "blob.bin.part").write_bytes(blob[:1_000_000])
|
||||
Handler.ignore_range = True
|
||||
seen.clear()
|
||||
download.fetch(f"{BASE}/blob.bin", dest, sha256=sha(blob), size=len(blob), on_bytes=seen.append)
|
||||
Handler.ignore_range = False
|
||||
check("a server that ignores Range makes it start over, correctly", dest.read_bytes() == blob and sum(seen) == len(blob))
|
||||
dest.unlink()
|
||||
try:
|
||||
download.fetch(f"{BASE}/blob.bin", dest, sha256="0" * 64, size=len(blob))
|
||||
check("a checksum mismatch is refused", False, "kept it")
|
||||
except download.DownloadError:
|
||||
check("a checksum mismatch is refused, and nothing is kept",
|
||||
not dest.exists() and not (dest.parent / "blob.bin.part").exists())
|
||||
calls = {"n": 0}
|
||||
|
||||
|
||||
def cancel_soon():
|
||||
calls["n"] += 1
|
||||
return calls["n"] > 1
|
||||
|
||||
|
||||
try:
|
||||
download.fetch(f"{BASE}/blob.bin", dest, sha256=sha(blob), size=len(blob), cancelled=cancel_soon)
|
||||
check("a cancelled download stops", False, "finished")
|
||||
except download.DownloadCancelled:
|
||||
check("a cancelled download stops, keeping its .part to resume", (dest.parent / "blob.bin.part").exists()
|
||||
and not dest.exists())
|
||||
|
||||
print("== engine install ==")
|
||||
VERSION = em.CONFIG["version"]
|
||||
|
||||
|
||||
def make_release(version_reported: str, name: str, parts: int = 2) -> dict:
|
||||
"""A fake engine archive, split into `parts`, plus its manifest entry."""
|
||||
src = tmp / f"build-{name}"
|
||||
exe = src / "konduktor-engine" / "konduktor-engine"
|
||||
exe.parent.mkdir(parents=True, exist_ok=True)
|
||||
exe.write_text(FAKE_ENGINE.format(python=sys.executable, version=version_reported))
|
||||
exe.chmod(exe.stat().st_mode | stat.S_IEXEC)
|
||||
archive = tmp / f"{name}.tar.gz"
|
||||
with tarfile.open(archive, "w:gz") as tar:
|
||||
tar.add(src / "konduktor-engine", arcname="konduktor-engine")
|
||||
data = archive.read_bytes()
|
||||
size = -(-len(data) // parts)
|
||||
entry = {"archive": archive.name, "size": len(data), "sha256": sha(data), "unpacked_size": 1234, "parts": []}
|
||||
for i in range(parts):
|
||||
chunk = data[i * size:(i + 1) * size]
|
||||
part = f"{name}.tar.gz.part{i:02d}"
|
||||
(site / part).write_bytes(chunk)
|
||||
entry["parts"].append({"name": part, "size": len(chunk), "sha256": sha(chunk)})
|
||||
return entry, archive
|
||||
|
||||
|
||||
good, good_archive = make_release(VERSION, "good")
|
||||
wrong, _ = make_release("0.0.1", "wrong")
|
||||
config = dict(em.CONFIG, manifest_url=f"{BASE}/manifest-{{version}}.json", asset_url=f"{BASE}/{{name}}")
|
||||
(site / f"manifest-{VERSION}.json").write_text(json.dumps(
|
||||
{"version": VERSION, "targets": {"macos-arm64": good, "windows-x64-cpu": wrong}}))
|
||||
|
||||
root = tmp / "root"
|
||||
mgr = em.EngineManager(root=root, config=config, target="macos-arm64")
|
||||
check("nothing is installed to begin with", mgr.installed() is None and not mgr.ready())
|
||||
status = mgr.status()
|
||||
check("status offers this computer's engine, with its download size",
|
||||
status["offered_targets"] == ["macos-arm64"] and status["download_sizes"]["macos-arm64"] == good["size"], str(status))
|
||||
got = []
|
||||
rec = mgr.install_engine(on_bytes=got.append)
|
||||
check("the engine installs from its parts", mgr.installed() is not None and Path(rec["executable"]).is_file())
|
||||
check("…with byte progress for the whole download", sum(got) == good["size"], str(sum(got)))
|
||||
check("…and the installed engine was PROBED (it started and named its version)", rec["info"]["version"] == VERSION)
|
||||
check("the downloaded parts are cleaned up", not any((root / "downloads").glob("*")))
|
||||
|
||||
mgr2 = em.EngineManager(root=tmp / "root2", config=config, target="windows-x64-cpu")
|
||||
try:
|
||||
mgr2.install_engine()
|
||||
check("an engine reporting the wrong version is refused", False, "installed")
|
||||
except em.EngineError as ex:
|
||||
check("an engine reporting the wrong version is refused, and nothing is installed",
|
||||
mgr2.installed() is None and not any((tmp / "root2" / VERSION).glob("*")), str(ex))
|
||||
|
||||
(site / good["parts"][1]["name"]).write_bytes(b"corrupt")
|
||||
mgr3 = em.EngineManager(root=tmp / "root3", config=config, target="macos-arm64")
|
||||
try:
|
||||
mgr3.install_engine()
|
||||
check("a corrupt part is refused", False, "installed")
|
||||
except (download.DownloadError, em.EngineError):
|
||||
check("a corrupt part is refused, and nothing is installed", mgr3.installed() is None)
|
||||
|
||||
print("== side-loading ==")
|
||||
mgr4 = em.EngineManager(root=tmp / "root4", config=config, target="macos-arm64")
|
||||
mgr4.side_load_engine(good_archive)
|
||||
check("an engine archive the user has is installed after its hash checks out", mgr4.installed() is not None)
|
||||
bogus = tmp / "bogus.tar.gz"
|
||||
bogus.write_bytes(b"not an engine")
|
||||
try:
|
||||
em.EngineManager(root=tmp / "root5", config=config, target="macos-arm64").side_load_engine(bogus)
|
||||
check("a file that is not the engine is refused", False, "installed")
|
||||
except em.EngineError:
|
||||
check("a file that is not the engine is refused", True)
|
||||
|
||||
print("== weights ==")
|
||||
files = [("htdemucs_ft.yaml", b"models: [a]\n"), ("a.safetensors", os.urandom(200_000))]
|
||||
for name, data in files:
|
||||
(site / "w" / "rev1").mkdir(parents=True, exist_ok=True)
|
||||
(site / "w" / "rev1" / name).write_bytes(data)
|
||||
wmanifest = {"repo": "x/y", "revision": "rev1", "url": f"{BASE}/w/{{revision}}/{{name}}",
|
||||
"files": [{"name": n, "size": len(d), "sha256": sha(d)} for n, d in files]}
|
||||
wm = em.EngineManager(root=tmp / "root6", config=config, weights=wmanifest, target="macos-arm64")
|
||||
check("weights are not installed to begin with", not wm.weights_installed())
|
||||
wm.install_weights()
|
||||
check("the weights install, verified", wm.weights_installed())
|
||||
side = tmp / "side-weights"
|
||||
side.mkdir()
|
||||
for name, data in files:
|
||||
(side / name).write_bytes(data)
|
||||
wm2 = em.EngineManager(root=tmp / "root7", config=config, weights=wmanifest, target="macos-arm64")
|
||||
wm2.side_load_weights(side)
|
||||
check("weights from a folder the user supplies are accepted when they verify", wm2.weights_installed())
|
||||
(side / "a.safetensors").write_bytes(b"tampered")
|
||||
try:
|
||||
em.EngineManager(root=tmp / "root8", config=config, weights=wmanifest, target="macos-arm64").side_load_weights(side)
|
||||
check("tampered weights are refused", False, "accepted")
|
||||
except em.EngineError:
|
||||
check("tampered weights are refused", True)
|
||||
mgr.remove()
|
||||
check("remove takes the engine away", mgr.installed() is None and not (root / VERSION).exists())
|
||||
|
||||
print("== CUDA is offered only where it will run ==")
|
||||
G = em.NvidiaGpu
|
||||
check("RTX 40-series, current driver: offered", em.cuda_suitable([G("RTX 4070", "581.08", 8.9)]) is not None)
|
||||
check("an old driver: not offered", em.cuda_suitable([G("RTX 4070", "552.22", 8.9)]) is None)
|
||||
check("a GTX 1060 (Pascal, 6.1): not offered", em.cuda_suitable([G("GTX 1060", "581.08", 6.1)]) is None)
|
||||
check("no card: not offered", em.cuda_suitable([]) is None)
|
||||
|
||||
print("== the engine process ==")
|
||||
exe = Path(mgr4.executable())
|
||||
pcm = np.random.default_rng(0).uniform(-0.5, 0.5, (2, 44100)).astype(np.float32)
|
||||
work = tmp / "work"
|
||||
with EngineProcess(exe, tmp, device="cpu") as eng:
|
||||
prog = []
|
||||
stems = eng.separate(pcm, work, on_progress=prog.append)
|
||||
check("separate returns four stems in drums/bass/other/vocals order",
|
||||
len(stems) == 4 and np.allclose(stems[0], pcm * 0.5) and np.allclose(stems[3], pcm * 0.1))
|
||||
check("…relaying progress", prog and prog[-1] == 1.0, str(prog))
|
||||
check("…and leaves no work files behind", not any(work.rglob("*.f32")), str(list(work.rglob("*"))))
|
||||
os.environ["FAKE_DELAY"] = "0.05"
|
||||
try:
|
||||
eng.separate(pcm, work, cancelled=lambda: True)
|
||||
check("a cancel stops the track", False, "finished")
|
||||
except EngineCancelled:
|
||||
check("a cancel stops the track", True)
|
||||
os.environ.pop("FAKE_DELAY")
|
||||
check("…and the engine is still usable", len(eng.separate(pcm, work)) == 4)
|
||||
proc = eng.proc
|
||||
check("closing ends the engine process", proc.poll() is not None)
|
||||
os.environ["FAKE_ERROR"] = "1"
|
||||
with EngineProcess(exe, tmp) as eng:
|
||||
try:
|
||||
eng.separate(pcm, work)
|
||||
check("an engine error is reported", False)
|
||||
except em.EngineError as ex:
|
||||
check("an engine error is reported with its message", "bad input" in str(ex), str(ex))
|
||||
os.environ.pop("FAKE_ERROR")
|
||||
os.environ["FAKE_CRASH"] = "1"
|
||||
with EngineProcess(exe, tmp) as eng:
|
||||
try:
|
||||
eng.separate(pcm, work)
|
||||
check("an engine crash is reported", False)
|
||||
except em.EngineError as ex:
|
||||
check("an engine crash is reported WITH its reason", "out of cheese" in str(ex), str(ex))
|
||||
os.environ.pop("FAKE_CRASH")
|
||||
if sys.platform == "darwin":
|
||||
import subprocess
|
||||
with EngineProcess(exe, tmp) as eng, keep_awake(eng.proc.pid):
|
||||
running = subprocess.run(["pgrep", "-f", f"caffeinate -i -w {eng.proc.pid}"], capture_output=True).returncode == 0
|
||||
check("the machine is kept awake while the engine runs (caffeinate)", running)
|
||||
|
||||
print("== the routes ==")
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
import time as _time # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
|
||||
# A fresh, uncorrupted release for the routes (an earlier check corrupted `good`).
|
||||
fresh, _ = make_release(VERSION, "fresh")
|
||||
(site / f"manifest-{VERSION}.json").write_text(json.dumps({"version": VERSION, "targets": {"macos-arm64": fresh}}))
|
||||
em._DEFAULT = em.EngineManager(root=tmp / "root-routes", config=config, weights=wmanifest, target="macos-arm64")
|
||||
with TestClient(main.app) as c:
|
||||
st = c.get("/api/stems/engine").json()
|
||||
check("status: supported, nothing installed, a download size known",
|
||||
st["supported"] and st["installed"] is None and st["download_sizes"]["macos-arm64"] == fresh["size"], str(st)[:300])
|
||||
os.environ["FAKE_DELAY"] = "0"
|
||||
gate = threading.Event()
|
||||
blocker = main.JOBS.submit(main.ENGINE_JOB, lambda h: gate.wait(10))
|
||||
second = c.post("/api/stems/engine/install", json={})
|
||||
gate.set()
|
||||
main.JOBS.wait(blocker.id, 10)
|
||||
job = c.post("/api/stems/engine/install", json={}).json()
|
||||
end = _time.time() + 30
|
||||
while _time.time() < end:
|
||||
j = c.get(f"/api/jobs/{job['id']}").json()
|
||||
if j["state"] != "running":
|
||||
break
|
||||
_time.sleep(0.05)
|
||||
check("install runs as a job counting BYTES (engine + weights)",
|
||||
j["state"] == "done" and j["unit"] == "bytes"
|
||||
and j["total"] == fresh["size"] + sum(f["size"] for f in wmanifest["files"]), str(j)[:300])
|
||||
check("…that ends ready to convert", j["result"] == {"target": "macos-arm64", "ready": True}, str(j["result"]))
|
||||
check("an install while another runs is refused (409)", second.status_code == 409, str(second.status_code))
|
||||
st = c.get("/api/stems/engine").json()
|
||||
check("status now shows the engine and the weights", st["installed"] is not None and st["weights"]["installed"])
|
||||
r = c.post("/api/stems/engine/sideload", json={"path": str(bogus), "kind": "engine"})
|
||||
check("side-loading a file that is not the engine is refused (400)", r.status_code == 400, r.text[:200])
|
||||
r = c.delete("/api/stems/engine")
|
||||
check("remove answers with nothing installed", r.status_code == 200 and r.json()["installed"] is None)
|
||||
|
||||
server.shutdown()
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
+338
-3
@@ -14,6 +14,7 @@ work perfectly on the machine that made it and resolve to nothing at the gig.
|
||||
Runs against the 8,485-entry fixture collection, so the tracks have real prep —
|
||||
flexible grids, hot cues on specific pads — rather than anything invented here.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
@@ -216,7 +217,7 @@ ad = STATE.adapter
|
||||
LIB = STATE.library_id
|
||||
|
||||
dest = Path(tempfile.mkdtemp()) / "GIG"
|
||||
eset = exports.create(LIB, name="GIG", target="traktor", destination=str(dest))
|
||||
eset = exports.create(LIB, name="GIG", targets=["traktor"], destination=str(dest))
|
||||
source_pl = next(n for n in ad.playlist_tree()[0].children if n.kind == "playlist")
|
||||
exports.add(LIB, eset.id, playlist_ids=[source_pl.id], track_ids=[ad.tracks[3].id])
|
||||
eset = exports.get(LIB, eset.id)
|
||||
@@ -229,14 +230,18 @@ def run_now(plan):
|
||||
return job
|
||||
|
||||
|
||||
print("== the plan mirrors the source tree, relative to its shared root ==")
|
||||
print("== the plan mirrors the source tree under Contents/, relative to its shared root ==")
|
||||
built = exporter.plan(ad, eset)
|
||||
check("nothing is blocking it", built.blocked is None, str(built.blocked))
|
||||
check("every track has somewhere to go", all(t.destination for t in built.exportable))
|
||||
rel = [str(t.destination.relative_to(dest)) for t in built.exportable]
|
||||
# Under Contents/, so the audio can never land on top of a library's own path.
|
||||
check("all audio lives under Contents/",
|
||||
all(r.startswith(exporter.AUDIO_DIR + "/") for r in rel), rel)
|
||||
# Mirroring ABSOLUTE paths would put the user's home directory on the stick.
|
||||
check("the user's own folders are preserved",
|
||||
all(r.startswith(("House/", "Techno/")) for r in rel), rel)
|
||||
all(r.startswith(("Contents/House/", "Contents/Techno/")) for r in rel), rel)
|
||||
check("a Traktor-only export never warns about a drive root", built.not_drive_root == [])
|
||||
check("and nothing above the shared root comes with them",
|
||||
not any("Users" in r or r.startswith("/") for r in rel), rel)
|
||||
check("space is checked before starting", exporter.space_for(built) is not None)
|
||||
@@ -338,6 +343,336 @@ check("no manifest either", not (fresh / exporter.MANIFEST_NAME).exists())
|
||||
leftover = [p for p in fresh.rglob("*") if p.is_file()] if fresh.exists() else []
|
||||
check("and no audio was left behind", leftover == [], [str(p) for p in leftover])
|
||||
|
||||
print("== several targets share ONE copy of the audio ==")
|
||||
from konduktor.adapters.onelibrary.driver import OneLibraryDriver # noqa: E402
|
||||
|
||||
multi = Path(tempfile.mkdtemp()) / "STICK"
|
||||
exports.update(LIB, eset.id, destination=str(multi), targets=["traktor", "onelibrary"])
|
||||
eset = exports.get(LIB, eset.id)
|
||||
check("the set keeps both targets, in order", eset.targets == ["traktor", "onelibrary"], eset.targets)
|
||||
mplan = exporter.plan(ad, eset)
|
||||
check("nothing is blocking it", mplan.blocked is None, str(mplan.blocked))
|
||||
# A temp folder is not a drive's root, and only OneLibrary cares.
|
||||
check("only the drive-root target is warned about", mplan.not_drive_root == ["onelibrary"],
|
||||
mplan.not_drive_root)
|
||||
mjob = run_now(mplan)
|
||||
check("it finishes", mjob.state == "done", f"{mjob.state}: {mjob.error}")
|
||||
check("the result names both libraries",
|
||||
[l["platform"] for l in mjob.result["libraries"]] == ["traktor", "onelibrary"],
|
||||
mjob.result.get("libraries"))
|
||||
mrel = [t.destination.relative_to(multi) for t in mplan.exportable]
|
||||
audio_files = [p for p in multi.rglob("*") if p.is_file() and p.parts[len(multi.parts)] == "Contents"]
|
||||
check("the audio was copied once, not once per target", len(audio_files) == len(mrel),
|
||||
f"{len(audio_files)} files for {len(mrel)} tracks")
|
||||
t_lib = TraktorDriver().open(multi / "collection.nml")
|
||||
o_lib = OneLibraryDriver().open(multi)
|
||||
check("the Traktor collection re-opens with every track", len(t_lib.tracks) == len(mrel))
|
||||
check("so does the OneLibrary drive", len(o_lib.tracks) == len(mrel))
|
||||
# Both libraries must point at the SAME files — a second copy would be a bug
|
||||
# in the plan, and a dangling path would be one in a writer.
|
||||
check("every OneLibrary track resolves to a copied file",
|
||||
all(o_lib.audio_path(t.id) and o_lib.audio_path(t.id).is_file() for t in o_lib.tracks))
|
||||
check("OneLibrary paths are drive-relative under /Contents/",
|
||||
all(t.id.startswith("/Contents/") for t in o_lib.tracks), [t.id for t in o_lib.tracks][:2])
|
||||
manifest = json.loads((multi / exporter.MANIFEST_NAME).read_text())
|
||||
check("the manifest lists both libraries",
|
||||
sorted(manifest["libraries"]) == sorted(["collection.nml", str(Path("PIONEER/rekordbox/exportLibrary.db"))]),
|
||||
manifest["libraries"])
|
||||
del t_lib, o_lib
|
||||
|
||||
print("== unticking a target removes its library on the next export ==")
|
||||
exports.update(LIB, eset.id, targets=["traktor"])
|
||||
eset = exports.get(LIB, eset.id)
|
||||
job3 = run_now(exporter.plan(ad, eset))
|
||||
check("the re-export succeeds", job3.state == "done", f"{job3.state}: {job3.error}")
|
||||
check("the OneLibrary library is gone", not (multi / "PIONEER").exists(),
|
||||
sorted(str(p.relative_to(multi)) for p in (multi / "PIONEER").rglob("*")) if (multi / "PIONEER").exists() else "")
|
||||
check("the Traktor one and the audio remain",
|
||||
(multi / "collection.nml").is_file() and all((multi / r).is_file() for r in mrel))
|
||||
|
||||
print("== a manifest from a single-target export is still cleared ==")
|
||||
old = Path(tempfile.mkdtemp()) / "OldExport"
|
||||
old.mkdir()
|
||||
(old / "collection.nml").write_text("stale")
|
||||
(old / "House").mkdir()
|
||||
(old / "House" / "stale.mp3").write_bytes(b"x")
|
||||
(old / exporter.MANIFEST_NAME).write_text(json.dumps(
|
||||
{"library": "collection.nml", "files": ["House/stale.mp3"]}))
|
||||
exports.update(LIB, eset.id, destination=str(old))
|
||||
job4 = run_now(exporter.plan(ad, exports.get(LIB, eset.id)))
|
||||
check("the re-export succeeds", job4.state == "done", f"{job4.state}: {job4.error}")
|
||||
check("the old root-level audio was cleared", not (old / "House").exists())
|
||||
check("and the new collection replaced the old one",
|
||||
(old / "collection.nml").read_text() != "stale")
|
||||
|
||||
print("== a failing LATER target undoes everything, earlier targets included ==")
|
||||
failing = Path(tempfile.mkdtemp()) / "Failing"
|
||||
exports.update(LIB, eset.id, destination=str(failing), targets=["traktor", "onelibrary"])
|
||||
onelib = core_export.for_platform("onelibrary")
|
||||
|
||||
|
||||
def _half_written(payload, destination):
|
||||
# Writes files it never gets to REPORT, then fails — the case the rollback's
|
||||
# snapshot exists for.
|
||||
stray = Path(destination) / "PIONEER" / "USBANLZ" / "P000" / "0000" / "ANLZ0000.DAT"
|
||||
stray.parent.mkdir(parents=True, exist_ok=True)
|
||||
stray.write_bytes(b"partial")
|
||||
raise RuntimeError("disk full")
|
||||
|
||||
|
||||
eset = exports.get(LIB, eset.id) # run_now() runs the module-level set
|
||||
onelib.write = _half_written
|
||||
try:
|
||||
job5 = run_now(exporter.plan(ad, eset))
|
||||
finally:
|
||||
del onelib.write
|
||||
check("the export fails", job5.state == "failed", job5.state)
|
||||
left = sorted(str(p.relative_to(failing)) for p in failing.rglob("*")) if failing.exists() else []
|
||||
check("nothing at all is left behind — no audio, no Traktor library, no stray analysis",
|
||||
left == [], left)
|
||||
exports.update(LIB, eset.id, destination=str(dest), targets=["traktor"])
|
||||
eset = exports.get(LIB, eset.id)
|
||||
|
||||
print("== a re-export copies only what changed ==")
|
||||
from konduktor.core import analysis_cache, waveform # noqa: E402
|
||||
|
||||
calls = {"copy": 0, "analyse": 0}
|
||||
_real_copy, _real_analyse = exporter.copy_file, waveform.analyse
|
||||
|
||||
|
||||
def _counting_copy(*a, **kw):
|
||||
calls["copy"] += 1
|
||||
return _real_copy(*a, **kw)
|
||||
|
||||
|
||||
def _counting_analyse(*a, **kw):
|
||||
calls["analyse"] += 1
|
||||
return _real_analyse(*a, **kw)
|
||||
|
||||
|
||||
exporter.copy_file, waveform.analyse = _counting_copy, _counting_analyse
|
||||
|
||||
|
||||
def run_set(s, plan, handle=None):
|
||||
if handle is not None:
|
||||
return exporter.run(ad, s, plan, handle)
|
||||
job = JOBS.submit("export", lambda h: exporter.run(ad, s, plan, h))
|
||||
while not job.finished:
|
||||
time.sleep(0.02)
|
||||
return job
|
||||
|
||||
|
||||
def reset():
|
||||
calls["copy"] = calls["analyse"] = 0
|
||||
|
||||
|
||||
def inodes(root):
|
||||
return {str(p.relative_to(root)): p.stat().st_ino
|
||||
for p in (root / exporter.AUDIO_DIR).rglob("*") if p.is_file()}
|
||||
|
||||
|
||||
inc = Path(tempfile.mkdtemp()) / "INC"
|
||||
iset = exports.create(LIB, name="INC", targets=["traktor", "onelibrary"], destination=str(inc))
|
||||
exports.add(LIB, iset.id, track_ids=[t.id for t in ad.tracks[:4]])
|
||||
iset = exports.get(LIB, iset.id)
|
||||
|
||||
first = exporter.plan(ad, iset)
|
||||
check("a first export reuses nothing", first.unchanged == 0 and first.total_bytes == 4 * 300_000,
|
||||
(first.unchanged, first.total_bytes))
|
||||
reset()
|
||||
j = run_set(iset, first)
|
||||
check("it finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("every file was copied and measured once", calls == {"copy": 4, "analyse": 4}, calls)
|
||||
manifest = json.loads((inc / exporter.MANIFEST_NAME).read_text())
|
||||
check("the manifest records each copy's source",
|
||||
sorted(r["source"] for r in manifest["audio"].values())
|
||||
== sorted(str(ad.audio_path(t.id)) for t in ad.tracks[:4]))
|
||||
check("no temporary files are left", not any(
|
||||
p.name.endswith(exporter.PARTIAL_SUFFIX) for p in inc.rglob("*")))
|
||||
before_ino = inodes(inc)
|
||||
|
||||
again = exporter.plan(ad, iset)
|
||||
check("nothing changed, so nothing is to be copied",
|
||||
again.unchanged == 4 and again.total_bytes == 0 and again.as_dict()["unchanged"] == 4,
|
||||
(again.unchanged, again.total_bytes))
|
||||
reset()
|
||||
j = run_set(iset, again)
|
||||
check("the re-export finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("no audio was copied and no track decoded", calls == {"copy": 0, "analyse": 0}, calls)
|
||||
check("the kept files are the very same files", inodes(inc) == before_ino)
|
||||
check("both libraries were still rewritten and re-open with every track",
|
||||
len(TraktorDriver().open(inc / "collection.nml").tracks) == 4
|
||||
and len(OneLibraryDriver().open(inc).tracks) == 4)
|
||||
|
||||
|
||||
|
||||
class _Recorder:
|
||||
"""A handle that keeps every progress report."""
|
||||
|
||||
def __init__(self):
|
||||
self.reports = []
|
||||
|
||||
def progress(self, **kw):
|
||||
self.reports.append(kw)
|
||||
|
||||
cancelled = False
|
||||
|
||||
def raise_if_cancelled(self):
|
||||
pass
|
||||
|
||||
|
||||
rec = _Recorder()
|
||||
run_set(iset, exporter.plan(ad, iset), rec)
|
||||
track_steps = [(r["done"], r["total"]) for r in rec.reports
|
||||
if r.get("unit") == "tracks" and r.get("total")]
|
||||
# The bug: the bar counted only bytes, so a re-export that copied nothing sat
|
||||
# on an indeterminate bar through the whole (slow) library write.
|
||||
check("with nothing to copy, the bar still moves — per track, while writing",
|
||||
track_steps and track_steps[-1] == (3, 4) and len(track_steps) >= 4, track_steps)
|
||||
|
||||
print("== an edited source is copied again, and only it ==")
|
||||
edited = ad.audio_path(ad.tracks[0].id)
|
||||
edited.write_bytes(b"\1" * 310_000) # what a tag write does: new bytes, new mtime
|
||||
plan3 = exporter.plan(ad, iset)
|
||||
check("one track is to be copied", plan3.unchanged == 3 and plan3.total_bytes == 310_000,
|
||||
(plan3.unchanged, plan3.total_bytes))
|
||||
reset()
|
||||
j = run_set(iset, plan3)
|
||||
check("it finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("one file copied, one decoded", calls == {"copy": 1, "analyse": 1}, calls)
|
||||
edited_copy = next(Path(t.destination) for t in plan3.exportable if t.source_path == edited)
|
||||
check("the copy on the stick is the new version", edited_copy.read_bytes() == b"\1" * 310_000)
|
||||
|
||||
print("== a copy changed ON the stick is not trusted ==")
|
||||
tampered = next(Path(t.destination) for t in plan3.exportable if t.source_path != edited)
|
||||
with tampered.open("ab") as f:
|
||||
f.write(b"junk")
|
||||
plan4 = exporter.plan(ad, iset)
|
||||
check("it alone is copied again",
|
||||
[Path(t.destination) for t in plan4.exportable if t.reuse is None] == [tampered],
|
||||
[str(t.destination) for t in plan4.exportable if t.reuse is None])
|
||||
j = run_set(iset, plan4)
|
||||
check("and the original is restored", j.state == "done" and tampered.stat().st_size == 300_000)
|
||||
|
||||
print("== a moved shared root renames kept copies instead of copying them ==")
|
||||
house = [t for t in ad.tracks[:4] if "/House/" in str(ad.audio_path(t.id))]
|
||||
techno = [t for t in ad.tracks[:4] if t not in house]
|
||||
moved = Path(tempfile.mkdtemp()) / "MOVED"
|
||||
mset = exports.create(LIB, name="MOVED", targets=["traktor"], destination=str(moved))
|
||||
exports.add(LIB, mset.id, track_ids=[t.id for t in house])
|
||||
mset = exports.get(LIB, mset.id)
|
||||
run_set(mset, exporter.plan(ad, mset))
|
||||
old_paths = inodes(moved)
|
||||
check("with only House tracks, the root is House itself",
|
||||
all(not r.startswith("Contents/House/") for r in old_paths), sorted(old_paths))
|
||||
exports.add(LIB, mset.id, track_ids=[techno[0].id])
|
||||
mset = exports.get(LIB, mset.id)
|
||||
mplan = exporter.plan(ad, mset)
|
||||
check("adding a Techno track moves every path, yet the House copies are reused",
|
||||
mplan.unchanged == len(house)
|
||||
and mplan.total_bytes == ad.audio_path(techno[0].id).stat().st_size,
|
||||
(mplan.unchanged, mplan.total_bytes))
|
||||
reset()
|
||||
j = run_set(mset, mplan)
|
||||
check("it finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("only the new track was copied", calls["copy"] == 1, calls)
|
||||
new_paths = inodes(moved)
|
||||
check("the kept copies now sit under House/, as the same files",
|
||||
sorted(v for r, v in new_paths.items() if r.startswith("Contents/House/"))
|
||||
== sorted(old_paths.values()), sorted(new_paths))
|
||||
check("and nothing is left at the old paths or in staging",
|
||||
not any((moved / r).exists() for r in old_paths)
|
||||
and not (moved / exporter.MOVING_DIR).exists())
|
||||
check("the collection points at the moved copies",
|
||||
all(TraktorDriver().open(moved / "collection.nml").audio_path(t.id).is_file()
|
||||
for t in TraktorDriver().open(moved / "collection.nml").tracks))
|
||||
|
||||
print("== a removed track's copy is removed ==")
|
||||
exports.remove(LIB, mset.id, track_ids=[techno[0].id])
|
||||
mset = exports.get(LIB, mset.id)
|
||||
j = run_set(mset, exporter.plan(ad, mset))
|
||||
check("it finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("the Techno copy is gone", not any("Techno" in str(p) for p in moved.rglob("*")),
|
||||
sorted(str(p.relative_to(moved)) for p in moved.rglob("*")))
|
||||
|
||||
print("== cancelling a re-export keeps what it kept, and the folder stays ours ==")
|
||||
edited.write_bytes(b"\2" * 320_000)
|
||||
cplan = exporter.plan(ad, iset)
|
||||
kept_before = {Path(t.destination) for t in cplan.exportable if t.reuse is not None}
|
||||
try:
|
||||
run_set(iset, cplan, _CancelAfter(2))
|
||||
check("it stops", False, "it did not raise")
|
||||
except JobCancelled:
|
||||
check("it stops", True)
|
||||
check("no library was left", not (inc / "collection.nml").exists()
|
||||
and not (inc / "PIONEER" / "rekordbox" / "exportLibrary.db").exists())
|
||||
check("the kept copies are still there", all(p.is_file() for p in kept_before))
|
||||
check("the half-copied file is not", not (edited_copy.exists() or any(
|
||||
p.name.endswith(exporter.PARTIAL_SUFFIX) for p in inc.rglob("*"))))
|
||||
retry = exporter.plan(ad, iset)
|
||||
check("the folder is still ours, not refused", retry.blocked is None, str(retry.blocked))
|
||||
check("and the retry still reuses the kept copies", retry.unchanged == len(kept_before),
|
||||
(retry.unchanged, len(kept_before)))
|
||||
reset()
|
||||
j = run_set(iset, retry)
|
||||
check("the retry finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("decoding only the changed track — the rest came from the cache", calls["analyse"] == 1, calls)
|
||||
|
||||
print("== the analysis cache ==")
|
||||
cache_dir = inc / analysis_cache.CACHE_DIR
|
||||
check("it lives on the drive", cache_dir.is_dir() and len(list(cache_dir.iterdir())) == 4,
|
||||
sorted(p.name for p in cache_dir.iterdir()) if cache_dir.exists() else "")
|
||||
check("and is not in the manifest, so a re-export never clears it",
|
||||
not any(f.startswith(analysis_cache.CACHE_DIR)
|
||||
for f in json.loads((inc / exporter.MANIFEST_NAME).read_text())["files"]))
|
||||
exports.remove(LIB, iset.id, track_ids=[ad.tracks[3].id])
|
||||
iset = exports.get(LIB, iset.id)
|
||||
run_set(iset, exporter.plan(ad, iset))
|
||||
check("a removed track's entry is pruned", len(list(cache_dir.iterdir())) == 3)
|
||||
# Round-trips a real measurement, not just the undecodable marker the silent
|
||||
# fixture files produce.
|
||||
import numpy as np # noqa: E402
|
||||
import soundfile as sf # noqa: E402
|
||||
|
||||
tone_dir = Path(tempfile.mkdtemp())
|
||||
tone = tone_dir / "tone.wav"
|
||||
sf.write(tone, 0.5 * np.sin(np.linspace(0, 2000 * np.pi, 44100 * 3)), 44100)
|
||||
c = analysis_cache.AnalysisCache(tone_dir / "cache")
|
||||
key = analysis_cache.fingerprint(tone, tone.stat().st_size, tone.stat().st_mtime_ns)
|
||||
fresh_a = c.analyse(tone, key, lead=0.025)
|
||||
reset()
|
||||
cached_a = c.analyse(tone, key, lead=0.025)
|
||||
check("a hit does not decode", calls["analyse"] == 0, calls)
|
||||
check("and returns the same measurement, exactly",
|
||||
fresh_a is not None and cached_a is not None
|
||||
and np.array_equal(fresh_a.columns.rms, cached_a.columns.rms)
|
||||
and np.array_equal(fresh_a.columns.brightness, cached_a.columns.brightness)
|
||||
and np.array_equal(fresh_a.frames.bands, cached_a.frames.bands)
|
||||
and fresh_a.duration == cached_a.duration)
|
||||
c.analyse(tone, key, lead=0.0)
|
||||
check("a different lead is a separate entry", calls["analyse"] == 1, calls)
|
||||
next((tone_dir / "cache").glob("*-25000-400.npz")).write_bytes(b"garbage")
|
||||
reset()
|
||||
check("a damaged entry is a miss, not a failure",
|
||||
c.analyse(tone, key, lead=0.025) is not None and calls["analyse"] == 1)
|
||||
|
||||
exporter.copy_file, waveform.analyse = _real_copy, _real_analyse
|
||||
exports.delete(LIB, iset.id)
|
||||
exports.delete(LIB, mset.id)
|
||||
|
||||
print("== targets are validated and migrated ==")
|
||||
check("a set saved with the old single `target` loads as a list",
|
||||
exports._targets({"target": "onelibrary"}) == ["onelibrary"])
|
||||
check("an empty list falls back rather than yielding a set with no target",
|
||||
exports._targets({"targets": []}) == ["traktor"])
|
||||
dup = exports.create(LIB, name="Dup", targets=["traktor", "traktor"], destination=str(dest / "x"))
|
||||
check("duplicate targets collapse", dup.targets == ["traktor"], dup.targets)
|
||||
exports.delete(LIB, dup.id)
|
||||
bad = exports.create(LIB, name="Bad", targets=["traktor", "serato"], destination=str(dest / "y"))
|
||||
check("one unsupported target blocks the whole plan",
|
||||
exporter.plan(ad, bad).blocked == exporter.BLOCKED_NO_TARGET)
|
||||
exports.delete(LIB, bad.id)
|
||||
|
||||
print("== a missing file is skipped, not fatal ==")
|
||||
gone = Path(seed_items[0].destination)
|
||||
gone.unlink()
|
||||
|
||||
@@ -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 CuePoint, GridMarker, TrackCues # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
@@ -148,8 +149,13 @@ for platform, reopen in (
|
||||
print(f"-- {platform}: the prep crossed")
|
||||
for track in chosen:
|
||||
s, o = src.track_cues(track.id), back.track_cues(by_title[track.title].id)
|
||||
# Same pads, same places — to the millisecond Pioneer stores (a position
|
||||
# now crosses a 25 ms clock shift and back, so 2-dp rounding can flip).
|
||||
ho, hs = hotcues(o), hotcues(s)
|
||||
check(f"{track.title[:22]}: hot cues keep their PAD",
|
||||
hotcues(o) == hotcues(s), f"{hotcues(o)} vs {hotcues(s)}")
|
||||
[p for p, _ in ho] == [p for p, _ in hs]
|
||||
and all(abs(a - b) <= 0.011 for (_, a), (_, b) in zip(ho, hs)),
|
||||
f"{ho} vs {hs}")
|
||||
check(f"{track.title[:22]}: the grid survives expansion + collapse",
|
||||
grid(o) == grid(s), f"{grid(o)} vs {grid(s)}")
|
||||
check("the flexible grid really is multi-tempo",
|
||||
@@ -181,5 +187,431 @@ 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
|
||||
from konduktor.adapters.rekordbox import artwork as artwork_mod # 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)
|
||||
# The reader moved the fixture's positions onto the decoded clock; packing puts
|
||||
# them back on rekordbox's, so the bytes must come back unchanged.
|
||||
from konduktor.adapters.rekordbox import timebase # noqa: E402
|
||||
demo_cues = OneLibraryExporter._cue_dicts(demo_item, demo_beats, timebase.offset(demo_item.destination))
|
||||
|
||||
|
||||
def _real_cue_tags(path: Path) -> list[bytes]:
|
||||
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
|
||||
|
||||
|
||||
def _mask_colour(tag: bytes) -> bytes:
|
||||
"""A PCO2 tag with each entry's code + RGB (after its comment) zeroed."""
|
||||
if tag[:4] != b"PCO2":
|
||||
return tag
|
||||
out, off = bytearray(tag), struct.unpack(">I", tag[4:8])[0]
|
||||
while off < len(tag):
|
||||
length = struct.unpack(">I", tag[off + 8:off + 12])[0]
|
||||
at = off + 44 + struct.unpack(">I", tag[off + 40:off + 44])[0]
|
||||
out[at:at + 4] = bytes(4)
|
||||
off += length
|
||||
return bytes(out)
|
||||
|
||||
|
||||
anlz = ol_root / "PIONEER" / "USBANLZ" / "P016" / "0000875E" / "ANLZ0000"
|
||||
for suffix, extended, shape in ((".DAT", False, "hot + memory PCOB"),
|
||||
(".EXT", True, "hot + memory PCOB, hot + memory PCO2")):
|
||||
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)}")
|
||||
# Byte-identical EXCEPT the four colour bytes of each PCP2 entry. The
|
||||
# fixture's cues carry rekordbox's OLD form (code 0 + an arbitrary RGB); the
|
||||
# writer now stores a palette code, which is what rekordbox 7 draws from —
|
||||
# pinned separately below against a real rekordbox 7 palette export.
|
||||
check(f"{suffix}: every cue tag is byte-identical to rekordbox's (colour aside)",
|
||||
all(_mask_colour(r) == _mask_colour(o) for r, o in zip(real, ours)),
|
||||
[i for i, (r, o) in enumerate(zip(real, ours)) if _mask_colour(r) != _mask_colour(o)])
|
||||
check("a track with no cues still gets every list, empty",
|
||||
[t[:4] for t in W.cue_tags([], extended=True)] == [b"PCOB", b"PCOB", b"PCO2", b"PCO2"])
|
||||
check("a Traktor STEM file is an M4A to a Pioneer player",
|
||||
_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=lambda m, **_progress: seen.append(m)),
|
||||
wf_root,
|
||||
)
|
||||
dats = [p for p in wf_written.extra if p.suffix == ".DAT"]
|
||||
check("two tracks, two .DAT files", len(dats) == 2)
|
||||
check("every file written is reported, so a re-export can clear it",
|
||||
all(p.exists() for p in wf_written.all_paths)
|
||||
and {p.suffix for p in wf_written.extra} == {".DAT", ".EXT", ".2EX"})
|
||||
for dat in dats:
|
||||
check(f"{dat.parent.name}: rekordbox's tag set, in rekordbox's order",
|
||||
_tag_kinds(dat) == REKORDBOX_DAT_ORDER, _tag_kinds(dat))
|
||||
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)
|
||||
|
||||
# The drawn waveforms: rekordbox 7's song-list preview and scrolling deck read
|
||||
# the .2EX (3-band) and .EXT. Same tags, same order as rekordbox writes.
|
||||
live_dat = next(d for d in dats if (d.with_suffix(".2EX")).exists())
|
||||
check("a decodable track gets all three analysis files",
|
||||
live_dat.with_suffix(".EXT").exists() and live_dat.with_suffix(".2EX").exists())
|
||||
check(".EXT: rekordbox's tag order",
|
||||
_tag_kinds(live_dat.with_suffix(".EXT")) == [b"PPTH", b"PWV3", b"PCOB", b"PCOB", b"PCO2", b"PCO2", b"PWV5", b"PWV4"],
|
||||
_tag_kinds(live_dat.with_suffix(".EXT")))
|
||||
check(".2EX: rekordbox's tag order",
|
||||
_tag_kinds(live_dat.with_suffix(".2EX")) == [b"PPTH", b"PWV7", b"PWV6", b"PWVC"],
|
||||
_tag_kinds(live_dat.with_suffix(".2EX")))
|
||||
pwv7 = _tag(live_dat.with_suffix(".2EX"), b"PWV7")
|
||||
n7 = struct.unpack(">I", pwv7[16:20])[0]
|
||||
check("PWV7 is 150 frames a second, 3 bytes each", abs(n7 - 8 * 150) <= 2 and len(pwv7) == 24 + 3 * n7, n7)
|
||||
check("PWV6 is 1200 overview columns of 3 bytes", len(_tag(live_dat.with_suffix(".2EX"), b"PWV6")) == 20 + 3600)
|
||||
# The song list's colour overview: without it rekordbox draws the row plain blue.
|
||||
pwv4 = _tag(live_dat.with_suffix(".EXT"), b"PWV4")
|
||||
check("PWV4 is 1200 columns of 6 bytes, with rekordbox's header",
|
||||
len(pwv4) == 24 + 7200 and pwv4[12:24] == bytes.fromhex("00000006000004b000000000"), pwv4[12:24].hex())
|
||||
p4 = np.frombuffer(pwv4[24:], np.uint8).reshape(-1, 6).astype(int)
|
||||
check("its colour overview is loud where the audio is loud (height byte)",
|
||||
p4[:600, 2].mean() > p4[600:, 2].mean() + 10, (p4[:600, 2].mean(), p4[600:, 2].mean()))
|
||||
p7 = np.frombuffer(pwv7[24:], np.uint8).reshape(-1, 3).astype(int)
|
||||
check("the 3-band detail is loud where the audio is loud",
|
||||
p7[: n7 // 2].mean() > p7[n7 // 2:].mean() + 10, (p7[: n7 // 2].mean(), p7[n7 // 2:].mean()))
|
||||
dead_dat = next(d for d in dats if d != live_dat)
|
||||
check("an undecodable track still gets its .EXT cue lists, but no invented waveform",
|
||||
dead_dat.with_suffix(".EXT").exists() and not dead_dat.with_suffix(".2EX").exists()
|
||||
and b"PWV3" not in _tag_kinds(dead_dat.with_suffix(".EXT")))
|
||||
|
||||
cols = waveform.columns(live, 400)
|
||||
check("decodable audio is measured", cols is not None and abs(cols.duration - 8.0) < 0.05)
|
||||
check("a loud half measures louder than a quiet half",
|
||||
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=[], **_progress): # 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== positions cross onto rekordbox's clock (25 ms later on MP3/AAC) ==")
|
||||
# Measured: rekordbox's grids sit a median 25.0 ms later than the decoded audio
|
||||
# on 16 MP3s and 24.5 ms on 4 M4As, 0 on WAV — the codec delay it does not trim.
|
||||
# Written at the decoded time, every cue showed ~25 ms early in rekordbox.
|
||||
check("an MP3's offset is 1105 samples", abs(timebase.offset("a.mp3") - 1105 / 44100) < 1e-9)
|
||||
check("a Traktor STEM (AAC) has it too", timebase.offset("a.stem.m4a") > 0.02)
|
||||
check("a lossless file has none", timebase.offset("a.wav") == 0.0 and timebase.offset("a.flac") == 0.0)
|
||||
check("a file of unknown location has none", timebase.offset(None) == 0.0)
|
||||
probe = [CuePoint(type="cue", role="hotcue", start=30.0, length=0.0, slot=1)]
|
||||
for name, want in (("probe.mp3", 30025), ("probe.wav", 30000)):
|
||||
it = ExportTrack(track=cued, destination=Path(name), cues=TrackCues(track_id="p", cues=probe, grid_markers=[]))
|
||||
got = OneLibraryExporter._cue_dicts(it, [], timebase.offset(it.destination))[0]["time_ms"]
|
||||
check(f"a cue at 30.000 s in {name} is stored at {want} ms", got == want, got)
|
||||
check("reading it back undoes it exactly",
|
||||
abs(timebase.from_pioneer(30025 / 1000, timebase.offset("a.mp3")) - 30.0) < 0.0005)
|
||||
check("a position inside the codec delay reads as the track's start",
|
||||
timebase.from_pioneer(0.010, timebase.offset("a.mp3")) == 0.0)
|
||||
|
||||
print("\n== cue colours cross as rekordbox PALETTE CODES ==")
|
||||
# rekordbox draws a hot cue from the palette code, not the RGB: an export writing
|
||||
# code 0 had every cue drawn in rekordbox's defaults (green cues, orange loops).
|
||||
# The table was measured from a rekordbox 7 export of all 16 swatches.
|
||||
from konduktor.adapters.rekordbox import palette # noqa: E402
|
||||
|
||||
check("a measured swatch keeps its exact code and RGB",
|
||||
palette.code_for("#1AFF00") == (0x16, (0x1A, 0xFF, 0x00))
|
||||
and palette.code_for("#FF00A1") == (0x31, (0xFF, 0x00, 0xA1)))
|
||||
check("a Konduktor cue (blue) is rekordbox's light blue", palette.code_for("#4D94FF")[0] == 0x05)
|
||||
check("a Konduktor loop (green) is rekordbox's GREEN, not the nearer-hued teal",
|
||||
palette.code_for("#3DDC84")[0] == 0x16)
|
||||
check("white has no swatch: code 0, RGB kept", palette.code_for("#FFFFFF") == (0, (255, 255, 255)))
|
||||
check("no colour is code 0, black", palette.code_for(None) == (0, (0, 0, 0)))
|
||||
check("any other colour takes the nearest-hue swatch, and that swatch's RGB",
|
||||
palette.code_for("#FF8C00") == (0x26, palette.PALETTE[0x26]))
|
||||
typed = [CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0),
|
||||
CuePoint(type="loop", role="hotcue", start=2.0, length=1.0, slot=1),
|
||||
CuePoint(type="cue", role="hotcue", start=3.0, length=0.0, slot=2, color="#FFFFFF"),
|
||||
CuePoint(type="cue", role="memory", start=4.0, length=0.0, slot=None)]
|
||||
got = {c["hot_cue"]: (c["code"], c["rgb"]) for c in OneLibraryExporter._cue_dicts(
|
||||
ExportTrack(track=cued, destination=Path("t.wav"),
|
||||
cues=TrackCues(track_id="t", cues=typed, grid_markers=[])), [], 0.0)}
|
||||
check("an uncoloured Traktor cue exports blue, a loop green, the grid cue white",
|
||||
got[1][0] == 0x05 and got[2][0] == 0x16 and got[3] == (0, (255, 255, 255)), got)
|
||||
check("a memory cue stays uncoloured, as rekordbox writes it", got[0] == (0, (0, 0, 0)), got[0])
|
||||
entry = W.cue_tags([{"hot_cue": 1, "kind": 1, "time_ms": 1000, "loop_ms": None,
|
||||
"rgb": (0x1A, 0xFF, 0x00), "code": 0x16, "beats": None}], extended=True)[2]
|
||||
check("the code is packed where rekordbox 7 puts it — byte 44, before the RGB",
|
||||
entry[20 + 44:20 + 48] == bytes([0x16, 0x1A, 0xFF, 0x00]), entry[64:68].hex())
|
||||
|
||||
print("\n== artwork crosses the way rekordbox 7 writes it ==")
|
||||
# Measured on a rekordbox 7 export: PIONEER/Artwork/00001/{a,b}<n>{,_m}.jpg at
|
||||
# 80 and 240 px (a == b byte for byte), baseline JPEG q85 4:2:0, non-square art
|
||||
# letterboxed onto black, image.path -> the b file, content.image_id -> the row.
|
||||
import io # noqa: E402
|
||||
|
||||
from PIL import Image, JpegImagePlugin # noqa: E402
|
||||
|
||||
art_root = Path(tempfile.mkdtemp())
|
||||
art_audio = art_root / "Contents" / "art.wav"
|
||||
art_audio.parent.mkdir(parents=True)
|
||||
sf.write(art_audio, tone, sr)
|
||||
plain_audio = art_root / "Contents" / "plain.wav"
|
||||
sf.write(plain_audio, tone, sr)
|
||||
wide = Image.new("RGB", (400, 100), (220, 30, 30)) # a wide red banner
|
||||
png = io.BytesIO(); wide.save(png, format="PNG")
|
||||
with_art = ExportTrack(track=live_t.model_copy(update={"id": "art", "title": "art"}),
|
||||
destination=art_audio, cues=grid, art=(png.getvalue(), "image/png"))
|
||||
without = ExportTrack(track=live_t.model_copy(update={"id": "plain", "title": "plain"}),
|
||||
destination=plain_audio, cues=grid)
|
||||
art_written = core_export.for_platform("onelibrary").write(
|
||||
ExportPayload(name="ART", tracks=[with_art, without]), art_root)
|
||||
folder = art_root / "PIONEER" / "Artwork" / "00001"
|
||||
names = sorted(p.name for p in folder.iterdir()) if folder.exists() else []
|
||||
check("one image: a1, a1_m, b1, b1_m — and none for the track without art",
|
||||
names == ["a1.jpg", "a1_m.jpg", "b1.jpg", "b1_m.jpg"], names)
|
||||
check("every art file is reported, so a re-export can clear it",
|
||||
all((folder / n) in art_written.extra for n in names))
|
||||
check("the a and b copies are byte-identical, as rekordbox writes them",
|
||||
(folder / "a1.jpg").read_bytes() == (folder / "b1.jpg").read_bytes()
|
||||
and (folder / "a1_m.jpg").read_bytes() == (folder / "b1_m.jpg").read_bytes())
|
||||
small_img, medium_img = Image.open(folder / "b1.jpg"), Image.open(folder / "b1_m.jpg")
|
||||
check("80 px and 240 px", small_img.size == (80, 80) and medium_img.size == (240, 240))
|
||||
ref = io.BytesIO(); Image.new("RGB", (8, 8)).save(ref, format="JPEG", quality=85, subsampling=2)
|
||||
check("baseline JPEG, quality 85, 4:2:0 — rekordbox's own tables",
|
||||
medium_img.quantization == Image.open(ref).quantization
|
||||
and JpegImagePlugin.get_sampling(medium_img) == 2 and not medium_img.info.get("progressive"))
|
||||
px = np.asarray(medium_img.convert("RGB")).astype(int)
|
||||
check("a wide cover is letterboxed onto black, not cropped or stretched",
|
||||
px[:40].mean() < 8 and px[-40:].mean() < 8 and px[120, 120, 0] > 150,
|
||||
(px[:40].mean(), px[120, 120].tolist()))
|
||||
reopened = OneLibraryDriver().open(art_root)
|
||||
by_title_art = {t.title: t for t in reopened.tracks}
|
||||
served = reopened.cover_art(by_title_art["art"].id)
|
||||
check("Konduktor's reader serves it back (the 240 px file)",
|
||||
served is not None and served[0] == (folder / "b1_m.jpg").read_bytes())
|
||||
check("and a track without art has none", reopened.cover_art(by_title_art["plain"].id) is None)
|
||||
|
||||
print("\n== content.contentLink is what rekordbox writes ==")
|
||||
# Measured: blanking it on ONE track of a rekordbox-written stick turned that
|
||||
# row's song-list preview plain blue and put a "?" beside CUE — exactly what
|
||||
# every row of Konduktor's exports showed while it was NULL.
|
||||
import sqlcipher3.dbapi2 as _sq # noqa: E402
|
||||
from pyrekordbox.devicelib_plus.database import BLOB as _BLOB # noqa: E402
|
||||
from pyrekordbox.utils import deobfuscate as _deob # noqa: E402
|
||||
|
||||
_con = _sq.connect(str(art_written.library))
|
||||
_con.execute(f"PRAGMA key='{_deob(_BLOB)}'")
|
||||
links = {r[0] for r in _con.execute("SELECT contentLink FROM content")}
|
||||
bits = {r[0] for r in _con.execute("SELECT analysedBits FROM content")}
|
||||
_con.close()
|
||||
check("every track carries contentLink 788224, beside analysedBits 41",
|
||||
links == {788224} and bits == {41}, (links, bits))
|
||||
check("an unreadable cover costs the artwork, not the export",
|
||||
artwork_mod.pioneer_jpegs(b"not an image") is None)
|
||||
|
||||
print("\n== a Rekordbox library carries masterPlaylists6.xml, vouching for every playlist ==")
|
||||
# Measured by swapping an export into a real Rekordbox 7: without this file
|
||||
# Rekordbox opened the library, generated one listing our playlists with
|
||||
# Timestamp 0, and showed NONE of them in its sidebar.
|
||||
import xml.etree.ElementTree as ET # noqa: E402
|
||||
|
||||
rb_root = Path(tempfile.mkdtemp())
|
||||
rb_written = core_export.for_platform("rekordbox").write(build(rb_root), rb_root)
|
||||
pl_xml = rb_root / "masterPlaylists6.xml"
|
||||
check("the file is written beside master.db", pl_xml.is_file())
|
||||
check("and reported, so a re-export can clear it", pl_xml in rb_written.all_paths)
|
||||
nodes = ET.parse(pl_xml).getroot().find("PLAYLISTS").findall("NODE")
|
||||
rb_db = RekordboxDriver().open(rb_root / "master.db")
|
||||
flat = []
|
||||
|
||||
|
||||
def _walk(ns):
|
||||
for n in ns:
|
||||
flat.append(n)
|
||||
_walk(n.children)
|
||||
|
||||
|
||||
_walk(rb_db.playlist_tree())
|
||||
check("one node per playlist and folder in the database", len(nodes) == len(flat), (len(nodes), len(flat)))
|
||||
_rbc = _sq.connect(str(rb_root / "master.db"))
|
||||
from pyrekordbox.masterdb.database import BLOB as _MBLOB # noqa: E402
|
||||
_rbc.execute(f"PRAGMA key='{_deob(_MBLOB)}'")
|
||||
_links = {r[0] for r in _rbc.execute("SELECT ContentLink FROM djmdContent")}
|
||||
_rbc.close()
|
||||
check("every track carries ContentLink 0x2C060E (coloured preview, no '?')",
|
||||
_links == {2885134}, _links)
|
||||
check("every node carries a real timestamp, not 0",
|
||||
nodes and all(int(n.get("Timestamp", "0")) > 0 for n in nodes), [n.get("Timestamp") for n in nodes])
|
||||
rb_db.close()
|
||||
|
||||
print("\n== the Rekordbox target: cue colours, memory cues and artwork ==")
|
||||
rbp_root = Path(tempfile.mkdtemp())
|
||||
rbp_audio = rbp_root / "Contents" / "parity.wav"
|
||||
rbp_audio.parent.mkdir(parents=True)
|
||||
sf.write(rbp_audio, tone, sr)
|
||||
parity_cues = [
|
||||
CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0), # -> light blue
|
||||
CuePoint(type="loop", role="hotcue", start=2.0, length=0.96, slot=1), # -> green
|
||||
CuePoint(type="cue", role="hotcue", start=0.0, length=0.0, slot=2, color="#FFFFFF"), # grid cue
|
||||
CuePoint(type="cue", role="memory", start=4.0, length=0.0, slot=None),
|
||||
]
|
||||
parity = ExportTrack(track=live_t.model_copy(update={"id": "parity", "title": "parity"}),
|
||||
destination=rbp_audio, art=(png.getvalue(), "image/png"),
|
||||
cues=TrackCues(track_id="parity", cues=parity_cues,
|
||||
grid_markers=[GridMarker(start=0.0, bpm=125.0)]))
|
||||
rbp_written = core_export.for_platform("rekordbox").write(ExportPayload(name="PARITY", tracks=[parity]), rbp_root)
|
||||
|
||||
_c = _sq.connect(str(rbp_root / "master.db"))
|
||||
_c.execute(f"PRAGMA key='{_deob(_MBLOB)}'")
|
||||
cue_rows = _c.execute("SELECT Kind, ColorTableIndex, Color, InMsec FROM djmdCue ORDER BY InMsec").fetchall()
|
||||
mirror = _c.execute("SELECT Cues FROM contentCue").fetchone()
|
||||
image_path = _c.execute("SELECT ImagePath FROM djmdContent").fetchone()[0]
|
||||
_c.close()
|
||||
by_kind = {k: (cti, col) for k, cti, col, _ms in cue_rows}
|
||||
check("four cue rows: three hot cues and a memory cue (Kind 0)",
|
||||
sorted(k for k, *_ in cue_rows) == [0, 1, 2, 3], cue_rows)
|
||||
check("a plain cue is rekordbox's light blue (code 5)", by_kind.get(1) == (0x05, -1), by_kind.get(1))
|
||||
check("a loop is rekordbox's green (code 22)", by_kind.get(2) == (0x16, -1), by_kind.get(2))
|
||||
check("the white grid cue has no swatch, so stays uncoloured", by_kind.get(3) == (None, -1), by_kind.get(3))
|
||||
check("the memory cue is written, uncoloured", by_kind.get(0) == (None, -1), by_kind.get(0))
|
||||
check("the contentCue mirror holds all four, colours included",
|
||||
mirror is not None and mirror[0].count('"Kind"') == 4 and '"ColorTableIndex": 22' in mirror[0].replace(":22", ": 22"),
|
||||
mirror and mirror[0][:200])
|
||||
|
||||
art_dir = rbp_root / "share" / image_path.lstrip("/").rsplit("/", 1)[0] if image_path else None
|
||||
check("ImagePath names artwork.jpg under the track's UUID folder",
|
||||
bool(image_path) and image_path.startswith("/PIONEER/Artwork/") and image_path.endswith("/artwork.jpg"), image_path)
|
||||
sizes = {p.name: Image.open(p).size for p in art_dir.iterdir()} if art_dir and art_dir.exists() else {}
|
||||
check("three JPEGs: the cover fit to 800 px (aspect kept), 240 and 80 px squares",
|
||||
sizes == {"artwork.jpg": (400, 100), "artwork_m.jpg": (240, 240), "artwork_s.jpg": (80, 80)}, sizes)
|
||||
check("every art file is reported, so a re-export can clear it",
|
||||
art_dir is not None and all(p in rbp_written.extra for p in art_dir.iterdir()))
|
||||
rb_back = RekordboxDriver().open(rbp_root / "master.db")
|
||||
t_back = rb_back.tracks[0]
|
||||
served = rb_back.cover_art(t_back.id)
|
||||
check("Konduktor's Rekordbox reader serves the cover back",
|
||||
served is not None and served[0] == (art_dir / "artwork.jpg").read_bytes())
|
||||
memory_back = [c for c in rb_back.track_cues(t_back.id).cues if c.role == "memory"]
|
||||
check("and reads the memory cue back, at its place",
|
||||
len(memory_back) == 1 and abs(memory_back[0].start - 4.0) < 0.002, memory_back)
|
||||
rb_back.close()
|
||||
|
||||
print("\n== overview columns sit where their audio is (no drift) ==")
|
||||
# np.array_split gives the FIRST n % k chunks an extra frame, so every early
|
||||
# overview column held later audio than its position: ~1 bar early mid-track in
|
||||
# rekordbox, right again near the end. A burst at a known time, with a frame
|
||||
# count whose remainder is large (24,420 % 1200 = 420), must land in its column.
|
||||
from konduktor.core.waveform import even_slices # noqa: E402
|
||||
|
||||
n_frames = 24420
|
||||
check("even_slices covers every frame once, in order",
|
||||
[x.start for x in even_slices(n_frames, 1200)][1:] == [x.stop for x in even_slices(n_frames, 1200)][:-1]
|
||||
and even_slices(n_frames, 1200)[-1].stop == n_frames)
|
||||
for when in (0.35, 0.5, 0.9):
|
||||
burst = np.full((n_frames, 3), 1.0)
|
||||
at = int(when * n_frames)
|
||||
burst[at:at + 40] = 100.0
|
||||
ext_t, two_t = W.waveform_tags(burst)
|
||||
tags_t = {x[:4]: x for x in ext_t + two_t}
|
||||
col6 = int(np.argmax(np.frombuffer(tags_t[b"PWV6"][20:], np.uint8).reshape(-1, 3)[:, 0]))
|
||||
col4 = int(np.argmax(np.frombuffer(tags_t[b"PWV4"][24:], np.uint8).reshape(-1, 6)[:, 3]))
|
||||
want = at * 1200 / n_frames
|
||||
check(f"a burst {int(when * 100)}% in lands in its overview column (PWV6 {col6}, PWV4 {col4}, want ~{want:.0f})",
|
||||
abs(col6 - want) <= 2 and abs(col4 - want) <= 2)
|
||||
|
||||
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -61,7 +61,7 @@ playlist_tracks = adapter.playlist_entries(playlist.id) or []
|
||||
all_tracks = [t.id for t in adapter.tracks]
|
||||
|
||||
print("== creating, listing, updating, deleting ==")
|
||||
s1 = exports.create(LIB, name="GIG", target="traktor", destination=str(work / "out"))
|
||||
s1 = exports.create(LIB, name="GIG", targets=["traktor"], destination=str(work / "out"))
|
||||
check("a set is created with an id", bool(s1.id))
|
||||
check("it lists", [s.id for s in exports.all_sets(LIB)] == [s1.id])
|
||||
check("it survives a reload from disk", exports.get(LIB, s1.id).name == "GIG")
|
||||
@@ -128,7 +128,7 @@ check("and is NOT counted as exportable",
|
||||
"Macintosh HD/:nowhere/:ghost.mp3" not in gone.track_ids)
|
||||
exports.remove(LIB, s1.id, track_ids=["Macintosh HD/:nowhere/:ghost.mp3"])
|
||||
|
||||
s2 = exports.create(LIB, name="Deleted playlist test", target="traktor",
|
||||
s2 = exports.create(LIB, name="Deleted playlist test", targets=["traktor"],
|
||||
destination=str(work / "out2"))
|
||||
exports.add(LIB, s2.id, playlist_ids=["no-such-playlist"])
|
||||
ghost = exports.resolve(adapter, exports.get(LIB, s2.id))
|
||||
@@ -141,7 +141,7 @@ print("== two sets, one destination ==")
|
||||
# Caught when the destination is chosen, not when it is too late to warn.
|
||||
check("no conflict for distinct destinations",
|
||||
exports.destination_conflict(LIB, str(work / "out"), ignore=s1.id) is None)
|
||||
s3 = exports.create(LIB, name="Clash", target="traktor", destination=str(work / "out"))
|
||||
s3 = exports.create(LIB, name="Clash", targets=["traktor"], destination=str(work / "out"))
|
||||
check("a clash is reported by NAME",
|
||||
exports.destination_conflict(LIB, str(work / "out"), ignore=s3.id) == "Ibiza")
|
||||
check("a set never conflicts with itself",
|
||||
@@ -189,7 +189,7 @@ import konduktor.main as main # noqa: E402
|
||||
ad, lib = STATE.adapter, STATE.library_id
|
||||
prefix = ad.path_prefix_suggestions()["primary"]
|
||||
loose = next(t.id for t in ad.tracks if str(ad.audio_path(t.id) or "").startswith(prefix))
|
||||
s3 = exports.create(lib, name="Remapped", target="traktor", destination=str(work / "remapped"))
|
||||
s3 = exports.create(lib, name="Remapped", targets=["traktor"], destination=str(work / "remapped"))
|
||||
exports.add(lib, s3.id, track_ids=[loose])
|
||||
r = TestClient(main.app, raise_server_exceptions=False).post(
|
||||
"/api/library/remap-paths", json={"from": prefix, "to": "/Volumes/KonduktorTest"}
|
||||
|
||||
+45
-1
@@ -158,7 +158,7 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
|
||||
print("== a held file is never added twice, but still reaches its target ==")
|
||||
library = STATE.library_id
|
||||
eset = exports.create(library, name="Folder Export", target="traktor",
|
||||
eset = exports.create(library, name="Folder Export", targets=["traktor"],
|
||||
destination=str(Path(tempfile.mkdtemp()) / "out"))
|
||||
req = {"track_ids": [str(one), str(two)], "mode": "reference",
|
||||
"playlist_id": playlist, "export_id": eset.id}
|
||||
@@ -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"))
|
||||
|
||||
@@ -193,11 +193,52 @@ with tempfile.TemporaryDirectory() as d:
|
||||
other = Path(d) / "other.nml"
|
||||
shutil.copy2(REAL, other)
|
||||
c.post("/api/library/open", json={"path": str(other)})
|
||||
check("opening another library has STOPPED the run by the time it returns",
|
||||
main.JOBS.get(jid).finished and main.JOBS.get(jid).state == "cancelled",
|
||||
main.JOBS.get(jid).state)
|
||||
check("opening another library cancels the run", wait(c, jid)["state"] == "cancelled")
|
||||
|
||||
# Exclusive submit is checked and registered under one lock: a second
|
||||
# batch cannot start while one runs, however the requests interleave.
|
||||
from konduktor.jobs import JobBusy
|
||||
import threading as _th
|
||||
gate = _th.Event()
|
||||
first = main.JOBS.submit(main.GRID_JOB, lambda h: gate.wait(5), exclusive_with=main.BATCH_JOBS)
|
||||
try:
|
||||
main.JOBS.submit(main.CUE_JOB, lambda h: None, exclusive_with=main.BATCH_JOBS)
|
||||
check("a second batch kind is refused while one runs", False, "it started")
|
||||
except JobBusy:
|
||||
check("a second batch kind is refused while one runs", True)
|
||||
check("wait() times out on a running job", main.JOBS.wait(first.id, timeout=0.05) is False)
|
||||
gate.set()
|
||||
check("…and returns once it has finished", main.JOBS.wait(first.id, timeout=5) is True)
|
||||
|
||||
# Within-item progress: what lets the overall bar move inside a long
|
||||
# track (99 % of the first of two = ~50 %), and it starts over per item.
|
||||
from konduktor.jobs import Job, JobHandle
|
||||
j = Job(id="x", kind="t")
|
||||
h = JobHandle(j)
|
||||
h.progress(done=0, total=2, fraction=0.99, status="separating 99 %")
|
||||
d = j.as_dict()
|
||||
check("a job reports its current item's fraction and status",
|
||||
d["fraction"] == 0.99 and d["status"] == "separating 99 %", str(d))
|
||||
h.progress(done=1)
|
||||
check("…both reset when the next item starts", j.fraction == 0.0 and j.status == "")
|
||||
h.progress(fraction=1.7)
|
||||
check("…and the fraction is clamped to 0..1", j.fraction == 1.0)
|
||||
from konduktor.schemas import JobStatus
|
||||
r = JobStatus(**j.as_dict()).model_dump()
|
||||
check("the job's response model carries fraction and status (not silently dropped)",
|
||||
r["fraction"] == 1.0 and "status" in r, str(r)[:200])
|
||||
|
||||
check("nothing was written to disk (edits stay in memory until Save)",
|
||||
work.read_bytes() == REAL.read_bytes())
|
||||
|
||||
# The status bar tells a byte count from a track count by `unit`; the
|
||||
# response model once dropped it on every job route.
|
||||
jid = main.JOBS.submit("unit-probe", lambda h: h.progress(done=1, total=2, unit="bytes")).id
|
||||
check("a job's unit reaches the client", wait(c, jid).get("unit") == "bytes")
|
||||
|
||||
print()
|
||||
print("FAILED" if failed else "RESULT: ALL PASSED")
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -28,6 +28,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-ol-appdata
|
||||
from konduktor.adapters.onelibrary import discovery # noqa: E402
|
||||
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
|
||||
from konduktor.adapters.onelibrary.beatgrid import markers_from_beats # noqa: E402
|
||||
from konduktor.adapters.rekordbox import timebase # noqa: E402
|
||||
from konduktor.adapters.onelibrary.cues import ( # noqa: E402
|
||||
MEMORY_SLOT,
|
||||
NO_LOOP,
|
||||
@@ -235,7 +236,12 @@ markers = cues.grid_markers
|
||||
check("a flexible grid stays flexible", len(markers) == 2, str(len(markers)))
|
||||
check("the first segment is 128 BPM", markers[0].bpm == 128.0)
|
||||
check("the second segment is 90 BPM", markers[1].bpm == 90.0)
|
||||
check("and it starts at 60 s", abs(markers[1].start - 60.0) < 0.001, str(markers[1].start))
|
||||
# Stored positions are on rekordbox's clock, 1105 samples behind the decoded
|
||||
# audio on an MP3 (`timebase`); the generic model reports the decoded time.
|
||||
OFF = timebase.offset("x.mp3")
|
||||
check("the reader converts rekordbox's clock to the decoded audio's (~25 ms on MP3)",
|
||||
abs(OFF - 1105 / 44100) < 1e-9, OFF)
|
||||
check("and it starts at 60 s", abs(markers[1].start - (60.0 - OFF)) < 0.001, str(markers[1].start))
|
||||
check("markers are ordered by position", [m.start for m in markers] == sorted(m.start for m in markers))
|
||||
|
||||
print("== cues, cross-checked against the same cues in master.db ==")
|
||||
@@ -246,20 +252,20 @@ print("== cues, cross-checked against the same cues in master.db ==")
|
||||
hot = {c.slot: c for c in cues.cues if c.role == "hotcue"}
|
||||
check("four hot cues, on pads A-D", sorted(hot) == [0, 1, 2, 3], str(sorted(hot)))
|
||||
check("pad A is the loop at 40.000 s",
|
||||
hot[0].type == "loop" and abs(hot[0].start - 40.0) < 0.001)
|
||||
hot[0].type == "loop" and abs(hot[0].start - (40.0 - OFF)) < 0.001)
|
||||
check("pad A's loop is 4 beats at 128 BPM = 1.875 s", abs(hot[0].length - 1.875) < 0.001)
|
||||
check("pad B is at 18.775 s", abs(hot[1].start - 18.775) < 0.001, str(hot[1].start))
|
||||
check("pad C is at 90.667 s", abs(hot[2].start - 90.667) < 0.001, str(hot[2].start))
|
||||
check("pad B is at 18.775 s", abs(hot[1].start - (18.775 - OFF)) < 0.001, str(hot[1].start))
|
||||
check("pad C is at 90.667 s", abs(hot[2].start - (90.667 - OFF)) < 0.001, str(hot[2].start))
|
||||
# Pad D exists ONLY in the .EXT. A reader that stopped at the .DAT would lose it,
|
||||
# and would do so silently.
|
||||
check("pad D is at 120.000 s — the cue that lives only in the .EXT",
|
||||
abs(hot[3].start - 120.0) < 0.001, str(hot[3].start))
|
||||
abs(hot[3].start - (120.0 - OFF)) < 0.001, str(hot[3].start))
|
||||
check("hot cues carry their RGB colour", all(c.color and c.color.startswith("#") for c in hot.values()))
|
||||
|
||||
memory = [c for c in cues.cues if c.role == "memory"]
|
||||
check("the memory cue is preserved", len(memory) == 1)
|
||||
check("it has no slot", memory[0].slot is None)
|
||||
check("it is the same loop, at the same place", abs(memory[0].start - 40.0) < 0.001)
|
||||
check("it is the same loop, at the same place", abs(memory[0].start - (40.0 - OFF)) < 0.001)
|
||||
check("no cue on a read-only drive is editable", all(not c.editable for c in cues.cues))
|
||||
|
||||
print("== playlists ==")
|
||||
@@ -314,6 +320,7 @@ COMMANDS = [
|
||||
("set_playlist_entries", lambda: adapter.set_playlist_entries(node.id, [])),
|
||||
("set_cue", lambda: adapter.set_cue(one.id, slot=0, start_sec=1.0, cue_type="cue")),
|
||||
("set_cue_type", lambda: adapter.set_cue_type(one.id, 0, "loop")),
|
||||
("set_cue_color", lambda: adapter.set_cue_color(one.id, 0, "#FF0000")),
|
||||
("delete_cue", lambda: adapter.delete_cue(one.id, 0)),
|
||||
("place_cues", lambda: adapter.place_cues(one.id, [])),
|
||||
("add_grid_marker", lambda: adapter.add_grid_marker(one.id, 1.0)),
|
||||
|
||||
@@ -14,6 +14,7 @@ import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from types import SimpleNamespace
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
@@ -31,6 +32,7 @@ from konduktor.adapters.rekordbox.cue_types import ( # noqa: E402
|
||||
kind_for,
|
||||
role_and_slot,
|
||||
)
|
||||
from konduktor.adapters.rekordbox import palette # noqa: E402
|
||||
from konduktor.adapters.rekordbox.driver import RekordboxDriver # noqa: E402
|
||||
from konduktor.adapters.rekordbox.projection import parse_key # noqa: E402
|
||||
from konduktor.core import registry # noqa: E402
|
||||
@@ -88,6 +90,21 @@ check("pad H is Kind 9", kind_for("hotcue", 7) == 9)
|
||||
check("BeatLoopSize encodes (beats << 16) | 1", beat_loop_size(4) == 262145 and beat_loop_size(1) == 65537)
|
||||
check("and decodes back", beats_in_loop(262145) == 4 and beats_in_loop(None) is None)
|
||||
|
||||
print("== hot cue colour palette ==")
|
||||
# rekordbox has 16; the teal-green between 0x0E and 0x16 was never measured, and
|
||||
# is left out rather than offered with a guessed RGB.
|
||||
check("15 pickable swatches, without the observed-only red",
|
||||
len(palette.SWATCHES) == 15 and 0x2B not in palette.SWATCHES)
|
||||
check("a code projects as its measured RGB", palette.hex_for(0x16) == "#1AFF00")
|
||||
check("uncoloured (None, or a loop's 0) projects as no colour",
|
||||
palette.hex_for(None) is None and palette.hex_for(0) is None)
|
||||
# The unmeasured teal-green is probably 0x12: claim nothing rather than guess.
|
||||
check("an unknown code projects as no colour", palette.hex_for(0x12) is None)
|
||||
check("a swatch maps back to its code, case-insensitively",
|
||||
all(palette.swatch_code(palette.hex_for(c).lower()) == c for c in palette.SWATCHES))
|
||||
# A user's pick must BE a swatch; nearest-hue is the exporter's rule, not an edit's.
|
||||
check("a non-palette colour is not a swatch", palette.swatch_code("#123456") is None)
|
||||
|
||||
print("== key parsing (Rekordbox names keys musically, not in Camelot) ==")
|
||||
check("Fm -> 4A", parse_key("Fm") == (4, "minor"))
|
||||
check("Am -> 8A", parse_key("Am") == (8, "minor"))
|
||||
@@ -115,6 +132,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:
|
||||
@@ -282,6 +320,9 @@ with tempfile.TemporaryDirectory() as d:
|
||||
# library, and the opposite of what the original plan assumed.
|
||||
check("a loop is a cue type, not a separate bank", caps.cues.loops == "cue_type")
|
||||
check("cue colour is a palette, not free RGB", caps.cues.color == "palette")
|
||||
check("and the palette is the measured swatches",
|
||||
caps.cues.palette == [palette.hex_for(c) for c in palette.SWATCHES],
|
||||
str(caps.cues.palette))
|
||||
check("the editable field set is advertised", bool(caps.tracks.editable_fields))
|
||||
# Rekordbox has no column for these; Traktor does. Mapping them onto its
|
||||
# Composer field would silently write the wrong thing.
|
||||
@@ -296,9 +337,6 @@ with tempfile.TemporaryDirectory() as d:
|
||||
print("== what Rekordbox genuinely cannot do still refuses, with a reason ==")
|
||||
commands = {
|
||||
"set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"),
|
||||
# A track spans rows in several tables plus ANLZ files; which of them
|
||||
# Rekordbox expects deleted together is unmeasured.
|
||||
"remove_tracks": lambda: adapter.remove_tracks([sample.id]),
|
||||
# Rekordbox genuinely has no per-track grid lock, unlike Traktor's LOCK.
|
||||
"set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True),
|
||||
"remap_locations": lambda: adapter.remap_locations(None),
|
||||
@@ -407,6 +445,71 @@ with tempfile.TemporaryDirectory() as d:
|
||||
_raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=-1.0,
|
||||
cue_type="cue"), InvalidCommand))
|
||||
|
||||
print("== hot cue colours ==")
|
||||
# Slot 0 holds a point cue at 1.0 s; put a loop in slot 7.
|
||||
adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, cue_type="loop", length_sec=1.92)
|
||||
red, green = palette.hex_for(0x2A), palette.hex_for(0x16)
|
||||
|
||||
def slot_cue(tc, slot):
|
||||
return next((c for c in tc.cues if c.slot == slot), None)
|
||||
|
||||
def mirror_of(slot):
|
||||
import json
|
||||
store = adapter._store
|
||||
t = store._tables
|
||||
row = store._db.session.query(t.ContentCue).filter(
|
||||
t.ContentCue.ContentID == str(cue_track.id)).first()
|
||||
kind = kind_for("hotcue", slot)
|
||||
return next((r for r in json.loads(row.Cues) if r.get("Kind") == kind), None)
|
||||
|
||||
before = slot_cue(adapter.track_cues(cue_track.id), 0)
|
||||
tc = adapter.set_cue_color(cue_track.id, 0, red.lower())
|
||||
c0 = slot_cue(tc, 0)
|
||||
check("a cue takes a palette colour", c0 is not None and c0.color == red, str(c0 and c0.color))
|
||||
check("recolouring does not move it", c0 is not None and before is not None
|
||||
and c0.start == before.start, f"{before and before.start} -> {c0 and c0.start}")
|
||||
raw = adapter._store._cue_row(cue_track.id, 0)
|
||||
check("stored as the palette code with Color -1",
|
||||
raw.ColorTableIndex == 0x2A and raw.Color == -1, f"{raw.ColorTableIndex}/{raw.Color}")
|
||||
m = mirror_of(0)
|
||||
check("the contentCue mirror carries the colour",
|
||||
m is not None and m.get("ColorTableIndex") == 0x2A and m.get("Color") == -1, str(m))
|
||||
chip = next((h for h in adapter.track(cue_track.id).hotcues if h.slot == 0), None)
|
||||
check("the table's hotcue dot shows it", chip is not None and chip.color == red,
|
||||
str(chip))
|
||||
# The colour belongs to the PAD: a rename, a move or a type change keeps it.
|
||||
tc = adapter.set_cue(cue_track.id, slot=0, start_sec=3.0, cue_type="cue", name="Renamed")
|
||||
check("re-setting the slot keeps its colour", slot_cue(tc, 0).color == red,
|
||||
str(slot_cue(tc, 0).color))
|
||||
tc = adapter.set_cue_color(cue_track.id, 7, green)
|
||||
check("a loop takes a colour too", slot_cue(tc, 7).color == green)
|
||||
raw = adapter._store._cue_row(cue_track.id, 7)
|
||||
check("a coloured loop stores the code, not the loop's 255/0",
|
||||
raw.ColorTableIndex == 0x16 and raw.Color == -1, f"{raw.ColorTableIndex}/{raw.Color}")
|
||||
tc = adapter.set_cue_type(cue_track.id, 7, "cue")
|
||||
check("a type change keeps the colour", slot_cue(tc, 7).color == green)
|
||||
tc = adapter.place_cues(cue_track.id, [SimpleNamespace(slot=7, start=70.0, type="cue",
|
||||
length=0.0, name="Drop")],
|
||||
overwrite=True)
|
||||
check("an Auto Hotcues Replace keeps the slot's colour", slot_cue(tc, 7).color == green)
|
||||
tc = adapter.set_cue_color(cue_track.id, 0, None)
|
||||
raw = adapter._store._cue_row(cue_track.id, 0)
|
||||
check("Default makes it uncoloured again",
|
||||
slot_cue(tc, 0).color is None and raw.ColorTableIndex is None and raw.Color == -1,
|
||||
f"{raw.ColorTableIndex}/{raw.Color}")
|
||||
adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, cue_type="loop", length_sec=1.92)
|
||||
adapter.set_cue_color(cue_track.id, 7, None)
|
||||
raw = adapter._store._cue_row(cue_track.id, 7)
|
||||
check("an uncoloured loop is back to Rekordbox's own 255/0",
|
||||
raw.ColorTableIndex == 0 and raw.Color == 255, f"{raw.ColorTableIndex}/{raw.Color}")
|
||||
adapter.delete_cue(cue_track.id, 0)
|
||||
tc = adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, cue_type="cue")
|
||||
check("a new cue in an emptied slot starts uncoloured", slot_cue(tc, 0).color is None)
|
||||
check("a colour outside the palette is refused",
|
||||
_raises(lambda: adapter.set_cue_color(cue_track.id, 0, "#123456"), InvalidCommand))
|
||||
check("recolouring an empty slot is NotFound",
|
||||
_raises(lambda: adapter.set_cue_color(cue_track.id, 6, red), NotFound))
|
||||
|
||||
print("== beatgrid edits ==")
|
||||
grid_track = next((t for t in adapter.tracks if t.bpm), None)
|
||||
if grid_track:
|
||||
|
||||
@@ -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])
|
||||
@@ -288,9 +334,16 @@ with tempfile.TemporaryDirectory() as d:
|
||||
row = cue_rows[0][3]
|
||||
check("the 0-based slot is stored as its measured Kind",
|
||||
row["Kind"] == 7, str(row["Kind"]))
|
||||
check("positions are stored in ms AND frames at 150fps",
|
||||
row["InMsec"] == 30000 and row["InFrame"] == 4500,
|
||||
f"{row['InMsec']}/{row['InFrame']}")
|
||||
# On rekordbox's clock: 30.000 s of DECODED audio is stored 1105 samples
|
||||
# later on an MP3/AAC (`timebase`), and exactly at 30.000 s lossless.
|
||||
from konduktor.adapters.rekordbox import timebase
|
||||
want_ms = int(round((30.0 + adapter._store.time_offset(cue_track.id)) * 1000))
|
||||
check("positions are stored in ms AND frames at 150fps, on rekordbox's clock",
|
||||
row["InMsec"] == want_ms and row["InFrame"] == int(want_ms * 150 / 1000),
|
||||
f"{row['InMsec']}/{row['InFrame']} (want {want_ms})")
|
||||
check("and read back at exactly the position that was set",
|
||||
abs(next(c.start for c in adapter.track_cues(cue_track.id).cues if c.slot == 5)
|
||||
- 30.0) < 0.0005)
|
||||
check("a non-loop has no out-point", row["OutMsec"] == -1, str(row["OutMsec"]))
|
||||
check("an uncoloured cue matches Rekordbox's own convention",
|
||||
row["Color"] == -1 and row["ColorTableIndex"] is None,
|
||||
@@ -411,5 +464,277 @@ with tempfile.TemporaryDirectory() as d:
|
||||
str(fields.get("BPM")))
|
||||
adapter.close()
|
||||
|
||||
# ---- I: removing a track does what Rekordbox 7 itself does -----------
|
||||
# Measured 2026-10-01 by removing a track in Rekordbox and diffing: its
|
||||
# rows are DELETED (not flagged) from djmdContent, djmdCue, contentCue,
|
||||
# contentFile, djmdMixerParam and djmdSongPlaylist, the playlist row is
|
||||
# left alone, and the files contentFile lists go with their folders.
|
||||
print("== I: removing a track deletes exactly what Rekordbox deletes ==")
|
||||
from konduktor.core.adapter import Unsupported # noqa: E402
|
||||
|
||||
clean_copy(REAL, work)
|
||||
before = dump(work)
|
||||
measured = ("djmdCue", "contentCue", "contentFile", "djmdMixerParam", "djmdSongPlaylist")
|
||||
sampler = {str(r["ContentID"]) for r in before.get("djmdSongSampler", {}).values()}
|
||||
songs = before["djmdSongPlaylist"].values()
|
||||
# The FIRST entry of the longest playlist, so the entries after it must
|
||||
# be renumbered.
|
||||
by_list: dict[str, list] = {}
|
||||
for r in songs:
|
||||
by_list.setdefault(str(r["PlaylistID"]), []).append(r)
|
||||
longest = max(by_list.values(), key=len, default=[])
|
||||
first = min(longest, key=lambda r: r["TrackNo"]) if len(longest) > 1 else None
|
||||
if first is None or str(first["ContentID"]) in sampler:
|
||||
print(" (skipped: no playlist with two entries to remove from)")
|
||||
else:
|
||||
victim = str(first["ContentID"])
|
||||
playlist_id = str(first["PlaylistID"])
|
||||
listed = [r["Path"] for r in before["contentFile"].values()
|
||||
if str(r["ContentID"]) == victim]
|
||||
files = [p for p in listed if p.startswith("/PIONEER/USBANLZ/")]
|
||||
art = [p for p in listed if p.startswith("/PIONEER/Artwork/")]
|
||||
adapter = RekordboxAdapter(work)
|
||||
n_tracks = len(adapter.tracks)
|
||||
check("remove_tracks reports one track removed", adapter.remove_tracks([victim]) == 1)
|
||||
check("it leaves the projection at once",
|
||||
adapter.track(victim) is None and len(adapter.tracks) == n_tracks - 1)
|
||||
check("and its playlist", victim not in adapter.playlist_entries(playlist_id))
|
||||
check("the adapter is dirty", adapter.dirty is True)
|
||||
check("nothing is on disk before save", not diff(before, dump(work)))
|
||||
check("its analysis files are still there before save",
|
||||
all((Path(d) / "share" / p.lstrip("/")).is_file() for p in files))
|
||||
adapter.save()
|
||||
|
||||
changes = diff(before, dump(work))
|
||||
expected_deletes = {("djmdContent", victim)} | {
|
||||
(t, pk) for t in measured for pk, r in before[t].items()
|
||||
if str(r.get("ContentID")) == victim
|
||||
}
|
||||
deletes = {(t, pk) for t, pk, kind, _ in changes if kind == "DELETE"}
|
||||
check("exactly the measured rows are deleted", deletes == expected_deletes,
|
||||
f"extra {sorted(deletes - expected_deletes)} missing "
|
||||
f"{sorted(expected_deletes - deletes)}")
|
||||
check("nothing is inserted", not [c for c in changes if c[2] == "INSERT"])
|
||||
updates = {(t, pk): f for t, pk, kind, f in changes if kind == "UPDATE"}
|
||||
later = {pk for pk, r in before["djmdSongPlaylist"].items()
|
||||
if str(r["PlaylistID"]) == playlist_id and r["TrackNo"] > first["TrackNo"]}
|
||||
check("only the counter and the later entries' TrackNo move",
|
||||
set(updates) == {("agentRegistry", "localUpdateCount")}
|
||||
| {("djmdSongPlaylist", pk) for pk in later}, describe(changes))
|
||||
check("each later entry moves up by one",
|
||||
all(updates[("djmdSongPlaylist", pk)]["TrackNo"][1]
|
||||
== before["djmdSongPlaylist"][pk]["TrackNo"] - 1 for pk in later))
|
||||
check("the playlist row itself is left alone",
|
||||
("djmdPlaylist", playlist_id) not in updates)
|
||||
check("the track's analysis files are deleted",
|
||||
not any((Path(d) / "share" / p.lstrip("/")).exists() for p in files), str(files))
|
||||
check("and their emptied folder",
|
||||
not any((Path(d) / "share" / p.lstrip("/")).parent.exists() for p in files))
|
||||
# Unmeasured (the measured track had none), so left in place.
|
||||
check("its artwork is left alone",
|
||||
all((Path(d) / "share" / p.lstrip("/")).is_file() for p in art))
|
||||
check("the analysis root is kept",
|
||||
(Path(d) / "share" / "PIONEER" / "USBANLZ").is_dir())
|
||||
adapter.close()
|
||||
reopened = RekordboxAdapter(work)
|
||||
check("the track is gone after a reopen", reopened.track(victim) is None)
|
||||
reopened.close()
|
||||
|
||||
# A table that was EMPTY in the measured library is not guessed at.
|
||||
if sampler:
|
||||
clean_copy(REAL, work)
|
||||
adapter = RekordboxAdapter(work)
|
||||
target = next(iter(sampler))
|
||||
try:
|
||||
adapter.remove_tracks([adapter.tracks[0].id, target])
|
||||
check("a track in the Sampler is refused", False)
|
||||
except Unsupported as ex:
|
||||
check("a track in the Sampler is refused", "Sampler" in str(ex), str(ex))
|
||||
check("and the whole batch changed nothing",
|
||||
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)
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Auto path remapping: the open-time missing-files check.
|
||||
|
||||
Two layers. `core.relocate.search` on temp folders, where where-the-files-are is
|
||||
known; then the Traktor path end to end through the routes, on a collection
|
||||
built here whose stored volume is a Windows drive letter — the real case that
|
||||
motivated this (a collection made on Windows with the SSD as `X:`, opened on a
|
||||
Mac where it is `/Volumes/<name>`).
|
||||
|
||||
Pins the things that would fail SILENTLY:
|
||||
|
||||
* a drive and its clone are AMBIGUOUS, never ranked — a wrong guess would play
|
||||
and tag files on the wrong drive;
|
||||
* a filename alone at a drive's root is not a match;
|
||||
* a volume in which even ONE track resolves is never asked about;
|
||||
* nothing is applied before the user answers, and only a proposed mapping is;
|
||||
* the answer is session-only: the collection and prefs are untouched, and a
|
||||
reopen asks again;
|
||||
* a saved manual mapping is respected — its volume is not asked about.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
_DATA = tempfile.TemporaryDirectory()
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = _DATA.name
|
||||
os.environ.pop("KONDUKTOR_NML", None)
|
||||
|
||||
from konduktor.core.pathmap import PathMapping # noqa: E402
|
||||
from konduktor.core.relocate import PathGroup, search # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
def touch(path: Path) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"")
|
||||
return path
|
||||
|
||||
|
||||
tmp = Path(tempfile.mkdtemp())
|
||||
ssd = tmp / "SSD"
|
||||
rel = [f"Music Library/{g}/t{i}.mp3" for g in ("EDM", "House", "DnB") for i in range(20)]
|
||||
for r in rel:
|
||||
touch(ssd / r)
|
||||
(ssd / rel[7]).unlink() # one track genuinely deleted
|
||||
stored = [f"X:/{r}" for r in rel]
|
||||
x = PathGroup(label="X:", root="X:", paths=stored)
|
||||
|
||||
print("== a changed drive letter is found ==")
|
||||
[p] = search([x], [ssd, tmp / "Nowhere"])
|
||||
check("found, with one candidate", p.status == "found", p.status)
|
||||
c = p.candidates[0]
|
||||
check("maps the drive letter onto the drive", c.mapping == PathMapping.make("X:", str(ssd)), str(c.mapping))
|
||||
check("the count is verified over the WHOLE group", c.found == 59 and p.total == 60, f"{c.found}/{p.total}")
|
||||
|
||||
print("== a drive and its clone are ambiguous ==")
|
||||
clone = tmp / "Clone"
|
||||
shutil.copytree(ssd, clone)
|
||||
[p] = search([x], [ssd, clone])
|
||||
check("ambiguous, both offered", p.status == "ambiguous" and len(p.candidates) == 2, p.status)
|
||||
check("both targets named", {c.mapping.to_prefix for c in p.candidates} == {str(ssd), str(clone)})
|
||||
|
||||
print("== a partial copy loses to the whole one ==")
|
||||
partial = tmp / "Partial"
|
||||
for r in rel[:8]:
|
||||
touch(partial / r)
|
||||
[p] = search([x], [ssd, partial])
|
||||
check("found on the full drive only",
|
||||
p.status == "found" and p.candidates[0].mapping.to_prefix == str(ssd), p.status)
|
||||
|
||||
print("== nothing found ==")
|
||||
[p] = search([PathGroup("E:", "E:", ["E:/Gone/a.mp3", "E:/Gone/b.mp3"])], [ssd])
|
||||
check("not found, no candidates", p.status == "not_found" and not p.candidates)
|
||||
|
||||
print("== a filename alone at a drive's root is not a match ==")
|
||||
bare = tmp / "Bare"
|
||||
for i in range(5):
|
||||
touch(bare / f"solo{i}.mp3")
|
||||
[p] = search([PathGroup("X:", "X:", [f"X:/Deep/Folder/solo{i}.mp3" for i in range(5)])], [bare])
|
||||
check("not found", p.status == "not_found", p.status)
|
||||
|
||||
print("== leading folders are dropped: another user's home ==")
|
||||
home = tmp / "home"
|
||||
for i in range(5):
|
||||
touch(home / "Music" / "Lib" / f"x{i}.mp3")
|
||||
[p] = search([PathGroup("Macintosh HD", "/", [f"/Users/alice/Music/Lib/x{i}.mp3" for i in range(5)])], [home])
|
||||
check("found", p.status == "found", p.status)
|
||||
check("maps the old home onto the new one",
|
||||
p.status == "found" and p.candidates[0].mapping == PathMapping.make("/Users/alice", str(home)),
|
||||
str(p.candidates[0].mapping) if p.candidates else "")
|
||||
|
||||
print("== a one-track group is taken on one ==")
|
||||
[p] = search([PathGroup("X:", "X:", [stored[0]])], [ssd])
|
||||
check("found", p.status == "found" and p.candidates[0].found == 1, p.status)
|
||||
|
||||
|
||||
# ---- the Traktor path, through the routes --------------------------------------
|
||||
from konduktor import relocation # noqa: E402
|
||||
|
||||
# Search only the fake SSD: the real drives would make the answer depend on the machine.
|
||||
relocation.candidate_roots = lambda: [ssd]
|
||||
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
|
||||
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
|
||||
from konduktor.core.adapter import NewTrack # noqa: E402
|
||||
from konduktor.core.model import Track # noqa: E402
|
||||
|
||||
lib = tmp / "lib" / "collection.nml"
|
||||
lib.parent.mkdir()
|
||||
lib.write_text(SKELETON, encoding="utf-8")
|
||||
on_ssd = [ssd / r for r in rel[:3]]
|
||||
local = touch(tmp / "Local" / "keep.mp3") # stays where it is: its volume resolves
|
||||
gone = touch(tmp / "Gone" / "lost.mp3")
|
||||
a = TraktorAdapter(lib)
|
||||
a.add_tracks([NewTrack(track=Track(id="", title=p.stem), audio_path=p) for p in [*on_ssd, local, gone]])
|
||||
a.save()
|
||||
|
||||
# Re-home the stored locations as a Windows machine would have written them.
|
||||
text = lib.read_text(encoding="utf-8")
|
||||
ssd_dir = os_path_to_location(ssd / "x")[1] # "/:…/:SSD/:"
|
||||
gone_dir = os_path_to_location(gone)[1]
|
||||
text = re.sub(rf'DIR="{re.escape(ssd_dir)}([^"]*)" (FILE="[^"]*") VOLUME="[^"]*"', r'DIR="/:\1" \2 VOLUME="X:"', text)
|
||||
text = re.sub(rf'DIR="{re.escape(gone_dir)}" (FILE="[^"]*") VOLUME="[^"]*"', r'DIR="/:Gone/:" \1 VOLUME="E:"', text)
|
||||
lib.write_text(text, encoding="utf-8")
|
||||
original = lib.read_bytes()
|
||||
check("the fixture has X: and E: locations", 'VOLUME="X:"' in text and 'VOLUME="E:"' in text)
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
from konduktor import prefs # noqa: E402
|
||||
|
||||
|
||||
def ssd_ids():
|
||||
return [t.id for t in main.require_adapter().tracks if t.id.startswith("X:")]
|
||||
|
||||
|
||||
def plays(c, tid):
|
||||
return c.get("/api/tracks/audio", params={"track_id": tid}).status_code == 200
|
||||
|
||||
|
||||
with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
check("opens", c.post("/api/library/open", json={"path": str(lib)}).status_code == 200)
|
||||
|
||||
print("== the check proposes, and applies nothing yet ==")
|
||||
r = c.get("/api/library/relocation")
|
||||
check("answers 200", r.status_code == 200, r.text[:300])
|
||||
vols = {v["label"]: v for v in r.json()["volumes"]}
|
||||
check("asks about X: and E: only — the volume that resolves is left alone",
|
||||
set(vols) == {"X:", "E:"}, str(sorted(vols)))
|
||||
xv = vols.get("X:", {})
|
||||
check("X: found on the SSD, 3 of 3",
|
||||
xv.get("status") == "found" and xv["candidates"][0]["to"] == str(ssd)
|
||||
and xv["candidates"][0]["found"] == 3, str(xv))
|
||||
check("E: not found", vols.get("E:", {}).get("status") == "not_found")
|
||||
tid = ssd_ids()[0]
|
||||
check("before answering, an SSD track does not play", not plays(c, tid))
|
||||
|
||||
print("== only a proposed mapping is accepted ==")
|
||||
r = c.post("/api/library/relocation", json={"mappings": [{"from": "X:", "to": str(tmp)}]})
|
||||
check("an unproposed mapping is a 400", r.status_code == 400, r.text[:200])
|
||||
|
||||
print("== Apply ==")
|
||||
r = c.post("/api/library/relocation", json={"mappings": [{"from": "X:", "to": str(ssd)}]})
|
||||
check("answers 200 with the track count", r.status_code == 200 and r.json()["tracks"] == 3, r.text[:200])
|
||||
check("the SSD tracks now play", all(plays(c, t) for t in ssd_ids()))
|
||||
check("the check is settled", c.get("/api/library/relocation").json()["volumes"] == [])
|
||||
check("a second answer is refused",
|
||||
c.post("/api/library/relocation", json={"mappings": []}).status_code == 400)
|
||||
check("track ids are unchanged (nothing was rewritten)", tid in ssd_ids() and len(ssd_ids()) == 3)
|
||||
check("the collection file is untouched", lib.read_bytes() == original)
|
||||
check("nothing is saved to prefs", prefs.get_path_mapping(str(lib)) is None)
|
||||
|
||||
print("== session-only: a reopen asks again ==")
|
||||
c.post("/api/library/open", json={"path": str(lib)})
|
||||
vols = {v["label"] for v in c.get("/api/library/relocation").json()["volumes"]}
|
||||
check("asked again", vols == {"X:", "E:"}, str(vols))
|
||||
check("and the mapping is gone", not plays(c, tid))
|
||||
|
||||
print("== Not now ==")
|
||||
r = c.post("/api/library/relocation", json={"mappings": []})
|
||||
check("answers 200", r.status_code == 200, r.text[:200])
|
||||
check("settled, nothing applied",
|
||||
c.get("/api/library/relocation").json()["volumes"] == [] and not plays(c, tid))
|
||||
|
||||
print("== a saved manual mapping is respected ==")
|
||||
c.put("/api/library/path-mapping", json={"from": "X:", "to": str(ssd)})
|
||||
c.post("/api/library/open", json={"path": str(lib)})
|
||||
vols = {v["label"] for v in c.get("/api/library/relocation").json()["volumes"]}
|
||||
check("only E: is asked about", vols == {"E:"}, str(vols))
|
||||
c.put("/api/library/path-mapping", json={"from": "", "to": ""})
|
||||
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
print("\nFAILED" if failed else "\nALL PASSED")
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -515,6 +515,164 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("H2: old playlist PRIMARYKEY gone", old_key not in all_pl_keys)
|
||||
check("H2: new playlist PRIMARYKEY present", new_key in all_pl_keys)
|
||||
|
||||
# H3: a remap re-keys the entry index, so the track is still reachable by its
|
||||
# NEW id before any save — and a tag edit made BEFORE the remap still reaches
|
||||
# the file on save (it was silently dropped when the index kept the old key).
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
|
||||
store = TraktorStore(work)
|
||||
target = next(e for e in store._nml.collection.entry if e.location and e.location.file)
|
||||
old_key = _key(target.location)
|
||||
from_prefix = str(resolve_path(target.location.volume, target.location.dir, target.location.file))
|
||||
to_prefix = "/Volumes/KONDUKTOR_TEST_H3/remapped__rekey__one.mp3"
|
||||
new_key = "".join(os_path_to_location(Path(to_prefix)))
|
||||
|
||||
store.set_track_metadata(old_key, {"genre": "H3 before remap"})
|
||||
store.set_track_art(old_key, b"\xff\xd8H3", "image/jpeg")
|
||||
moved = store.remap_locations(PathMapping.make(from_prefix, to_prefix))
|
||||
check("H3: the remap reports the new id", moved.get(old_key) == new_key, str(moved))
|
||||
check("H3: the index finds the ENTRY by its new id", store._entry_by_key.get(new_key) is target)
|
||||
check("H3: …and no longer by its old one", old_key not in store._entry_by_key)
|
||||
check("H3: staged cover art follows the track", new_key in store._track_art and old_key not in store._track_art)
|
||||
|
||||
try:
|
||||
store.set_track_metadata(new_key, {"label": "H3 after remap"})
|
||||
check("H3: an edit by the new id works before saving", target.info.label == "H3 after remap")
|
||||
except PlaylistError as exc:
|
||||
check("H3: an edit by the new id works before saving", False, str(exc))
|
||||
|
||||
# The tag sync must visit the moved track with BOTH edits. Stub the file
|
||||
# side: this is about which tracks it reaches, not about mutagen.
|
||||
import konduktor.core.audio_tags as _tags # noqa: E402
|
||||
|
||||
written = []
|
||||
real_write_tags, real_write_cover = _tags.write_tags, _tags.write_cover
|
||||
ok = SimpleNamespace(ok=True, status="ok", detail=None)
|
||||
_tags.write_tags = lambda path, meta, **k: (written.append(("tags", meta)), ok)[1]
|
||||
_tags.write_cover = lambda path, data, mime: (written.append(("cover", data)), ok)[1]
|
||||
store._resolve = lambda loc: Path(to_prefix)
|
||||
try:
|
||||
results = store._sync_file_tags()
|
||||
finally:
|
||||
_tags.write_tags, _tags.write_cover = real_write_tags, real_write_cover
|
||||
tag_meta = next((m for kind, m in written if kind == "tags"), {})
|
||||
check("H3: the file-tag sync reaches the remapped track",
|
||||
[r.track_id for r in results] == [new_key, new_key], str([r.track_id for r in results]))
|
||||
check("H3: …with the edit made before the remap AND the one after",
|
||||
tag_meta.get("genre") == "H3 before remap" and tag_meta.get("label") == "H3 after remap",
|
||||
str(tag_meta))
|
||||
check("H3: …and the staged cover art", ("cover", b"\xff\xd8H3") in written)
|
||||
|
||||
# H4: a remap that would give two ENTRYs one primary key is refused with nothing
|
||||
# changed; the preview says so first. A chain (one track onto another's OLD
|
||||
# path while that one moves on) is not a clash, and each track's staged art and
|
||||
# edits must follow IT, not the path.
|
||||
from konduktor.core.adapter import InvalidCommand # noqa: E402
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
store = TraktorStore(work)
|
||||
entries = [e for e in store._nml.collection.entry if e.location and e.location.file]
|
||||
e1, e2, e3 = entries[0], entries[1], entries[2]
|
||||
|
||||
def put(e, path):
|
||||
e.location.volume, e.location.dir, e.location.file = os_path_to_location(Path(path))
|
||||
|
||||
def rekey(st):
|
||||
st._entry_by_key = {st._key_of(e): e for e in st._nml.collection.entry if e.location}
|
||||
|
||||
# (a) onto a path a STAYING track already has — the realistic case: a folder
|
||||
# copied to a new drive and both copies in the collection.
|
||||
put(e1, "/Volumes/H4OLD/Music/same.mp3")
|
||||
put(e2, "/Volumes/H4NEW/Music/same.mp3")
|
||||
rekey(store)
|
||||
before = store._render()
|
||||
mapping = PathMapping.make("/Volumes/H4OLD/Music", "/Volumes/H4NEW/Music")
|
||||
preview = store.remap_preview(mapping)
|
||||
check("H4: the preview reports the clash before anything is done",
|
||||
preview["collisions"] == 1 and len(preview["collision_samples"]) == 1
|
||||
and preview["collision_samples"][0].endswith("H4NEW/Music/same.mp3"), str(preview))
|
||||
try:
|
||||
store.remap_locations(mapping)
|
||||
check("H4: a remap onto a staying track's path is refused", False, "it ran")
|
||||
except PlaylistError as exc:
|
||||
check("H4: a remap onto a staying track's path is refused", "nothing was changed" in str(exc), str(exc))
|
||||
check("H4: …and nothing changed", store._render() == before and not store.dirty)
|
||||
|
||||
# (b) two DIFFERENTLY-keyed entries for one file — the boot disk spelt
|
||||
# "Macintosh HD" and blank, both resolving to /Users/… — that the mapping
|
||||
# sends to the same place.
|
||||
put(e1, "/Users/h4/one.mp3")
|
||||
e3.location.volume, e3.location.dir, e3.location.file = "", e1.location.dir, e1.location.file
|
||||
put(e2, "/Volumes/H4OTHER/two.mp3")
|
||||
rekey(store)
|
||||
check("H4: (setup) two keys, one file",
|
||||
store._key_of(e1) != store._key_of(e3)
|
||||
and resolve_path(e1.location.volume, e1.location.dir, e1.location.file)
|
||||
== resolve_path(e3.location.volume, e3.location.dir, e3.location.file))
|
||||
mapping = PathMapping.make("/Users/h4", "/Volumes/H4DEST")
|
||||
check("H4: two entries with different keys landing on one path clash",
|
||||
store.remap_preview(mapping)["collisions"] == 1, str(store.remap_preview(mapping)))
|
||||
before = store._render()
|
||||
try:
|
||||
store.remap_locations(mapping)
|
||||
check("H4: …and that remap is refused", False, "it ran")
|
||||
except PlaylistError:
|
||||
check("H4: …and that remap is refused, unchanged", store._render() == before)
|
||||
put(e3, "/Volumes/H4OTHER/unrelated.mp3")
|
||||
|
||||
# (c) a duplicate the collection ALREADY had moves as it was — refusing it
|
||||
# would make a library with one duplicate impossible to move at all.
|
||||
put(e1, "/Volumes/H4OLD/Music/same.mp3")
|
||||
put(e2, "/Volumes/H4OLD/Music/same.mp3") # e1 and e2 now share a key
|
||||
rekey(store)
|
||||
mapping = PathMapping.make("/Volumes/H4OLD/Music", "/Volumes/H4MOVED/Music")
|
||||
check("H4: an existing duplicate is not a new clash", store.remap_preview(mapping)["collisions"] == 0)
|
||||
moved = store.remap_locations(mapping)
|
||||
check("H4: …and the pair moves together", len(moved) == 1 and store._key_of(e1) == store._key_of(e2))
|
||||
|
||||
# (d) a chain from a nested prefix: x/f -> x/sub/f while x/sub/f -> x/sub/sub/f.
|
||||
put(e1, "/Volumes/H4C/x/f.mp3")
|
||||
put(e2, "/Volumes/H4C/x/sub/f.mp3")
|
||||
rekey(store)
|
||||
k1, k2 = store._key_of(e1), store._key_of(e2)
|
||||
store.set_track_metadata(k1, {"genre": "chain one"})
|
||||
store.set_track_metadata(k2, {"genre": "chain two"})
|
||||
store.set_track_art(k1, b"art-one", "image/jpeg")
|
||||
store.set_track_art(k2, b"art-two", "image/jpeg")
|
||||
mapping = PathMapping.make("/Volumes/H4C/x", "/Volumes/H4C/x/sub")
|
||||
check("H4: a chain is not a clash", store.remap_preview(mapping)["collisions"] == 0)
|
||||
moved = store.remap_locations(mapping)
|
||||
n1, n2 = store._key_of(e1), store._key_of(e2)
|
||||
check("H4: the first track takes the second's old path", n1 == k2 and moved[k1] == n1, f"{moved}")
|
||||
check("H4: the index finds each track at its new id",
|
||||
store._entry_by_key.get(n1) is e1 and store._entry_by_key.get(n2) is e2)
|
||||
check("H4: each track's staged art follows the TRACK",
|
||||
store._track_art.get(n1, (b"",))[0] == b"art-one" and store._track_art.get(n2, (b"",))[0] == b"art-two",
|
||||
str({k: v[0] for k, v in store._track_art.items()}))
|
||||
check("H4: …and so do its edits",
|
||||
store._journal.fields_for(n1) == {"genre"} and store._journal.fields_for(n2) == {"genre"}
|
||||
and store._entry_field_value(store._entry_by_key[n1], "genre") == "chain one")
|
||||
j1 = [c for c in store._journal.changes if c.target == n1 and c.scope == "track"]
|
||||
check("H4: …exactly one edit each, not both on one track", len(j1) == 1, str(j1))
|
||||
|
||||
# Through the adapter the refusal is the generic InvalidCommand (-> HTTP 400).
|
||||
shutil.copy2(REAL, work)
|
||||
ad = TraktorAdapter(work)
|
||||
a1, a2 = [e for e in ad.store._nml.collection.entry if e.location and e.location.file][:2]
|
||||
put(a1, "/Volumes/H4OLD/Music/same.mp3")
|
||||
put(a2, "/Volumes/H4NEW/Music/same.mp3")
|
||||
rekey(ad.store)
|
||||
try:
|
||||
ad.remap_locations(PathMapping.make("/Volumes/H4OLD/Music", "/Volumes/H4NEW/Music"))
|
||||
check("H4: the adapter refuses with InvalidCommand", False, "it ran")
|
||||
except InvalidCommand:
|
||||
check("H4: the adapter refuses with InvalidCommand", True)
|
||||
|
||||
|
||||
# ---- Invariant I: flexible (multi-marker) beatgrids round-trip ---------
|
||||
print("== I. flexible beatgrid: add/move/delete markers, localized + reversible ==")
|
||||
@@ -736,5 +894,51 @@ with tempfile.TemporaryDirectory() as d:
|
||||
all((n.playlist.entries or 0) == len(n.playlist.entry or []) for n in pl_nodes(re)))
|
||||
|
||||
|
||||
# ---- Invariant M: dates cross in Traktor's own form -----------------------
|
||||
# The projection turns Traktor's "YYYY/M/D" into ISO; everything that writes a
|
||||
# date back must turn it round again, or the NML ends up holding a notation
|
||||
# Traktor never writes.
|
||||
print("== M. dates are written as Traktor's YYYY/M/D, tags get ISO ==")
|
||||
from konduktor.adapters.traktor.projection import iso_date, traktor_date # noqa: E402
|
||||
|
||||
for given, want in [
|
||||
("2021-03-04", "2021/3/4"), ("2021-12-25", "2021/12/25"), ("2021", "2021/1/1"),
|
||||
("2021-07", "2021/7/1"), ("2021-03-04T10:20:30", "2021/3/4"), ("2021/03/04", "2021/3/4"),
|
||||
("2021/3/4", "2021/3/4"), ("sometime", "sometime"), ("", None), (None, None),
|
||||
]:
|
||||
check(f"M: traktor_date({given!r}) == {want!r}", traktor_date(given) == want, repr(traktor_date(given)))
|
||||
check("M: every date in the collection round-trips through ISO",
|
||||
all(traktor_date(iso_date(v)) == v
|
||||
for e in TraktorCollection(path=REAL).nml.collection.entry if e.info
|
||||
for v in (e.info.release_date, e.info.import_date, e.info.last_played) if v))
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
store = TraktorStore(work)
|
||||
target = next(e for e in store._nml.collection.entry
|
||||
if e.location and e.info and e.info.release_date)
|
||||
key = store._key_of(target)
|
||||
original = store._render()
|
||||
store.set_track_metadata(key, {"release_date": "2019-06-07"})
|
||||
check("M: an ISO edit is stored as Traktor's form", target.info.release_date == "2019/6/7",
|
||||
target.info.release_date)
|
||||
check("M: …and the file tag is given ISO",
|
||||
store._entry_field_value(target, "release_date") == "2019-06-07")
|
||||
changed = [dl for dl in difflib.unified_diff(tag_lines(original), tag_lines(store._render()), n=0)
|
||||
if dl[:1] in "+-" and dl[:3] not in ("+++", "---")]
|
||||
check("M: only that ENTRY's INFO line changes", len(changed) == 2 and "RELEASE_DATE=\"2019/6/7\"" in changed[1],
|
||||
"\n".join(changed[:4]))
|
||||
|
||||
new_id = store.add_entry(
|
||||
SimpleNamespace(title="M dates", release_date="2020", import_date="2026-09-30"),
|
||||
Path("/Volumes/KONDUKTOR_TEST_M/dates.mp3"),
|
||||
)
|
||||
info = store._entry_by_key[new_id].info
|
||||
check("M: an added track's dates are Traktor's form",
|
||||
(info.release_date, info.import_date) == ("2020/1/1", "2026/9/30"),
|
||||
f"{info.release_date!r} {info.import_date!r}")
|
||||
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,272 @@
|
||||
"""The stem writer (`core/stem_file.py`) on GENERATED sources with a FAKE engine.
|
||||
|
||||
The separation is a callback, so everything Konduktor itself does — decode,
|
||||
encode five streams, the `stem` box, tags, verification — is tested here with no
|
||||
torch installed. What would fail SILENTLY is what this pins:
|
||||
|
||||
* the two stem JSON literals are exactly the bytes the user's commercial files
|
||||
and Traktor's collection hold (skipped when those files are not on the
|
||||
machine), and hold the same float32 values;
|
||||
* a mono source is not converted 3 dB quieter, and resampling does not move
|
||||
time — both would shift or change every converted track;
|
||||
* the finished file starts on the source's first sample (cue positions carry
|
||||
over unchanged in the decoded time base), with every tag and the cover;
|
||||
* `verify` refuses a shifted, truncated or box-less file.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fractions
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-stemfile-appdata-")
|
||||
|
||||
import av # noqa: E402
|
||||
import numpy as np # noqa: E402
|
||||
|
||||
from konduktor.core import stem_file as sf # noqa: E402
|
||||
from konduktor.core import tag_copy # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
def encode(path: Path, codec: str, fmt: str, x: np.ndarray, sr: int, layout="stereo", bit_rate=None):
|
||||
with av.open(str(path), "w", format=fmt) as c:
|
||||
s = c.add_stream(codec, rate=sr, layout=layout)
|
||||
if bit_rate:
|
||||
s.bit_rate = bit_rate
|
||||
n = x.shape[1]
|
||||
for o in range(0, n, 1152):
|
||||
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout=layout)
|
||||
f.sample_rate, f.pts = sr, o
|
||||
for p in s.encode(f):
|
||||
c.mux(p)
|
||||
for p in s.encode(None):
|
||||
c.mux(p)
|
||||
|
||||
|
||||
def music(n, sr, seed=1):
|
||||
"""Noise bursts on a beat: something every encoder and the correlator can grip."""
|
||||
rng = np.random.default_rng(seed)
|
||||
x = np.zeros((2, n), np.float32)
|
||||
for start in range(int(0.5 * sr), n - sr // 10, sr // 2):
|
||||
burst = rng.uniform(-0.6, 0.6, (2, sr // 20)).astype(np.float32)
|
||||
x[:, start:start + burst.shape[1]] += burst * np.linspace(1, 0, burst.shape[1])
|
||||
return x
|
||||
|
||||
|
||||
def fake_separate(pcm):
|
||||
"""Four 'stems' in DEMUCS_ORDER: scaled copies, so each stream is distinct."""
|
||||
return [pcm * g for g in (0.5, 0.25, -0.2, 0.1)]
|
||||
|
||||
|
||||
tmp = Path(tempfile.mkdtemp(prefix="konduktor-stemfile-"))
|
||||
|
||||
print("== 1. the stem JSON literals ==")
|
||||
box, nml = json.loads(sf.STEM_BOX_JSON), json.loads(sf.NML_STEMS_JSON)
|
||||
|
||||
|
||||
def f32(o):
|
||||
if isinstance(o, float):
|
||||
return struct.unpack("f", struct.pack("f", o))[0]
|
||||
if isinstance(o, dict):
|
||||
return {k: f32(v) for k, v in o.items()}
|
||||
if isinstance(o, list):
|
||||
return [f32(v) for v in o]
|
||||
return o
|
||||
|
||||
|
||||
check("the box and the NML value hold the same float32 values", f32(box) == f32(nml))
|
||||
check("names and colours are Drums/Bass/Synths/Vox, as on every stem in the collection",
|
||||
[s["name"] for s in box["stems"]] == list(sf.STEM_NAMES))
|
||||
check("mastering DSP is written disabled", not box["mastering_dsp"]["compressor"]["enabled"]
|
||||
and not box["mastering_dsp"]["limiter"]["enabled"])
|
||||
commercial = sorted(Path.home().glob("Music/Library/*.stem.m4a"))
|
||||
if commercial:
|
||||
check(f"the box is byte-identical to {len(commercial)} commercial stem files",
|
||||
all(sf.read_stem_box(p) == sf.STEM_BOX_JSON for p in commercial))
|
||||
else:
|
||||
print(" (skipped: no commercial stem files on this machine)")
|
||||
real_nml = Path.home() / "Downloads/collection_latest.nml"
|
||||
if real_nml.is_file():
|
||||
values = {html.unescape(v) for v in re.findall(r'<STEMS STEMS="([^"]*)"', real_nml.read_text(encoding="utf-8"))}
|
||||
check("the NML value is the one Traktor wrote on every stem entry", values == {sf.NML_STEMS_JSON}, str(len(values)))
|
||||
else:
|
||||
print(" (skipped: the real collection is not on this machine)")
|
||||
# How a stem file that Konduktor did NOT write gets its `<STEMS>` when added:
|
||||
# rendered from its own box by Traktor's rule.
|
||||
check("Traktor's rendering rule turns the box literal into the NML literal",
|
||||
sf.traktor_stems_json(sf.STEM_BOX_JSON) == sf.NML_STEMS_JSON)
|
||||
check("…and keeps other names, colours and values (keys sorted, whole floats as integers)",
|
||||
sf.traktor_stems_json(b'{"version": 1, "stems": [{"name": "Kick \\u00e9", "color": "#010203"}], '
|
||||
b'"x": {"b": 2.5, "a": 3.0, "c": true}}')
|
||||
== '{"stems":[{"color":"#010203","name":"Kick é"}],"version":1,"x":{"a":3,"b":2.5,"c":true}}')
|
||||
nml_stem_entries = {}
|
||||
for n in (real_nml, Path.home() / "Downloads/collection.nml"):
|
||||
if n.is_file():
|
||||
for file, value in re.findall(r'FILE="([^"]+)"(?:(?!</ENTRY>).)*?<STEMS STEMS="([^"]*)"',
|
||||
n.read_text(encoding="utf-8"), re.S):
|
||||
nml_stem_entries[html.unescape(file)] = html.unescape(value)
|
||||
pairs = [(p, nml_stem_entries[p.name]) for p in commercial if p.name in nml_stem_entries]
|
||||
if pairs:
|
||||
check(f"…and gives exactly what Traktor wrote for {len(pairs)} stem files in its collections",
|
||||
all(sf.nml_stems_for(p) == v for p, v in pairs))
|
||||
else:
|
||||
print(" (skipped: no stem file with a Traktor entry on this machine)")
|
||||
|
||||
print("== 2. decode: mono level, resampling does not move time ==")
|
||||
m = np.zeros((1, 44100), np.float32)
|
||||
m[0, 100] = 0.5
|
||||
encode(tmp / "mono.wav", "pcm_f32le", "wav", m, 44100, layout="mono")
|
||||
d = sf.decode(tmp / "mono.wav")
|
||||
check("a mono source is duplicated at full level (not FFmpeg's -3 dB)",
|
||||
d.pcm.shape[0] == 2 and np.allclose(d.pcm[:, 100], 0.5), str(d.pcm[:, 100]))
|
||||
x48 = np.zeros((2, 48000 * 3), np.float32)
|
||||
x48[:, 48000] = 1.0
|
||||
encode(tmp / "imp48.wav", "pcm_f32le", "wav", x48, 48000)
|
||||
d = sf.decode(tmp / "imp48.wav")
|
||||
check("a 48 kHz impulse at 1.000 s lands on sample 44100", int(np.argmax(np.abs(d.pcm[0]))) == 44100)
|
||||
check("…and the length converts exactly", d.samples == 44100 * 3, str(d.samples))
|
||||
|
||||
print("== 3. build: MP3 and FLAC sources, both encoders ==")
|
||||
from mutagen.flac import FLAC, Picture # noqa: E402
|
||||
from mutagen.id3 import APIC, ID3, TBPM, TIT2, TKEY, TPE1, TPUB, TRCK # noqa: E402
|
||||
|
||||
SR = 44100
|
||||
src = music(SR * 12, SR)
|
||||
MP3 = tmp / "Track One.mp3"
|
||||
encode(MP3, "libmp3lame", "mp3", src, SR, bit_rate=320_000)
|
||||
tags = ID3()
|
||||
for frame in (TIT2(encoding=3, text=["Track One"]), TPE1(encoding=3, text=["Some Artist"]),
|
||||
TKEY(encoding=3, text=["8A"]), TBPM(encoding=3, text=["125"]),
|
||||
TRCK(encoding=3, text=["3/12"]), TPUB(encoding=3, text=["A Label"])):
|
||||
tags.add(frame)
|
||||
COVER = b"\xff\xd8\xff\xe0" + os.urandom(2000)
|
||||
tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=COVER))
|
||||
tags.save(str(MP3))
|
||||
|
||||
MP3_128 = tmp / "low.mp3"
|
||||
encode(MP3_128, "libmp3lame", "mp3", src, SR, bit_rate=128_000)
|
||||
FLAC_SRC = tmp / "Lossless.flac"
|
||||
encode(FLAC_SRC, "flac", "flac", src, SR)
|
||||
fl = FLAC(str(FLAC_SRC))
|
||||
fl["title"], fl["artist"], fl["initialkey"], fl["tracknumber"], fl["tracktotal"] = "Lossless", "FLAC Artist", "11B", "4", "9"
|
||||
pic = Picture()
|
||||
pic.type, pic.mime, pic.data = 3, "image/jpeg", COVER
|
||||
fl.add_picture(pic)
|
||||
fl.save()
|
||||
|
||||
encoders = ["aac"] + (["aac_at"] if "aac_at" in av.codecs_available else [])
|
||||
for enc in encoders:
|
||||
out = tmp / f"Track One.{enc}.stem.m4a.konduktor-partial"
|
||||
source = sf.decode(MP3)
|
||||
written = sf.build(MP3, out, fake_separate, encoder=enc)
|
||||
with av.open(str(out)) as c:
|
||||
streams = c.streams.audio
|
||||
info = (len(streams), [int(s.disposition) for s in streams])
|
||||
check(f"{enc}: five streams, only the mix enabled", info == (5, [1, 0, 0, 0, 0]), str(info))
|
||||
check(f"{enc}: the stem box is exactly the commercial one", sf.read_stem_box(out) == sf.STEM_BOX_JSON)
|
||||
check(f"{enc}: it counts as a stem file", sf.is_stem_file(out.with_name("x.stem.m4a")) is False
|
||||
and sf.read_stem_box(out) is not None)
|
||||
check(f"{enc}: 320 kbps from a 320 kbps source", written.bit_rate == 320_000, str(written.bit_rate))
|
||||
check(f"{enc}: duration is the source's", abs(written.duration - source.samples / SR) < 1e-9)
|
||||
def stream(k):
|
||||
with av.open(str(out)) as c: # one open per stream: decoding one reads to EOF
|
||||
return np.concatenate([f.to_ndarray() for f in c.decode(c.streams.audio[k])], axis=1)
|
||||
mix, drums = stream(0), stream(1)
|
||||
# By cross-correlation, not a threshold onset: AAC pre-echo smears energy a
|
||||
# few dozen samples ahead of a sharp transient, which a threshold reads as
|
||||
# "early" although nothing moved.
|
||||
lag = sf._aligned(mix, source.pcm)
|
||||
check(f"{enc}: the mix is not shifted against the source (cues carry over unchanged)",
|
||||
lag == 0, f"lag {lag}")
|
||||
check(f"{enc}: stream 1 is the drums stem, not the mix", abs(np.max(np.abs(drums)) / np.max(np.abs(mix)) - 0.5) < 0.1)
|
||||
got = tag_copy.read_tags(out)
|
||||
check(f"{enc}: title, artist, key, BPM, track number and label copied",
|
||||
(got.get("title"), got.get("artist"), got.get("key"), got.get("bpm"), got.get("tracknumber"), got.get("label"))
|
||||
== ("Track One", "Some Artist", "8A", "125", "3/12", "A Label"), str(got))
|
||||
from mutagen.mp4 import MP4 # noqa: E402
|
||||
covr = MP4(str(out)).tags.get("covr")
|
||||
check(f"{enc}: the cover art is copied", bool(covr) and bytes(covr[0]) == COVER)
|
||||
|
||||
w = sf.build(MP3_128, tmp / "low.stem.m4a", fake_separate, encoder="aac")
|
||||
check("a 128 kbps source is encoded at the 256 kbps floor", w.bit_rate == 256_000, str(w.bit_rate))
|
||||
w = sf.build(FLAC_SRC, tmp / "Lossless.stem.m4a", fake_separate, encoder="aac")
|
||||
check("a lossless source is encoded at 320 kbps", w.bit_rate == 320_000)
|
||||
got = tag_copy.read_tags(tmp / "Lossless.stem.m4a")
|
||||
check("FLAC's Vorbis tags cross into MP4 atoms (key, track n/total)",
|
||||
(got.get("title"), got.get("key"), got.get("tracknumber")) == ("Lossless", "11B", "4/9"), str(got))
|
||||
check("a finished stem file is recognised as a stem container", sf.is_stem_file(tmp / "Lossless.stem.m4a"))
|
||||
check("a plain M4A is not", not sf.is_stem_file(tmp / "plain.m4a"))
|
||||
check("an MP3 is not, whatever the collection says", not sf.is_stem_file(MP3))
|
||||
check("Track.mp3 -> Track.stem.m4a", sf.stem_target_name("Track.mp3") == "Track.stem.m4a")
|
||||
|
||||
print("== 4. verify refuses what is wrong ==")
|
||||
source = sf.decode(MP3)
|
||||
|
||||
|
||||
def raw_file(name, master):
|
||||
path = tmp / name
|
||||
with open(path, "wb") as fp:
|
||||
sf._encode(fp, [master, *fake_separate(master)], bit_rate=256_000, encoder="aac", checkpoint=None)
|
||||
sf.add_stem_box(path)
|
||||
return path
|
||||
|
||||
|
||||
def refused(path, src_obj=source):
|
||||
try:
|
||||
sf.verify(path, src_obj)
|
||||
return None
|
||||
except sf.StemFileError as ex:
|
||||
return str(ex)
|
||||
|
||||
|
||||
shifted = np.roll(source.pcm, 5, axis=1)
|
||||
check("a mix shifted by 5 samples is refused", refused(raw_file("shift.m4a", shifted)) is not None)
|
||||
check("a truncated mix is refused", refused(raw_file("short.m4a", source.pcm[:, : source.samples - 5000])) is not None)
|
||||
good = raw_file("good.m4a", source.pcm)
|
||||
check("the same file unshifted passes", refused(good) is None, refused(good) or "")
|
||||
nobox = tmp / "nobox.m4a"
|
||||
with open(nobox, "wb") as fp:
|
||||
sf._encode(fp, [source.pcm, *fake_separate(source.pcm)], bit_rate=256_000, encoder="aac", checkpoint=None)
|
||||
check("a file without the stem box is refused", "box" in (refused(nobox) or ""), refused(nobox) or "")
|
||||
|
||||
print("== 5. cancel ==")
|
||||
|
||||
|
||||
class Stop(Exception):
|
||||
pass
|
||||
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
|
||||
def stop_in_encode():
|
||||
calls["n"] += 1
|
||||
if calls["n"] > 3:
|
||||
raise Stop()
|
||||
|
||||
|
||||
try:
|
||||
sf.build(MP3, tmp / "cancelled.partial", fake_separate, encoder="aac", checkpoint=stop_in_encode)
|
||||
check("a checkpoint that raises stops the build", False, "it finished")
|
||||
except Stop:
|
||||
check("a checkpoint that raises stops the build", True)
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Stem playback on the deck — the backend half: a stem file's stems served one
|
||||
by one, because a browser decodes only an MP4's first audio stream (the mix).
|
||||
|
||||
Pins what would fail silently:
|
||||
* a served stem is BIT-IDENTICAL to decoding that stream in place, edit list
|
||||
and all — a stem shifted by its priming would flam against the others and
|
||||
sit off every cue;
|
||||
* "is this a stem file" is read from the FILE: an MP3 whose collection entry
|
||||
carries `<STEMS>` (105 real ones do) has no stems to play;
|
||||
* the cache follows the file (an edited file is not served stale) and stays
|
||||
within its limit without evicting what it just wrote;
|
||||
* all three origins (collection, device, folder) serve them.
|
||||
|
||||
Everything is generated: a stem file built with a FAKE separator whose four
|
||||
stems are distinct scalings of the mix, so each served stem can be told apart.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-stemplay-appdata-")
|
||||
|
||||
import av # noqa: E402
|
||||
import numpy as np # noqa: E402
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
|
||||
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
|
||||
from konduktor.core import stem_file as sf # noqa: E402
|
||||
from konduktor.stems import stream_cache # noqa: E402
|
||||
from stem_test_support import make_mp3 # noqa: E402
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
def decode(path: Path, stream: int = 0) -> np.ndarray:
|
||||
with av.open(str(path)) as c:
|
||||
return np.concatenate([f.to_ndarray() for f in c.decode(c.streams.audio[stream])], axis=1)
|
||||
|
||||
|
||||
GAINS = (0.5, 0.25, -0.2, 0.1)
|
||||
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-stemplay-"))
|
||||
music = ROOT / "Music"
|
||||
music.mkdir()
|
||||
stem = music / "Tune.stem.m4a"
|
||||
sf.build(make_mp3(ROOT / "src.mp3", seconds=6), stem, lambda p: [p * g for g in GAINS])
|
||||
plain = make_mp3(music / "Plain.mp3", seed=7)
|
||||
tagged = make_mp3(music / "Tagged.mp3", seed=8) # its ENTRY will carry <STEMS>
|
||||
|
||||
print("== stem_file: what a file carries ==")
|
||||
layout = sf.stem_layout(stem)
|
||||
check("a stem file lists its four stems with names and colours, in stream order",
|
||||
[s["name"] for s in layout or []] == ["Drums", "Bass", "Synths", "Vox"]
|
||||
and all(s["color"].startswith("#") for s in layout), str(layout))
|
||||
check("a plain MP3 has none", sf.stem_layout(plain) is None)
|
||||
check("a missing file has none (no exception)", sf.stem_layout(ROOT / "nope.stem.m4a") is None)
|
||||
|
||||
print("== a temp collection pointing at them ==")
|
||||
work = ROOT / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
st = TraktorStore(work)
|
||||
entries = [e for e in st._nml.collection.entry if e.location][:3]
|
||||
ids = []
|
||||
for e, path in zip(entries, (stem, plain, tagged)):
|
||||
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
|
||||
ids.append(st._key_of(e))
|
||||
from traktor_nml_utils.models.collection import Stemstype # noqa: E402
|
||||
|
||||
entries[2].stems = Stemstype(stems=sf.NML_STEMS_JSON)
|
||||
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
|
||||
st.save()
|
||||
stem_id, plain_id, tagged_id = ids
|
||||
|
||||
with TestClient(main.app) as c:
|
||||
assert c.post("/api/library/open", json={"path": str(work)}).status_code == 200
|
||||
print("== the collection routes ==")
|
||||
r = c.get("/api/tracks/stems", params={"track_id": stem_id}).json()
|
||||
check("/api/tracks/stems lists the stem file's stems", r["stems"] == layout, str(r))
|
||||
check("…none for a plain MP3", c.get("/api/tracks/stems", params={"track_id": plain_id}).json()["stems"] == [])
|
||||
tagged_track = c.get("/api/tracks", params={"limit": 20000}).json()
|
||||
tagged_kind = next((t["media_kind"] for t in tagged_track["items"] if t["id"] == tagged_id), None) \
|
||||
if isinstance(tagged_track, dict) and "items" in tagged_track else None
|
||||
check("…and none for an MP3 the COLLECTION calls a stem track (decided by the file)",
|
||||
c.get("/api/tracks/stems", params={"track_id": tagged_id}).json()["stems"] == [],
|
||||
f"media_kind={tagged_kind}")
|
||||
|
||||
mix = decode(stem, 0)
|
||||
for k in range(4):
|
||||
r = c.get("/api/tracks/audio", params={"track_id": stem_id, "stem": k})
|
||||
ok = r.status_code == 200 and r.headers["content-type"].startswith("audio/mp4")
|
||||
got = ROOT / f"served-{k}.m4a"
|
||||
got.write_bytes(r.content if ok else b"")
|
||||
same = ok and np.array_equal(decode(got), decode(stem, k + 1))
|
||||
check(f"stem {k} is served as its own MP4, bit-identical to stream {k + 1} in place", same)
|
||||
if same:
|
||||
s = decode(got)
|
||||
n = min(s.shape[1], mix.shape[1])
|
||||
# The fake stems are the mix scaled: the right stream, not just A stream.
|
||||
ratio = float(np.dot(s[0, :n], mix[0, :n]) / np.dot(mix[0, :n], mix[0, :n]))
|
||||
check(f"…and it is stem {k} (gain {GAINS[k]:+.2f}, measured {ratio:+.2f}), same length as the mix",
|
||||
abs(ratio - GAINS[k]) < 0.05 and s.shape[1] == mix.shape[1], f"{ratio} {s.shape} {mix.shape}")
|
||||
check("the plain audio route still serves the whole file",
|
||||
c.get("/api/tracks/audio", params={"track_id": stem_id}).content == stem.read_bytes())
|
||||
check("a stem out of range is 404",
|
||||
c.get("/api/tracks/audio", params={"track_id": stem_id, "stem": 4}).status_code == 404)
|
||||
check("asking a plain MP3 for a stem is 404",
|
||||
c.get("/api/tracks/audio", params={"track_id": plain_id, "stem": 0}).status_code == 404)
|
||||
|
||||
print("== the cache ==")
|
||||
cached = stream_cache.stem_file_for(stem, 0)
|
||||
check("a second request reuses the cached file", stream_cache.stem_file_for(stem, 0) == cached)
|
||||
st_ = stem.stat()
|
||||
os.utime(stem, ns=(st_.st_atime_ns, st_.st_mtime_ns + 10_000_000_000))
|
||||
check("an edited source gets a fresh file, never the stale one", stream_cache.stem_file_for(stem, 0) != cached)
|
||||
before = sorted(stream_cache.root().glob("*.m4a"))
|
||||
stream_cache.LIMIT = 1 # everything is over the limit now
|
||||
newest = stream_cache.stem_file_for(stem, 3)
|
||||
after = sorted(stream_cache.root().glob("*.m4a"))
|
||||
check("over its limit the cache evicts the least recently used…", len(before) >= 2 and after == [newest],
|
||||
f"{len(before)} -> {[p.name for p in after]}")
|
||||
check("…but never the file it just wrote", newest.exists() and newest in after)
|
||||
check("no partial file is left behind", not list(stream_cache.root().glob("*.part")))
|
||||
stream_cache.LIMIT = 2 * 1024 ** 3
|
||||
|
||||
print("== the folder origin ==")
|
||||
listing = c.get("/api/folder/tracks", params={"path": str(music)})
|
||||
check("(setup) the folder lists", listing.status_code == 200, listing.text[:200])
|
||||
fid = str(stem)
|
||||
r = c.get("/api/folder/tracks/stems", params={"track_id": fid})
|
||||
check("a stem file browsed in a folder lists its stems", r.status_code == 200 and r.json()["stems"] == layout,
|
||||
r.text[:200])
|
||||
r = c.get("/api/folder/tracks/audio", params={"track_id": fid, "stem": 1})
|
||||
got = ROOT / "folder-1.m4a"
|
||||
got.write_bytes(r.content)
|
||||
check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2)))
|
||||
kinds = {t["id"]: t["media_kind"] for t in listing.json()["tracks"]}
|
||||
check("the listing marks the stem file as a stem track and the MP3 as audio",
|
||||
kinds.get(str(stem)) == "stem" and kinds.get(str(plain)) == "audio", str(kinds))
|
||||
|
||||
print("== adding a stem file to the collection ==")
|
||||
extra_dir = ROOT / "More"
|
||||
extra_dir.mkdir()
|
||||
extra = extra_dir / "Other.stem.m4a"
|
||||
shutil.copy2(stem, extra)
|
||||
extra_plain = make_mp3(extra_dir / "Other.mp3", seed=9)
|
||||
assert c.get("/api/folder/tracks", params={"path": str(extra_dir)}).status_code == 200
|
||||
pl_id = c.post("/api/playlists", json={"name": "Stem Adds"}).json()["id"]
|
||||
job = c.post("/api/folder/add", json={"track_ids": [str(extra), str(extra_plain)],
|
||||
"mode": "reference", "playlist_id": pl_id}).json()
|
||||
while job["state"] == "running":
|
||||
time.sleep(0.05)
|
||||
job = c.get(f"/api/jobs/{job['id']}").json()
|
||||
check("(setup) the add finishes", job["state"] == "done", str(job))
|
||||
new_stem, new_plain = job["result"]["track_ids"]
|
||||
kinds = {t["id"]: t["media_kind"] for t in c.get("/api/tracks", params={"limit": 20000}).json()["items"]}
|
||||
check("the added stem file is a stem track, the MP3 beside it audio",
|
||||
kinds.get(new_stem) == "stem" and kinds.get(new_plain) == "audio", f"{kinds.get(new_stem)} {kinds.get(new_plain)}")
|
||||
saved = work.read_text(encoding="utf-8")
|
||||
|
||||
def entry_of(name: str) -> str:
|
||||
at = saved.find(f'FILE="{name}"')
|
||||
return saved[at:saved.find("</ENTRY>", at)] if at >= 0 else ""
|
||||
|
||||
m = re.search(r'<STEMS STEMS="([^"]*)"', entry_of(extra.name))
|
||||
check("…its saved ENTRY carries <STEMS>, rendered as Traktor renders that file's box",
|
||||
m is not None and html.unescape(m.group(1)) == sf.NML_STEMS_JSON, entry_of(extra.name)[:300])
|
||||
check("…the MP3's carries none", entry_of(extra_plain.name) != "" and "<STEMS" not in entry_of(extra_plain.name))
|
||||
check('…and the playlist keys the stem file TYPE="STEM", the MP3 TYPE="TRACK"',
|
||||
re.search(r'<PRIMARYKEY TYPE="STEM" KEY="[^"]*Other\.stem\.m4a"', saved) is not None
|
||||
and re.search(r'<PRIMARYKEY TYPE="TRACK" KEY="[^"]*Other\.mp3"', saved) is not None)
|
||||
|
||||
# Rekordbox has no <STEMS>: the FILE decides, so the Type column agrees
|
||||
# with the deck, which plays a stem file's stems on every platform.
|
||||
print("== adding a stem file to a Rekordbox library ==")
|
||||
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 = ROOT / "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")
|
||||
rb_stem_dir = ROOT / "ForRekordbox"
|
||||
rb_stem_dir.mkdir()
|
||||
rb_stem = rb_stem_dir / "Rb.stem.m4a"
|
||||
shutil.copy2(stem, rb_stem)
|
||||
rb_plain = make_mp3(rb_stem_dir / "Rb.mp3", seed=11)
|
||||
r = c.post("/api/library/open", json={"path": str(rb_dir / "master.db")})
|
||||
check("(setup) a Rekordbox copy opens", r.status_code == 200, r.text[:300])
|
||||
assert c.get("/api/folder/tracks", params={"path": str(rb_stem_dir)}).status_code == 200
|
||||
job = c.post("/api/folder/add", json={"track_ids": [str(rb_stem), str(rb_plain)],
|
||||
"mode": "reference"}).json()
|
||||
while job["state"] == "running":
|
||||
time.sleep(0.05)
|
||||
job = c.get(f"/api/jobs/{job['id']}").json()
|
||||
check("(setup) the add finishes", job["state"] == "done", str(job))
|
||||
rb_new_stem, rb_new_plain = (job.get("result") or {}).get("track_ids") or [None, None]
|
||||
|
||||
def rb_kinds():
|
||||
items = c.get("/api/tracks", params={"limit": 20000}).json()["items"]
|
||||
return {t["id"]: t["media_kind"] for t in items}
|
||||
|
||||
kinds = rb_kinds()
|
||||
check("the added stem file is a stem track, the MP3 beside it audio",
|
||||
kinds.get(rb_new_stem) == "stem" and kinds.get(rb_new_plain) == "audio",
|
||||
f"{kinds.get(rb_new_stem)} {kinds.get(rb_new_plain)}")
|
||||
r = c.post("/api/library/open", json={"path": str(rb_dir / "master.db")})
|
||||
kinds = rb_kinds()
|
||||
check("…and still after a reopen",
|
||||
kinds.get(rb_new_stem) == "stem" and kinds.get(rb_new_plain) == "audio",
|
||||
f"{kinds.get(rb_new_stem)} {kinds.get(rb_new_plain)}")
|
||||
r = c.get("/api/tracks/stems", params={"track_id": rb_new_stem})
|
||||
check("and the deck is offered its stems",
|
||||
r.status_code == 200 and len(r.json()["stems"]) == 4, r.text[:200])
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,265 @@
|
||||
"""Swapping converted stem files into a Traktor collection (`apply_stem_swaps`).
|
||||
|
||||
Against a temp copy of the real collection, with a real playlisted ENTRY pointed
|
||||
at a generated MP3 (which HAS a Xing/Info header, so Traktor's clock runs 2257
|
||||
samples behind its decoded audio) and a real stem file built from it. Pins:
|
||||
|
||||
* **the prep does not move in the decoded time base** — every cue and marker
|
||||
reads back at the same second — while its stored START shifts by exactly
|
||||
the MP3's offset, read from the PARKED original;
|
||||
* a repoint changes only that ENTRY and the PRIMARYKEYs naming it (now
|
||||
`TYPE="STEM"`), byte for byte, and round-trips through a save;
|
||||
* a grid anchor pushed before 0 moves by whole beats with its companion, a
|
||||
hotcue there is clamped and reported;
|
||||
* "add" appends an entry and leaves the original's bytes alone;
|
||||
* a clash is refused with nothing changed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-stemswap-appdata-")
|
||||
|
||||
import av # noqa: E402
|
||||
import numpy as np # noqa: E402
|
||||
|
||||
from konduktor.adapters.traktor import timebase # noqa: E402
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
|
||||
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
|
||||
from konduktor.core import stem_file as sf # noqa: E402
|
||||
from konduktor.core.adapter import InvalidCommand, StemSwap # noqa: E402
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
def make_mp3(path: Path, seconds=6):
|
||||
sr = 44100
|
||||
rng = np.random.default_rng(3)
|
||||
x = np.zeros((2, sr * seconds), np.float32)
|
||||
for start in range(sr // 2, x.shape[1] - sr // 10, sr // 2):
|
||||
x[:, start:start + 2000] = rng.uniform(-0.5, 0.5, (2, 2000))
|
||||
with av.open(str(path), "w", format="mp3") as c:
|
||||
s = c.add_stream("libmp3lame", rate=sr, layout="stereo")
|
||||
s.bit_rate = 320_000
|
||||
for o in range(0, x.shape[1], 1152):
|
||||
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
|
||||
f.sample_rate, f.pts = sr, o
|
||||
for p in s.encode(f):
|
||||
c.mux(p)
|
||||
for p in s.encode(None):
|
||||
c.mux(p)
|
||||
|
||||
|
||||
def tag_lines(b: bytes) -> list[str]:
|
||||
return [("<" + t).strip() for t in b.decode("utf-8").split("<") if t.strip()]
|
||||
|
||||
|
||||
def fake_separate(pcm):
|
||||
return [pcm * g for g in (0.5, 0.25, -0.2, 0.1)]
|
||||
|
||||
|
||||
def key_of(path: Path) -> str:
|
||||
return "".join(os_path_to_location(path))
|
||||
|
||||
|
||||
def setup(tmp: Path, name: str):
|
||||
"""A temp collection whose first playlisted track now points at an MP3 with
|
||||
a header, carrying a hotcue at 3.000 s and a grid anchored at 0.500 s (both
|
||||
in DECODED time), saved. Returns (work nml, track id, mp3 path)."""
|
||||
work = tmp / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
mp3 = tmp / f"{name}.mp3"
|
||||
make_mp3(mp3)
|
||||
st = TraktorStore(work)
|
||||
in_pl = {k for n in st._iter_nodes(st._root()) if n.playlist for k in st._entry_keys_of(n.playlist)}
|
||||
entry = next(e for e in st._nml.collection.entry
|
||||
if e.location and st._key_of(e) in in_pl and e.stems is None)
|
||||
old = st._key_of(entry)
|
||||
entry.location.volume, entry.location.dir, entry.location.file = os_path_to_location(mp3)
|
||||
new = st._key_of(entry)
|
||||
for n in st._iter_nodes(st._root()):
|
||||
for pe in (n.playlist.entry if n.playlist else None) or []:
|
||||
if pe.primarykey and pe.primarykey.key == old:
|
||||
pe.primarykey.key = new
|
||||
st._entry_by_key = {st._key_of(e): e for e in st._nml.collection.entry if e.location}
|
||||
entry.cue_v2 = []
|
||||
st.set_hotcue(new, 1, 3.0, 0, name="Drop")
|
||||
st.replace_grid(new, [(0.5, 120.0)])
|
||||
st.save()
|
||||
return work, new, mp3
|
||||
|
||||
|
||||
def build_stem(mp3: Path) -> sf.Written:
|
||||
target = mp3.with_name(sf.stem_target_name(mp3.name))
|
||||
return sf.build(mp3, target, fake_separate, encoder="aac")
|
||||
|
||||
|
||||
def park(mp3: Path) -> Path:
|
||||
parked = mp3.with_name(f".{mp3.name}.konduktor-parked")
|
||||
os.replace(mp3, parked)
|
||||
return parked
|
||||
|
||||
|
||||
OFF = 2257 / 44.1 # ms: the generated MP3's Traktor offset
|
||||
|
||||
print("== 1. repoint: prep keeps its place, only the ENTRY + its keys change ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
tmp = Path(d)
|
||||
work, tid, mp3 = setup(tmp, "Song")
|
||||
check("(setup) the MP3 has Traktor's 2257-sample offset", abs(timebase.offset_ms(mp3) - OFF) < 1e-9)
|
||||
ad = TraktorAdapter(work)
|
||||
before_cues = ad.track_cues(tid)
|
||||
before = ad.snapshot()
|
||||
audio_id = ad.store.model_entry(tid).audio_id
|
||||
written = build_stem(mp3)
|
||||
parked = park(mp3)
|
||||
stem = written.path
|
||||
res = ad.apply_stem_swaps([StemSwap(tid, stem, "repoint", parked, written.bit_rate, written.duration, written.size)])
|
||||
new = key_of(stem)
|
||||
check("the result renames the track to the stem file's id", res.renamed == {tid: new}, str(res.renamed))
|
||||
check("nothing was clamped", res.clamped == {})
|
||||
entry = ad.store.model_entry(new)
|
||||
check("the entry names the stem file", entry is not None and entry.location.file == stem.name)
|
||||
check("it carries Traktor's <STEMS> value", entry.stems is not None and entry.stems.stems == sf.NML_STEMS_JSON)
|
||||
check("INFO describes the new file",
|
||||
(entry.info.bitrate, entry.info.playtime, entry.info.filesize)
|
||||
== (written.bit_rate, round(written.duration), round(written.size / 1024)),
|
||||
f"{entry.info.bitrate} {entry.info.playtime} {entry.info.filesize}")
|
||||
check("the projection calls it a stem track", ad.track(new).media_kind == "stem")
|
||||
check("Traktor's fingerprint is KEPT (cleared, Traktor re-measures the grid's BPM on load)",
|
||||
entry.audio_id == audio_id and bool(audio_id))
|
||||
after_cues = ad.track_cues(new)
|
||||
check("every cue reads back at the same DECODED second",
|
||||
[(c.slot, round(c.start, 9)) for c in after_cues.cues] == [(c.slot, round(c.start, 9)) for c in before_cues.cues],
|
||||
f"{[(c.slot, c.start) for c in after_cues.cues]} vs {[(c.slot, c.start) for c in before_cues.cues]}")
|
||||
check("…and so does the grid",
|
||||
[round(m.start, 9) for m in after_cues.grid_markers] == [round(m.start, 9) for m in before_cues.grid_markers])
|
||||
drop = next(c for c in entry.cue_v2 if c.hotcue == 1)
|
||||
marker = next(c for c in entry.cue_v2 if c.grid is not None)
|
||||
check("the stored START moved by the MP3's offset (3051.18 -> 3000.00 ms)", abs(drop.start - 3000.0) < 1e-6, str(drop.start))
|
||||
check("…the marker too (551.18 -> 500.00 ms)", abs(marker.start - 500.0) < 1e-6, str(marker.start))
|
||||
|
||||
after = ad.snapshot()
|
||||
b_lines, a_lines = tag_lines(before), tag_lines(after)
|
||||
# Everything outside this ENTRY must be identical once the one key is renamed.
|
||||
def outside(lines, file_name):
|
||||
i = next(n for n, l in enumerate(lines) if l.startswith("<LOCATION") and f'FILE="{file_name}"' in l)
|
||||
start = max(n for n in range(i) if lines[n].startswith("<ENTRY "))
|
||||
end = next(n for n in range(i, len(lines)) if lines[n] == "</ENTRY>")
|
||||
return lines[:start] + lines[end + 1:]
|
||||
rest_b = outside(b_lines, mp3.name)
|
||||
rest_a = [l.replace(f'TYPE="STEM" KEY="{new}"', f'TYPE="TRACK" KEY="{tid}"') for l in outside(a_lines, stem.name)]
|
||||
check("outside the ENTRY only its PRIMARYKEYs changed (TYPE STEM, new key)", rest_a == rest_b,
|
||||
f"{len(rest_a)} vs {len(rest_b)} lines")
|
||||
check("…and there is at least one such PRIMARYKEY", any(f'KEY="{new}"' in l for l in a_lines))
|
||||
check("the history message says what happened", "converted 1 track to stems" in ad.store._edit_summary().lower(),
|
||||
ad.store._edit_summary())
|
||||
ad.save()
|
||||
re_ad = TraktorAdapter(work)
|
||||
check("after a save the stem entry is a STEM for playlists", new in re_ad.store.stem_keys())
|
||||
check("…and its prep still reads back unmoved",
|
||||
[round(c.start, 6) for c in re_ad.track_cues(new).cues] == [round(c.start, 6) for c in before_cues.cues])
|
||||
|
||||
print("== 2. the offset must come from the PARKED file ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
tmp = Path(d)
|
||||
work, tid, mp3 = setup(tmp, "Song")
|
||||
ad = TraktorAdapter(work)
|
||||
written = build_stem(mp3)
|
||||
park(mp3)
|
||||
ad.apply_stem_swaps([StemSwap(tid, written.path, "repoint", mp3, written.bit_rate, written.duration, written.size)])
|
||||
drop = next(c for c in ad.store.model_entry(key_of(written.path)).cue_v2 if c.hotcue == 1)
|
||||
check("(the failure this guards against) read from the OLD path, nothing shifts — the cue lands 51 ms late",
|
||||
abs(drop.start - (3000.0 + OFF)) < 1e-6, str(drop.start))
|
||||
|
||||
print("== 3. positions pushed before 0 ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
tmp = Path(d)
|
||||
work, tid, mp3 = setup(tmp, "Early")
|
||||
st = TraktorStore(work)
|
||||
e = st.model_entry(tid)
|
||||
marker = next(c for c in e.cue_v2 if c.grid is not None)
|
||||
marker.start = 20.979167 # a Traktor AutoGrid inside the header frame
|
||||
st.place_grid_companion(tid, 0, prefer_slot=0)
|
||||
next(c for c in e.cue_v2 if c.hotcue == 1).start = 10.0 # a hotcue before the audio
|
||||
st._sort_cues(e)
|
||||
st.save()
|
||||
ad = TraktorAdapter(work)
|
||||
written = build_stem(mp3)
|
||||
parked = park(mp3)
|
||||
res = ad.apply_stem_swaps([StemSwap(tid, written.path, "repoint", parked, written.bit_rate, written.duration, written.size)])
|
||||
new = key_of(written.path)
|
||||
e = ad.store.model_entry(new)
|
||||
marker = next(c for c in e.cue_v2 if c.grid is not None)
|
||||
comp = next(c for c in e.cue_v2 if c.hotcue == 0)
|
||||
expect = 20.979167 - OFF + 500.0 # one beat at 120 BPM later: the same grid
|
||||
check("the anchor moved forward by a whole beat, not clamped", abs(marker.start - expect) < 1e-6, str(marker.start))
|
||||
check("its companion moved with it, as the same float", comp.start == marker.start)
|
||||
check("the hotcue before the audio is clamped to 0 and reported",
|
||||
next(c for c in e.cue_v2 if c.hotcue == 1).start == 0.0 and res.clamped == {new: [1]}, str(res.clamped))
|
||||
|
||||
print("== 4. add: a new entry, the original untouched ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
tmp = Path(d)
|
||||
work, tid, mp3 = setup(tmp, "Song")
|
||||
ad = TraktorAdapter(work)
|
||||
ad.set_track_metadata(tid, {"genre": "Pending edit"})
|
||||
original_bytes = [l for l in tag_lines(ad.snapshot())]
|
||||
n_before = len(ad.store._nml.collection.entry)
|
||||
written = build_stem(mp3)
|
||||
playlist = ad.create_playlist("Stems")
|
||||
res = ad.apply_stem_swaps([StemSwap(tid, written.path, "add", mp3, written.bit_rate, written.duration, written.size)],
|
||||
add_to_playlist=playlist)
|
||||
new = key_of(written.path)
|
||||
check("an entry was appended", len(ad.store._nml.collection.entry) == n_before + 1
|
||||
and ad.store._nml.collection.entries == n_before + 1)
|
||||
check("the original entry is still there, unchanged, not a stem",
|
||||
ad.store.model_entry(tid) is not None and ad.store.model_entry(tid).stems is None)
|
||||
check("the new one is a stem, with the original's prep",
|
||||
ad.track(new).media_kind == "stem"
|
||||
and [round(c.start, 9) for c in ad.track_cues(new).cues] == [round(c.start, 9) for c in ad.track_cues(tid).cues])
|
||||
check("…and it is in the chosen playlist as a STEM", ad.playlist_entries(playlist) == [new]
|
||||
and new in ad.store.stem_keys())
|
||||
check("the pending tag edit will also reach the new file on Save", ad.store._journal.fields_for(new) == {"genre"})
|
||||
|
||||
print("== 5. refusals change nothing ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
tmp = Path(d)
|
||||
work, tid, mp3 = setup(tmp, "Song")
|
||||
ad = TraktorAdapter(work)
|
||||
written = build_stem(mp3)
|
||||
before = ad.snapshot()
|
||||
other = next(t.id for t in ad.tracks if t.id != tid)
|
||||
try:
|
||||
ad.apply_stem_swaps([
|
||||
StemSwap(tid, written.path, "repoint", mp3, written.bit_rate, written.duration, written.size),
|
||||
StemSwap(other, written.path, "repoint", mp3, written.bit_rate, written.duration, written.size),
|
||||
])
|
||||
check("two tracks onto one stem file are refused", False, "it ran")
|
||||
except InvalidCommand:
|
||||
check("two tracks onto one stem file are refused", ad.snapshot() == before and not ad.dirty)
|
||||
ad.apply_stem_swaps([StemSwap(tid, written.path, "repoint", mp3, written.bit_rate, written.duration, written.size)])
|
||||
try:
|
||||
ad.apply_stem_swaps([StemSwap(other, written.path, "add", mp3, written.bit_rate, written.duration, written.size)])
|
||||
check("a stem file the collection already holds is refused", False, "it ran")
|
||||
except InvalidCommand:
|
||||
check("a stem file the collection already holds is refused", True)
|
||||
check("Traktor advertises stem conversion", ad.capabilities().tracks.stem_convertible)
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,277 @@
|
||||
"""The Convert to Stems batch end to end, through the routes, with a FAKE engine.
|
||||
|
||||
Against temp copies of the real collection whose playlisted tracks are pointed
|
||||
at generated MP3s. What would fail silently or destroy something:
|
||||
|
||||
* skips are reported with reasons (missing, already a stem file, target
|
||||
exists, two sources onto one target) and never converted;
|
||||
* a Replace batch leaves the SAVED collection untouched, parks the originals,
|
||||
swaps every entry at the end — prep unmoved in decoded time — and blocks
|
||||
the operations that would save or drop the swap;
|
||||
* Save deletes the parked originals and retargets export sets; Discard and
|
||||
opening another library put them back;
|
||||
* Cancel deletes what the run made and nothing else; one bad track fails
|
||||
alone;
|
||||
* destination + add mirrors the tree, never touches the originals, fills a
|
||||
new playlist;
|
||||
* after a CRASH, the next open restores (or, if the save got through,
|
||||
finishes) from what the saved collection says — and keeps the finished
|
||||
stem files, which the next batch reuses without separating again.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-stemsbatch-appdata-")
|
||||
os.environ.pop("KONDUKTOR_NML", None)
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
from konduktor import exports # noqa: E402
|
||||
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
|
||||
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
|
||||
from konduktor.core import stem_file as sf # noqa: E402
|
||||
from konduktor.stems import engine_manager as em # noqa: E402
|
||||
from konduktor.stems.pending import parked_name, partial_name # noqa: E402
|
||||
from stem_test_support import install_fake_engine, make_mp3 # noqa: E402
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-stemsbatch-"))
|
||||
em._DEFAULT = install_fake_engine(ROOT / "engine")
|
||||
|
||||
|
||||
def library(name: str, files: list[str]) -> tuple[Path, list[str], Path]:
|
||||
"""A temp collection whose first len(files) playlisted tracks point at
|
||||
`files` in a music folder (each created as an MP3 unless it is 'missing'),
|
||||
each with a hotcue at 1.000 s and a grid at 0.500 s, saved."""
|
||||
d = ROOT / name
|
||||
music = d / "Music"
|
||||
music.mkdir(parents=True)
|
||||
work = d / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
st = TraktorStore(work)
|
||||
in_pl = {k for n in st._iter_nodes(st._root()) if n.playlist for k in st._entry_keys_of(n.playlist)}
|
||||
entries = [e for e in st._nml.collection.entry if e.location and st._key_of(e) in in_pl and e.stems is None]
|
||||
ids = []
|
||||
for f, e in zip(files, entries):
|
||||
path = music / f
|
||||
if f.endswith(".mp3") and not f.startswith("missing"):
|
||||
make_mp3(path, seed=len(ids) + 1)
|
||||
old = st._key_of(e)
|
||||
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
|
||||
new = st._key_of(e)
|
||||
for n in st._iter_nodes(st._root()):
|
||||
for pe in (n.playlist.entry if n.playlist else None) or []:
|
||||
if pe.primarykey and pe.primarykey.key == old:
|
||||
pe.primarykey.key = new
|
||||
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
|
||||
e.cue_v2 = []
|
||||
if path.exists():
|
||||
st.set_hotcue(new, 1, 1.0, 0, name="Drop")
|
||||
st.replace_grid(new, [(0.5, 120.0)])
|
||||
ids.append(new)
|
||||
st.save()
|
||||
return work, ids, music
|
||||
|
||||
|
||||
def open_lib(c, work):
|
||||
r = c.post("/api/library/open", json={"path": str(work)})
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
def wait(c, jid, timeout=60):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
j = c.get(f"/api/jobs/{jid}").json()
|
||||
if j["state"] != "running":
|
||||
return j
|
||||
time.sleep(0.05)
|
||||
raise AssertionError("job did not finish")
|
||||
|
||||
|
||||
def convert(c, ids, **opts):
|
||||
r = c.post("/api/tracks/stems/convert", json={"track_ids": ids, "mode": "replace", **opts})
|
||||
assert r.status_code == 200, r.text
|
||||
return wait(c, r.json()["id"])
|
||||
|
||||
|
||||
with TestClient(main.app) as c:
|
||||
print("== preview: skips, with reasons ==")
|
||||
work, ids, music = library("preview", ["ok.mp3", "missing.mp3", "have.mp3", "dup.mp3", "dup.m4a", "stemsrc.mp3"])
|
||||
sf.build(make_mp3(ROOT / "tmp-src.mp3"), music / "already.stem.m4a", lambda p: [p * g for g in (0.5, 0.25, -0.2, 0.1)])
|
||||
(music / "have.stem.m4a").write_bytes(b"a stem the user already owns")
|
||||
make_mp3(music / "dup.m4a") # (MP3 bytes under an .m4a name: only its target name matters here)
|
||||
st = TraktorStore(work)
|
||||
e = st.model_entry(ids[5])
|
||||
e.location.file = "already.stem.m4a"
|
||||
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
|
||||
ids[5] = st._key_of(e)
|
||||
st.save()
|
||||
open_lib(c, work)
|
||||
pv = c.post("/api/tracks/stems/preview", json={"track_ids": ids, "mode": "replace"}).json()
|
||||
reasons = [s["reason"] for s in pv["skipped"]]
|
||||
check("the convertible tracks are planned (ok.mp3, dup.mp3)",
|
||||
sorted(Path(x["target"]).name for x in pv["convert"]) == ["dup.stem.m4a", "ok.stem.m4a"], str(pv["convert"]))
|
||||
check("a missing file is skipped, saying so", any("missing" in r for r in reasons), str(reasons))
|
||||
check("a file that is already a stem file is skipped", any("already a stem file" in r for r in reasons))
|
||||
check("an existing target is skipped, NEVER overwritten", any("already exists" in r for r in reasons)
|
||||
and (music / "have.stem.m4a").read_bytes() == b"a stem the user already owns")
|
||||
check("two sources onto one target (dup.mp3 + dup.m4a): the second is skipped",
|
||||
any("same file" in r for r in reasons), str(reasons))
|
||||
check("no disk-space block for a few small files", pv["blocked"] is None, str(pv["blocked"]))
|
||||
|
||||
print("== Replace: convert, park, swap at the end; the saved file untouched ==")
|
||||
work, ids, music = library("replace", ["a.mp3", "b.mp3"])
|
||||
open_lib(c, work)
|
||||
a = main.require_adapter()
|
||||
before = {t: a.track_cues(t) for t in ids}
|
||||
disk = work.read_bytes()
|
||||
lib_id = main.STATE.library_id
|
||||
es = exports.create(lib_id, name="Gig", targets=["traktor"], destination=str(ROOT / "stick"))
|
||||
exports.add(lib_id, es.id, track_ids=[ids[0]])
|
||||
j = convert(c, ids)
|
||||
res = j["result"]
|
||||
check("the job finishes, both converted", j["state"] == "done" and len(res["converted"]) == 2, str(j)[:400])
|
||||
new = [res["renamed"][t] for t in ids]
|
||||
check("stem files sit beside the originals", all((music / n).is_file() for n in ("a.stem.m4a", "b.stem.m4a")))
|
||||
check("the originals are PARKED, not gone",
|
||||
all(parked_name(music / n).is_file() and not (music / n).exists() for n in ("a.mp3", "b.mp3")))
|
||||
check("no unfinished files are left", not list(music.glob("*.konduktor-partial")))
|
||||
check("the saved collection is untouched until Save", work.read_bytes() == disk)
|
||||
state = c.get("/api/state").json()
|
||||
check("the library is dirty and reports the pending conversions",
|
||||
state["dirty"] and state["pending_stems"]["tracks"] == 2 and state["pending_stems"]["parked"] == 2, str(state))
|
||||
a = main.require_adapter()
|
||||
check("the entries are stems now", all(a.track(n).media_kind == "stem" for n in new))
|
||||
check("prep reads back at the same decoded seconds",
|
||||
all([round(x.start, 6) for x in a.track_cues(n).cues] == [round(x.start, 6) for x in before[o].cues]
|
||||
for o, n in zip(ids, new)))
|
||||
for route, body in (("/api/reload", None), ("/api/library/remap-paths", {"from": "/x", "to": "/y"}),
|
||||
("/api/history/deadbeef/restore", None)):
|
||||
r = c.post(route, json=body) if body else c.post(route)
|
||||
check(f"{route} is refused while conversions await Save (409)", r.status_code == 409, f"{r.status_code} {r.text[:120]}")
|
||||
r = c.post("/api/save")
|
||||
check("Save succeeds", r.status_code == 200, r.text[:200])
|
||||
check("…and deletes the parked originals", not any(music.glob(".*.konduktor-parked")))
|
||||
check("…keeps the stem files", all((music / n).is_file() for n in ("a.stem.m4a", "b.stem.m4a")))
|
||||
check("…and nothing is pending any more", c.get("/api/state").json()["pending_stems"] is None)
|
||||
check("the saved collection names the stem files as STEM entries", all(n in TraktorStore(work).stem_keys() for n in new))
|
||||
check("the export set follows the converted track to its new id", exports.get(lib_id, es.id).track_ids == [new[0]],
|
||||
str(exports.get(lib_id, es.id).track_ids))
|
||||
|
||||
print("== Discard puts everything back ==")
|
||||
work, ids, music = library("discard", ["a.mp3", "b.mp3"])
|
||||
open_lib(c, work)
|
||||
convert(c, ids)
|
||||
r = c.post("/api/discard")
|
||||
check("discard succeeds", r.status_code == 200 and r.json()["dirty"] is False, r.text[:200])
|
||||
check("the originals are back under their own names", all((music / n).is_file() for n in ("a.mp3", "b.mp3")))
|
||||
check("the stem files are gone, and nothing parked is left",
|
||||
not list(music.glob("*.stem.m4a")) and not list(music.glob(".*.konduktor-parked")))
|
||||
check("the entries name the MP3s again", all(main.require_adapter().track(t) is not None for t in ids))
|
||||
|
||||
print("== opening another library also puts them back ==")
|
||||
convert(c, ids)
|
||||
other, _o, _m = library("other", [])
|
||||
open_lib(c, other)
|
||||
check("the originals are back when switching library", all((music / n).is_file() for n in ("a.mp3", "b.mp3"))
|
||||
and not list(music.glob("*.stem.m4a")))
|
||||
|
||||
print("== Cancel deletes what the run made, nothing else ==")
|
||||
work, ids, music = library("cancel", ["a.mp3", "b.mp3", "c.mp3"])
|
||||
open_lib(c, work)
|
||||
os.environ["FAKE_DELAY"] = "0.15"
|
||||
jid = c.post("/api/tracks/stems/convert", json={"track_ids": ids, "mode": "replace"}).json()["id"]
|
||||
end = time.time() + 30
|
||||
while time.time() < end and "separating" not in c.get(f"/api/jobs/{jid}").json()["status"]:
|
||||
time.sleep(0.05)
|
||||
time.sleep(1.8) # into the second track
|
||||
c.post(f"/api/jobs/{jid}/cancel")
|
||||
j = wait(c, jid)
|
||||
os.environ.pop("FAKE_DELAY")
|
||||
check("the job is cancelled", j["state"] == "cancelled" and j["result"]["cancelled"], str(j)[:300])
|
||||
check("no stem file, no unfinished file is left",
|
||||
not list(music.glob("*.stem.m4a*")) and not list(music.glob("*.konduktor-partial")), str(list(music.iterdir())))
|
||||
check("the originals were never touched", all((music / n).is_file() for n in ("a.mp3", "b.mp3", "c.mp3")))
|
||||
check("nothing is dirty", c.get("/api/state").json()["dirty"] is False)
|
||||
|
||||
print("== one bad track fails alone ==")
|
||||
work, ids, music = library("fail", ["a.mp3", "bad.mp3"])
|
||||
(music / "bad.mp3").write_bytes(b"not audio at all")
|
||||
open_lib(c, work)
|
||||
j = convert(c, ids)
|
||||
res = j["result"]
|
||||
check("the good track converts", ids[0] in res["renamed"], str(res)[:300])
|
||||
check("the bad one is reported with a reason and keeps its original",
|
||||
len(res["failed"]) == 1 and res["failed"][0]["reason"] and (music / "bad.mp3").is_file(), str(res["failed"]))
|
||||
c.post("/api/discard")
|
||||
|
||||
print("== destination + add: a new playlist, originals untouched ==")
|
||||
work, ids, music = library("dest", ["x.mp3", "sub/y.mp3"])
|
||||
open_lib(c, work)
|
||||
dest = ROOT / "dest-out"
|
||||
j = convert(c, ids, mode="destination", destination=str(dest), collection="add", new_playlist="Stems")
|
||||
res = j["result"]
|
||||
check("both added", len(res["added"]) == 2 and not res["renamed"], str(res)[:300])
|
||||
check("the source tree is mirrored under the destination",
|
||||
(dest / "x.stem.m4a").is_file() and (dest / "sub" / "y.stem.m4a").is_file(), str(list(dest.rglob("*"))))
|
||||
check("the originals are untouched, not parked", (music / "x.mp3").is_file() and not list(music.rglob("*.konduktor-parked")))
|
||||
a = main.require_adapter()
|
||||
pl = next(n for n in a.store._iter_nodes(a.store._root()) if n.playlist is not None and n.name == "Stems")
|
||||
check("the new entries fill the new playlist", a.playlist_entries(pl.playlist.uuid) == [res["added"][t] for t in ids])
|
||||
check("the original entries are still plain tracks", all(a.track(t).media_kind != "stem" for t in ids))
|
||||
c.post("/api/discard")
|
||||
|
||||
print("== after a crash: restore from the saved file, keep the work, reuse it ==")
|
||||
work, ids, music = library("crash", ["a.mp3", "b.mp3"])
|
||||
open_lib(c, work)
|
||||
convert(c, ids)
|
||||
main.STATE.pending = None # the process died: nothing ran the discard
|
||||
open_lib(c, work)
|
||||
rec = c.get("/api/state").json()["stem_recovery"]
|
||||
check("the next open restored the originals", all((music / n).is_file() for n in ("a.mp3", "b.mp3")) and rec["restored"] == 2, str(rec))
|
||||
check("…and kept the finished stem files aside (not as finished files)",
|
||||
all(partial_name(music / n).is_file() and not (music / n).exists() for n in ("a.stem.m4a", "b.stem.m4a"))
|
||||
and rec["kept"] == 2, str(list(music.iterdir())))
|
||||
count = ROOT / "count.txt"
|
||||
os.environ["FAKE_COUNT"] = str(count)
|
||||
pv = c.post("/api/tracks/stems/preview", json={"track_ids": ids, "mode": "replace"}).json()
|
||||
check("a new batch plans to REUSE them", all(x["reuse"] for x in pv["convert"]), str(pv))
|
||||
j = convert(c, ids)
|
||||
check("…and converts without separating again", j["state"] == "done" and len(j["result"]["converted"]) == 2
|
||||
and not count.exists(), f"{j['result']} engine calls: {count.read_text() if count.exists() else 0}")
|
||||
os.environ.pop("FAKE_COUNT")
|
||||
c.post("/api/discard")
|
||||
|
||||
print("== after a crash between the save and the clean-up ==")
|
||||
work, ids, music = library("crash2", ["a.mp3"])
|
||||
open_lib(c, work)
|
||||
convert(c, ids)
|
||||
main.require_adapter().save() # the library write happened…
|
||||
main.STATE.pending = None # …then the process died before deleting the parked original
|
||||
open_lib(c, work)
|
||||
rec = c.get("/api/state").json()["stem_recovery"]
|
||||
check("the next open sees the swap was committed and finishes it",
|
||||
rec["committed"] == 1 and not list(music.glob(".*.konduktor-parked")) and (music / "a.stem.m4a").is_file(), str(rec))
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Traktor's MP3 time base — the offset between its clock and the decoded audio.
|
||||
|
||||
Nothing fails when this is wrong: every MP3 cue and beat is simply ~51 ms off,
|
||||
which is what every release before `adapters/traktor/timebase.py` did. So this
|
||||
pins the numbers rather than trusting them, in three layers:
|
||||
|
||||
1. `core.mp3_gapless` on GENERATED MP3s: the header frame is found AFTER an
|
||||
ID3 tag holding a megabyte of art (the check that missed it once read only
|
||||
the start of the file), and a header-less MP3 has none.
|
||||
2. The Traktor store and projection on a skeleton collection pointing at those
|
||||
files: a write adds the offset, a read subtracts it, a read is NOT clamped
|
||||
(a grid anchored inside the header frame survives a Reset byte for byte),
|
||||
and a file with nothing to go by — WAV, missing — gets 0.
|
||||
3. Traktor's OWN data: the hotcues placed by hand in Traktor 4.5 on kit 4's
|
||||
synthetic kick must read back onto that kick in the decoded audio. Skipped
|
||||
cleanly when kit 4 or its collection is not on this machine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-timebase-appdata-")
|
||||
|
||||
import av # noqa: E402
|
||||
import numpy as np # noqa: E402
|
||||
|
||||
from konduktor.adapters.traktor import timebase # noqa: E402
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
|
||||
from konduktor.core import mp3_gapless # noqa: E402
|
||||
from konduktor.core.adapter import NewTrack # noqa: E402
|
||||
from konduktor.core.model import Track # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
def encode(path: Path, codec: str, fmt: str, sr: int = 44100, container_options=None, bit_rate=320_000):
|
||||
"""Two seconds of a click at 1.0 s — enough for a header; content is irrelevant."""
|
||||
n = 2 * sr
|
||||
x = np.zeros((2, n), dtype=np.float32)
|
||||
x[:, sr:sr + 64] = 0.8
|
||||
with av.open(str(path), "w", format=fmt, options=container_options or {}) as c:
|
||||
s = c.add_stream(codec, rate=sr, layout="stereo")
|
||||
if bit_rate and codec != "pcm_s16le":
|
||||
s.bit_rate = bit_rate
|
||||
step = s.codec_context.frame_size or 1024
|
||||
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)
|
||||
|
||||
|
||||
def add_big_id3(path: Path):
|
||||
from mutagen.id3 import APIC, ID3, TIT2
|
||||
|
||||
tags = ID3()
|
||||
tags.add(TIT2(encoding=3, text="timebase"))
|
||||
tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=os.urandom(1_000_000)))
|
||||
tags.save(str(path))
|
||||
|
||||
|
||||
tmp = Path(tempfile.mkdtemp(prefix="konduktor-timebase-"))
|
||||
XING = tmp / "xing.mp3"
|
||||
NOXING = tmp / "noxing.mp3"
|
||||
MP3_48K = tmp / "48k.mp3"
|
||||
WAV = tmp / "plain.wav"
|
||||
encode(XING, "libmp3lame", "mp3")
|
||||
add_big_id3(XING)
|
||||
encode(NOXING, "libmp3lame", "mp3", container_options={"write_xing": "0"})
|
||||
encode(MP3_48K, "libmp3lame", "mp3", sr=48000)
|
||||
encode(WAV, "pcm_s16le", "wav")
|
||||
|
||||
print("== 1. mp3_gapless reads the first frame ==")
|
||||
x = mp3_gapless.read(XING)
|
||||
check("the header frame is found after a 1 MB ID3 tag", x is not None and x.header_frame, str(x))
|
||||
check("…with LAME's 576-sample encoder delay", x is not None and x.encoder_delay == 576, str(x))
|
||||
check("…in an MPEG-1 frame of 1152 samples", x is not None and x.samples_per_frame == 1152 and x.sample_rate == 44100)
|
||||
n = mp3_gapless.read(NOXING)
|
||||
check("a header-less MP3 has no header frame", n is not None and not n.header_frame, str(n))
|
||||
check("a missing file reads as None (and is not cached as header-less)",
|
||||
mp3_gapless.read(tmp / "gone.mp3") is None)
|
||||
|
||||
print("== 1b. timebase.offset ==")
|
||||
check("MP3 with a header: 2257 samples", timebase.offset_samples(XING) == (2257, 44100), str(timebase.offset_samples(XING)))
|
||||
check("…which is 51.18 ms at 44.1 kHz", abs(timebase.offset_ms(XING) - 51.179138) < 1e-6, str(timebase.offset_ms(XING)))
|
||||
check("48 kHz: the same 2257 SAMPLES, i.e. 47.02 ms",
|
||||
timebase.offset_samples(MP3_48K) == (2257, 48000) and abs(timebase.offset_ms(MP3_48K) - 47.020833) < 1e-6,
|
||||
str(timebase.offset_samples(MP3_48K)))
|
||||
check("header-less MP3: 0", timebase.offset_ms(NOXING) == 0.0)
|
||||
check("WAV: 0", timebase.offset_ms(WAV) == 0.0)
|
||||
check("a missing MP3: 0", timebase.offset_ms(tmp / "gone.mp3") == 0.0)
|
||||
|
||||
print("== 2. the store adds it on write, the projection subtracts it on read ==")
|
||||
lib = tmp / "collection.nml"
|
||||
lib.write_text(SKELETON, encoding="utf-8")
|
||||
ad = TraktorAdapter(lib)
|
||||
ids = dict(zip(("xing", "noxing", "wav"), ad.add_tracks([
|
||||
NewTrack(track=Track(id="", title=p.stem), audio_path=p, cues=None) for p in (XING, NOXING, WAV)
|
||||
])))
|
||||
OFF = 2257 / 44.1 # ms
|
||||
|
||||
|
||||
def native(tid):
|
||||
return ad.store.model_entry(tid)
|
||||
|
||||
|
||||
def cue_start_ms(tid, slot):
|
||||
return next(c.start for c in native(tid).cue_v2 if c.hotcue == slot)
|
||||
|
||||
|
||||
def marker_starts_ms(tid):
|
||||
return sorted(c.start for c in native(tid).cue_v2 if c.grid is not None)
|
||||
|
||||
|
||||
for key, off in (("xing", OFF), ("noxing", 0.0), ("wav", 0.0)):
|
||||
tid = ids[key]
|
||||
tc = ad.set_cue(tid, slot=0, start_sec=1.0, cue_type="cue")
|
||||
check(f"{key}: a cue at 1.000 s is stored at START {1000 + off:.6f}",
|
||||
abs(cue_start_ms(tid, 0) - (1000 + off)) < 1e-9, str(cue_start_ms(tid, 0)))
|
||||
check(f"{key}: …and reads back at 1.000 s", abs(tc.cues[0].start - 1.0) < 1e-12, str(tc.cues[0].start))
|
||||
|
||||
tid = ids["xing"]
|
||||
tc = ad.replace_grid(tid, [(0.5, 120.0), (1.5, 126.0)])
|
||||
check("replace_grid shifts every marker", marker_starts_ms(tid) == [500 + OFF, 1500 + OFF], str(marker_starts_ms(tid)))
|
||||
check("…and the projection undoes it", [round(m.start, 9) for m in tc.grid_markers] == [0.5, 1.5])
|
||||
tc = ad.move_grid_marker(tid, 0, 0.25)
|
||||
check("move_grid_marker shifts", abs(marker_starts_ms(tid)[0] - (250 + OFF)) < 1e-9, str(marker_starts_ms(tid)))
|
||||
tc = ad.add_grid_marker(tid, 1.0)
|
||||
check("add_grid_marker shifts", abs(marker_starts_ms(tid)[1] - (1000 + OFF)) < 1e-9, str(marker_starts_ms(tid)))
|
||||
tc = ad.set_analysed_grid(tid, [(0.75, 124.0)])
|
||||
comp = tc.grid_markers[0].companion
|
||||
check("the analysed grid's companion sits on its marker",
|
||||
comp is not None and abs(cue_start_ms(tid, comp) - marker_starts_ms(tid)[0]) < 1e-9,
|
||||
f"slot {comp}, markers {marker_starts_ms(tid)}")
|
||||
|
||||
# A grid Traktor anchored INSIDE the header frame (the real collection has an
|
||||
# AutoGrid at 21 ms): in decoded time it lies before the audio starts. It must
|
||||
# read as a negative position, and the deck's Reset — which sends the markers
|
||||
# back exactly as it loaded them — must leave the bytes alone. (No companion:
|
||||
# Reset's `replace_grid` drops the old grid's companions by design.)
|
||||
ad.delete_grid(tid)
|
||||
for c in list(ad.track_cues(tid).cues):
|
||||
ad.delete_cue(tid, c.slot)
|
||||
ad.replace_grid(tid, [(0.0, 172.0)])
|
||||
ad.set_cue(tid, slot=3, start_sec=0.0, cue_type="cue")
|
||||
for c in native(tid).cue_v2: # as Traktor wrote them, both inside the header frame
|
||||
c.start = 20.979167 if c.grid is not None else 33.5
|
||||
ad.store._sort_cues(native(tid)) # as a real file would be ordered
|
||||
ad.store._sync_tempo(native(tid))
|
||||
before = ad.snapshot()
|
||||
tc = ad.track_cues(tid)
|
||||
check("a Traktor anchor inside the header frame reads as negative, unclamped",
|
||||
abs(tc.grid_markers[0].start - (20.979167 - OFF) / 1000) < 1e-12, str(tc.grid_markers[0].start))
|
||||
check("…as does a cue there", abs(tc.cues[0].start - (33.5 - OFF) / 1000) < 1e-12, str(tc.cues[0].start))
|
||||
ad.replace_grid(tid, [(m.start, m.bpm) for m in tc.grid_markers])
|
||||
ad.set_cue(tid, slot=3, start_sec=tc.cues[0].start, cue_type="cue")
|
||||
check("…and writing the loaded grid and cue straight back is byte-identical", ad.snapshot() == before)
|
||||
|
||||
ad.save()
|
||||
re_ad = TraktorAdapter(lib)
|
||||
check("positions survive a save and reopen",
|
||||
abs(re_ad.track_cues(tid).grid_markers[0].start - (20.979167 - OFF) / 1000) < 1e-9)
|
||||
(tmp / "xing.mp3").rename(tmp / "xing-moved.mp3")
|
||||
gone = TraktorAdapter(lib).track_cues(tid)
|
||||
check("with the file gone the offset is 0 (the raw START)",
|
||||
abs(gone.grid_markers[0].start - 0.020979167) < 1e-12, str(gone.grid_markers[0].start))
|
||||
|
||||
print("== 3. Traktor's own hand-placed cues land on the kick (kit 4) ==")
|
||||
KIT = Path.home() / "Music/Konduktor Stem Test/Kit 4"
|
||||
NML = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
|
||||
if not (KIT.is_dir() and NML.is_file()):
|
||||
print(" (skipped: kit 4 or the local Traktor collection is not on this machine)")
|
||||
else:
|
||||
xml = NML.read_text(encoding="utf-8")
|
||||
seen = 0
|
||||
for m in re.finditer(r"<ENTRY [^>]*>.*?</ENTRY>", xml, re.S):
|
||||
e = m.group(0)
|
||||
if "Kit 4" not in e:
|
||||
continue
|
||||
name = re.search(r'FILE="([^"]*)"', e).group(1)
|
||||
pad8 = re.search(r'<CUE_V2 [^>]*START="([^"]*)"[^>]*HOTCUE="7"', e)
|
||||
if not pad8 or not (KIT / name).is_file():
|
||||
continue
|
||||
with av.open(str(KIT / name), metadata_errors="ignore") as c:
|
||||
st = c.streams.audio[0]
|
||||
sr = st.rate
|
||||
y = np.concatenate([f.to_ndarray()[0] for f in c.decode(st)]).astype(np.float64)
|
||||
a = int(8.9 * sr)
|
||||
onset = (a + int(np.argmax(np.abs(y[a:a + int(0.2 * sr)]) > 0.05))) / sr
|
||||
decoded = timebase.from_traktor_ms(float(pad8.group(1)), timebase.offset_ms(KIT / name))
|
||||
err = (decoded - onset) * 1000
|
||||
seen += 1
|
||||
check(f"{name}: a cue placed in Traktor reads back on the kick (±1 ms)", abs(err) < 1.0, f"{err:+.2f} ms")
|
||||
if not seen:
|
||||
print(" (skipped: no hand-placed pad-8 cues in kit 4)")
|
||||
|
||||
print("== 4. rekordbox's clock is per file too (Pioneer timebase) ==")
|
||||
from konduktor.adapters.rekordbox import beatgrid as pioneer_grid # noqa: E402
|
||||
from konduktor.adapters.rekordbox import timebase as pioneer # noqa: E402
|
||||
from konduktor.core import mp4_edit # noqa: E402
|
||||
from konduktor.core.model import GridMarker # noqa: E402
|
||||
|
||||
(tmp / "xing-moved.mp3").rename(XING) # section 2 moved it away
|
||||
AAC = tmp / "ffmpeg.m4a"
|
||||
encode(AAC, "aac", "ipod", bit_rate=256_000)
|
||||
check("an FFmpeg AAC's edit list primes 1024 samples", mp4_edit.priming_seconds(AAC) == 1024 / 44100,
|
||||
str(mp4_edit.priming_seconds(AAC)))
|
||||
check("MP3 with a header: the trimmed 1105 samples", abs(pioneer.offset(XING) - 1105 / 44100) < 1e-12)
|
||||
check("MP3 at 48 kHz: 1105 SAMPLES", abs(pioneer.offset(MP3_48K) - 1105 / 48000) < 1e-12)
|
||||
check("MP3 without a header: 0 (nothing is trimmed)", pioneer.offset(NOXING) == 0.0)
|
||||
check("AAC: the edit list's priming (rekordbox ignores it)", pioneer.offset(AAC) == 1024 / 44100)
|
||||
if "aac_at" in av.codecs_available:
|
||||
APPLE = tmp / "apple.m4a"
|
||||
encode(APPLE, "aac_at", "ipod", bit_rate=256_000)
|
||||
check("Apple AAC: 2112 samples of priming", pioneer.offset(APPLE) == 2112 / 44100, str(pioneer.offset(APPLE)))
|
||||
check("WAV: 0", pioneer.offset(WAV) == 0.0)
|
||||
check("an unreadable MP3 keeps the old 1105-sample default",
|
||||
abs(pioneer.offset(tmp / "offline.mp3") - 1105 / 44100) < 1e-12)
|
||||
check("no path: 0", pioneer.offset(None) == 0.0)
|
||||
check("a position before the decoded audio clamps to rekordbox's 0 on write",
|
||||
pioneer.to_pioneer(-0.030, 1105 / 44100) == 0.0)
|
||||
|
||||
# A Traktor grid anchored inside the header frame reads NEGATIVE; expanding it
|
||||
# for a Pioneer export must drop the beats before 0 — and number the rest as
|
||||
# if nothing had been dropped, or every bar would start on the wrong beat.
|
||||
nums, _bpms, times = pioneer_grid.beats_from_markers([GridMarker(start=-0.030, bpm=120.0)], 3.0)
|
||||
check("no beat before 0 is written", min(times) >= 0.0, str(times[:3]))
|
||||
check("the first kept beat is beat 2 of the bar, 0.47 s in",
|
||||
nums[0] == 2 and abs(times[0] - 0.47) < 1e-9, f"{nums[:4]} {times[:2]}")
|
||||
|
||||
print("== 5. rekordbox's own hand-placed cues land on the kick (kit 4) ==")
|
||||
MASTER = Path.home() / "Library/Pioneer/rekordbox/master.db"
|
||||
if not (KIT.is_dir() and MASTER.is_file()):
|
||||
print(" (skipped: kit 4 or the local rekordbox library is not on this machine)")
|
||||
else:
|
||||
from pyrekordbox.masterdb import MasterDatabase # noqa: E402
|
||||
|
||||
seen = 0
|
||||
db = MasterDatabase(MASTER)
|
||||
try:
|
||||
for c in db.get_cue():
|
||||
name = c.Content.FileNameL if c.Content else ""
|
||||
if not name.startswith("K4-") or c.Kind != 9 or not (KIT / name).is_file():
|
||||
continue # pad H: the ones placed by hand
|
||||
with av.open(str(KIT / name), metadata_errors="ignore") as con:
|
||||
st = con.streams.audio[0]
|
||||
sr = st.rate
|
||||
y = np.concatenate([f.to_ndarray()[0] for f in con.decode(st)]).astype(np.float64)
|
||||
a = int(8.9 * sr)
|
||||
onset = (a + int(np.argmax(np.abs(y[a:a + int(0.2 * sr)]) > 0.05))) / sr
|
||||
decoded = pioneer.from_pioneer(c.InMsec / 1000, pioneer.offset(KIT / name))
|
||||
err = (decoded - onset) * 1000
|
||||
seen += 1
|
||||
# rekordbox stores whole milliseconds, apparently truncated.
|
||||
check(f"{name}: a cue placed in rekordbox reads back on the kick (±1.5 ms)", abs(err) < 1.5,
|
||||
f"{err:+.2f} ms")
|
||||
finally:
|
||||
db.close()
|
||||
if not seen:
|
||||
print(" (skipped: no hand-placed pad-H cues in kit 4)")
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -86,6 +86,8 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("8 hotcue slots", caps.cues.hotcue_slots == 8)
|
||||
check("no memory cues on Traktor", caps.cues.memory_cues is False)
|
||||
check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type")
|
||||
# Traktor colours a cue by its type, so no colour picker may be offered.
|
||||
check("no cue colours to pick", caps.cues.color == "none" and caps.cues.palette == [])
|
||||
check("flexible beatgrids supported", caps.grid.flexible is True)
|
||||
check("grid is lockable", caps.grid.lockable is True)
|
||||
check("save facts present for the UI to compose copy from",
|
||||
@@ -127,6 +129,11 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("memory cues are refused on Traktor", False, "no error raised")
|
||||
except Unsupported:
|
||||
check("memory cues are refused on Traktor", True)
|
||||
try:
|
||||
adapter.set_cue_color(tid2, free, "#FF0000")
|
||||
check("cue colour is refused on Traktor", False, "no error raised")
|
||||
except Unsupported:
|
||||
check("cue colour is refused on Traktor", True)
|
||||
|
||||
# grid
|
||||
grid_before = len(adapter.track_cues(tid2).grid_markers)
|
||||
@@ -136,6 +143,42 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("marker count reached the track projection",
|
||||
adapter.track(tid2).grid_marker_count == grid_before + 1)
|
||||
|
||||
# ---- "Comment 2" ----------------------------------------------------------
|
||||
# Traktor keeps it in INFO@RATING — a free-text attribute despite its name; the
|
||||
# stars are RANKING. Mixing the two up would corrupt either field silently.
|
||||
print("== Comment 2 is INFO@RATING, collection-only ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
adapter = TraktorAdapter(work)
|
||||
|
||||
with_c2 = [t for t in adapter.tracks if t.comment2]
|
||||
check("real Comment 2 values are projected", len(with_c2) > 0, "none found")
|
||||
check("comment2 is advertised as editable",
|
||||
"comment2" in adapter.capabilities().tracks.editable_fields)
|
||||
|
||||
t = next(t for t in adapter.tracks if t.title and t.rating and not t.comment2)
|
||||
adapter.set_track_metadata(t.id, {"comment2": "Konduktor C2"})
|
||||
after = adapter.track(t.id)
|
||||
check("comment2 edit is visible in the projection", after.comment2 == "Konduktor C2")
|
||||
check("comment2 edit leaves the star rating alone", after.rating == t.rating)
|
||||
outcome = adapter.save()
|
||||
check("comment2 alone writes no file tags", not outcome.tag_results,
|
||||
str(outcome.tag_results))
|
||||
text = work.read_text(encoding="utf-8")
|
||||
check("stored as INFO RATING", 'RATING="Konduktor C2"' in text)
|
||||
reopened = TraktorAdapter(work).track(t.id)
|
||||
check("comment2 round-trips through save",
|
||||
reopened.comment2 == "Konduktor C2" and reopened.rating == t.rating)
|
||||
|
||||
# Clearing it removes the attribute entirely.
|
||||
a2 = TraktorAdapter(work)
|
||||
a2.set_track_metadata(t.id, {"comment2": ""})
|
||||
a2.save()
|
||||
check("clearing comment2 drops the attribute",
|
||||
'RATING="Konduktor C2"' not in work.read_text(encoding="utf-8")
|
||||
and TraktorAdapter(work).track(t.id).comment2 is None)
|
||||
|
||||
# ---- analysed grid vs plain replace --------------------------------------
|
||||
print("== set_analysed_grid writes Traktor's own shape, replace_grid does not ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
|
||||
+17
-12
@@ -1,15 +1,20 @@
|
||||
<svg viewBox="0 0 100 100" width="1024" height="1024" xmlns="http://www.w3.org/2000/svg" shape-rendering="geometricPrecision">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="1024" height="1024">
|
||||
<defs>
|
||||
<linearGradient id="bg_k" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#1a1524"/><stop offset="1" stop-color="#06060c"/></linearGradient>
|
||||
<linearGradient id="sheen_k" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff" stop-opacity="0.14"/><stop offset="0.45" stop-color="#fff" stop-opacity="0"/></linearGradient>
|
||||
<radialGradient id="vig_k" cx="0.5" cy="0.42" r="0.75"><stop offset="0.55" stop-color="#000" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity="0.45"/></radialGradient>
|
||||
<filter id="glow_k" x="-30%" y="-30%" width="160%" height="160%"><feGaussianBlur stdDeviation="1.3" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge></filter>
|
||||
<linearGradient id="b_k_0" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffb5a0"/><stop offset="0.55" stop-color="#ff5a2c"/><stop offset="1" stop-color="#e04f27"/></linearGradient><linearGradient id="b_k_1" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#f9b2ad"/><stop offset="0.55" stop-color="#f25448"/><stop offset="1" stop-color="#d54a3f"/></linearGradient><linearGradient id="b_k_2" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#f4afba"/><stop offset="0.55" stop-color="#e64d65"/><stop offset="1" stop-color="#ca4459"/></linearGradient><linearGradient id="b_k_3" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#eeacc6"/><stop offset="0.55" stop-color="#d94781"/><stop offset="1" stop-color="#bf3e72"/></linearGradient><linearGradient id="b_k_4" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#e8aad3"/><stop offset="0.55" stop-color="#cc419d"/><stop offset="1" stop-color="#b4398a"/></linearGradient><linearGradient id="b_k_5" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#e2a7e0"/><stop offset="0.55" stop-color="#bf3bb9"/><stop offset="1" stop-color="#a834a3"/></linearGradient><linearGradient id="b_k_6" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#dda4ed"/><stop offset="0.55" stop-color="#b334d6"/><stop offset="1" stop-color="#9e2ebc"/></linearGradient><linearGradient id="b_k_7" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#d7a1f9"/><stop offset="0.55" stop-color="#a62ef2"/><stop offset="1" stop-color="#9228d5"/></linearGradient><linearGradient id="b_k_8" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#cfa9fa"/><stop offset="0.55" stop-color="#943ff4"/><stop offset="1" stop-color="#8237d7"/></linearGradient><linearGradient id="b_k_9" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#c6b0fb"/><stop offset="0.55" stop-color="#8150f6"/><stop offset="1" stop-color="#7246d8"/></linearGradient><linearGradient id="b_k_10" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#beb8fc"/><stop offset="0.55" stop-color="#6f61f8"/><stop offset="1" stop-color="#6255da"/></linearGradient><linearGradient id="b_k_11" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#b6c0fc"/><stop offset="0.55" stop-color="#5d73f9"/><stop offset="1" stop-color="#5265db"/></linearGradient><linearGradient id="b_k_12" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#aec8fd"/><stop offset="0.55" stop-color="#4b84fb"/><stop offset="1" stop-color="#4274dd"/></linearGradient><linearGradient id="b_k_13" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#a5cffe"/><stop offset="0.55" stop-color="#3895fd"/><stop offset="1" stop-color="#3183df"/></linearGradient><linearGradient id="b_k_14" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#9dd7ff"/><stop offset="0.55" stop-color="#26a6ff"/><stop offset="1" stop-color="#2192e0"/></linearGradient>
|
||||
<clipPath id="sbc"><rect x="2" y="2" width="96" height="96" rx="22"/></clipPath>
|
||||
<filter id="sbblur" filterUnits="userSpaceOnUse" x="-60" y="-60" width="220" height="220"><feGaussianBlur stdDeviation="13"/></filter>
|
||||
<filter id="sbglow" filterUnits="userSpaceOnUse" x="-20" y="-20" width="140" height="140"><feGaussianBlur stdDeviation="1.6" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge></filter>
|
||||
<filter id="sbshadow" filterUnits="userSpaceOnUse" x="-20" y="-20" width="140" height="140"><feGaussianBlur stdDeviation="2.2"/></filter>
|
||||
<filter id="sbbigglow" filterUnits="userSpaceOnUse" x="-20" y="-20" width="140" height="140"><feGaussianBlur stdDeviation="4"/></filter>
|
||||
<linearGradient id="sbsheen" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff" stop-opacity=".16"/><stop offset=".42" stop-color="#fff" stop-opacity="0"/></linearGradient>
|
||||
<linearGradient id="sbrim" x1="0" y1="0" x2="0.4" y2="1"><stop offset="0" stop-color="#fff" stop-opacity=".55"/><stop offset=".5" stop-color="#fff" stop-opacity=".08"/><stop offset="1" stop-color="#fff" stop-opacity=".22"/></linearGradient>
|
||||
<linearGradient id="sbspec" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#ff8a3d"/><stop offset=".5" stop-color="#8f6bff"/><stop offset="1" stop-color="#5ee7ff"/></linearGradient>
|
||||
</defs>
|
||||
<rect x="2" y="2" width="96" height="96" rx="22" fill="url(#bg_k)"/>
|
||||
<g filter="url(#glow_k)"><rect x="22.00" y="42.90" width="2.33" height="16.20" rx="1.17" fill="url(#b_k_0)"/><rect x="25.83" y="37.50" width="2.33" height="27.00" rx="1.17" fill="url(#b_k_1)"/><rect x="29.67" y="40.20" width="2.33" height="21.60" rx="1.17" fill="url(#b_k_2)"/><rect x="33.50" y="33.18" width="2.33" height="35.64" rx="1.17" fill="url(#b_k_3)"/><rect x="37.33" y="27.78" width="2.33" height="46.44" rx="1.17" fill="url(#b_k_4)"/><rect x="41.17" y="35.88" width="2.33" height="30.24" rx="1.17" fill="url(#b_k_5)"/><rect x="45.00" y="24.00" width="2.33" height="54.00" rx="1.17" fill="url(#b_k_6)"/><rect x="48.83" y="32.10" width="2.33" height="37.80" rx="1.17" fill="url(#b_k_7)"/><rect x="52.67" y="26.70" width="2.33" height="48.60" rx="1.17" fill="url(#b_k_8)"/><rect x="56.50" y="37.50" width="2.33" height="27.00" rx="1.17" fill="url(#b_k_9)"/><rect x="60.33" y="31.56" width="2.33" height="38.88" rx="1.17" fill="url(#b_k_10)"/><rect x="64.17" y="39.66" width="2.33" height="22.68" rx="1.17" fill="url(#b_k_11)"/><rect x="68.00" y="34.80" width="2.33" height="32.40" rx="1.17" fill="url(#b_k_12)"/><rect x="71.83" y="41.28" width="2.33" height="19.44" rx="1.17" fill="url(#b_k_13)"/><rect x="75.67" y="43.98" width="2.33" height="14.04" rx="1.17" fill="url(#b_k_14)"/></g>
|
||||
<rect x="48.10" y="14" width="3.80" height="72" rx="1.90" fill="#000" fill-opacity="0.42"/><rect x="48.70" y="14.5" width="2.60" height="71" rx="1.30" fill="#ff3b30"/><path d="M 46.30 13 L 53.70 13 L 50.00 19 Z" fill="#ffb020"/>
|
||||
<rect x="2" y="2" width="96" height="96" rx="22" fill="url(#vig_k)"/>
|
||||
<rect x="2" y="2" width="96" height="96" rx="22" fill="url(#sheen_k)"/>
|
||||
<rect x="2.5" y="2.5" width="95" height="95" rx="21.5" fill="none" stroke="#fff" stroke-opacity="0.08"/>
|
||||
<g clip-path="url(#sbc)">
|
||||
<rect width="100" height="100" fill="#07070d"/>
|
||||
<g filter="url(#sbblur)"><circle cx="22" cy="18" r="32" fill="#6d4aff"/><circle cx="90" cy="28" r="26" fill="#e0409a"/><circle cx="76" cy="96" r="32" fill="#12b5c9"/><circle cx="8" cy="82" r="26" fill="#2f3fe0"/></g>
|
||||
<rect width="100" height="100" fill="#05060a" opacity="0.5"/>
|
||||
<g filter="url(#sbglow)"><g style="mix-blend-mode:normal"><rect x="20.00" y="43.22" width="2.4" height="13.56" fill="#ff6a3d" fill-opacity="0.95"/><rect x="23.50" y="37.12" width="2.4" height="25.76" fill="#ff6a3d" fill-opacity="0.95"/><rect x="27.00" y="40.84" width="2.4" height="18.32" fill="#ff6a3d" fill-opacity="0.95"/><rect x="30.50" y="30.18" width="2.4" height="39.65" fill="#ff6a3d" fill-opacity="0.95"/><rect x="34.00" y="26.93" width="2.4" height="46.14" fill="#ff6a3d" fill-opacity="0.95"/><rect x="37.50" y="33.53" width="2.4" height="32.94" fill="#ff6a3d" fill-opacity="0.95"/><rect x="41.00" y="21.71" width="2.4" height="56.58" fill="#ff6a3d" fill-opacity="0.95"/><rect x="44.50" y="29.10" width="2.4" height="41.79" fill="#ff6a3d" fill-opacity="0.95"/><rect x="48.00" y="19.35" width="2.4" height="61.31" fill="#ff6a3d" fill-opacity="0.95"/><rect x="51.50" y="31.09" width="2.4" height="37.82" fill="#ff6a3d" fill-opacity="0.95"/><rect x="55.00" y="23.49" width="2.4" height="53.01" fill="#ff6a3d" fill-opacity="0.95"/><rect x="58.50" y="36.55" width="2.4" height="26.90" fill="#ff6a3d" fill-opacity="0.95"/><rect x="62.00" y="26.90" width="2.4" height="46.20" fill="#ff6a3d" fill-opacity="0.95"/><rect x="65.50" y="26.31" width="2.4" height="47.37" fill="#ff6a3d" fill-opacity="0.95"/><rect x="69.00" y="31.79" width="2.4" height="36.41" fill="#ff6a3d" fill-opacity="0.95"/><rect x="72.50" y="39.61" width="2.4" height="20.78" fill="#ff6a3d" fill-opacity="0.95"/><rect x="76.00" y="42.64" width="2.4" height="14.71" fill="#ff6a3d" fill-opacity="0.95"/></g><g style="mix-blend-mode:normal"><rect x="20.00" y="44.59" width="2.4" height="10.81" fill="#8f6bff" fill-opacity="0.95"/><rect x="23.50" y="41.35" width="2.4" height="17.30" fill="#8f6bff" fill-opacity="0.95"/><rect x="27.00" y="42.55" width="2.4" height="14.89" fill="#8f6bff" fill-opacity="0.95"/><rect x="30.50" y="35.66" width="2.4" height="28.67" fill="#8f6bff" fill-opacity="0.95"/><rect x="34.00" y="31.37" width="2.4" height="37.26" fill="#8f6bff" fill-opacity="0.95"/><rect x="37.50" y="37.11" width="2.4" height="25.79" fill="#8f6bff" fill-opacity="0.95"/><rect x="41.00" y="27.44" width="2.4" height="45.12" fill="#8f6bff" fill-opacity="0.95"/><rect x="44.50" y="32.98" width="2.4" height="34.04" fill="#8f6bff" fill-opacity="0.95"/><rect x="48.00" y="26.59" width="2.4" height="46.82" fill="#8f6bff" fill-opacity="0.95"/><rect x="51.50" y="34.37" width="2.4" height="31.27" fill="#8f6bff" fill-opacity="0.95"/><rect x="55.00" y="31.11" width="2.4" height="37.79" fill="#8f6bff" fill-opacity="0.95"/><rect x="58.50" y="38.98" width="2.4" height="22.03" fill="#8f6bff" fill-opacity="0.95"/><rect x="62.00" y="34.95" width="2.4" height="30.11" fill="#8f6bff" fill-opacity="0.95"/><rect x="65.50" y="32.51" width="2.4" height="34.98" fill="#8f6bff" fill-opacity="0.95"/><rect x="69.00" y="37.96" width="2.4" height="24.08" fill="#8f6bff" fill-opacity="0.95"/><rect x="72.50" y="41.76" width="2.4" height="16.48" fill="#8f6bff" fill-opacity="0.95"/><rect x="76.00" y="44.36" width="2.4" height="11.28" fill="#8f6bff" fill-opacity="0.95"/></g><g style="mix-blend-mode:normal"><rect x="20.00" y="45.65" width="2.4" height="8.70" fill="#3f9dff" fill-opacity="0.95"/><rect x="23.50" y="42.45" width="2.4" height="15.11" fill="#3f9dff" fill-opacity="0.95"/><rect x="27.00" y="43.90" width="2.4" height="12.20" fill="#3f9dff" fill-opacity="0.95"/><rect x="30.50" y="39.81" width="2.4" height="20.39" fill="#3f9dff" fill-opacity="0.95"/><rect x="34.00" y="35.55" width="2.4" height="28.90" fill="#3f9dff" fill-opacity="0.95"/><rect x="37.50" y="40.97" width="2.4" height="18.07" fill="#3f9dff" fill-opacity="0.95"/><rect x="41.00" y="34.28" width="2.4" height="31.43" fill="#3f9dff" fill-opacity="0.95"/><rect x="44.50" y="37.23" width="2.4" height="25.53" fill="#3f9dff" fill-opacity="0.95"/><rect x="48.00" y="35.03" width="2.4" height="29.94" fill="#3f9dff" fill-opacity="0.95"/><rect x="51.50" y="38.15" width="2.4" height="23.71" fill="#3f9dff" fill-opacity="0.95"/><rect x="55.00" y="35.35" width="2.4" height="29.30" fill="#3f9dff" fill-opacity="0.95"/><rect x="58.50" y="42.01" width="2.4" height="15.99" fill="#3f9dff" fill-opacity="0.95"/><rect x="62.00" y="36.90" width="2.4" height="26.20" fill="#3f9dff" fill-opacity="0.95"/><rect x="65.50" y="35.07" width="2.4" height="29.85" fill="#3f9dff" fill-opacity="0.95"/><rect x="69.00" y="40.36" width="2.4" height="19.29" fill="#3f9dff" fill-opacity="0.95"/><rect x="72.50" y="43.00" width="2.4" height="14.01" fill="#3f9dff" fill-opacity="0.95"/><rect x="76.00" y="45.71" width="2.4" height="8.59" fill="#3f9dff" fill-opacity="0.95"/></g><g style="mix-blend-mode:normal"><rect x="20.00" y="46.81" width="2.4" height="6.38" fill="#7fe6ff" fill-opacity="0.9"/><rect x="23.50" y="44.91" width="2.4" height="10.19" fill="#7fe6ff" fill-opacity="0.9"/><rect x="27.00" y="45.79" width="2.4" height="8.41" fill="#7fe6ff" fill-opacity="0.9"/><rect x="30.50" y="43.27" widthLine truncated
|
||||
<rect width="100" height="100" fill="url(#sbsheen)"/>
|
||||
</g>
|
||||
<rect x="2.4" y="2.4" width="95.2" height="95.2" rx="21.6" fill="none" stroke="url(#sbrim)" stroke-width=".8"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 8.4 KiB |
@@ -0,0 +1,7 @@
|
||||
"""PyInstaller entry point for the frozen stem engine (`konduktor-engine`)."""
|
||||
import sys
|
||||
|
||||
from konduktor_engine.__main__ import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Fetch and verify the pinned htdemucs_ft weights into a folder (CI, dev).
|
||||
|
||||
python fetch_weights.py DEST
|
||||
|
||||
Standard library only. Files already present with the right hash are kept.
|
||||
Konduktor itself downloads through its engine manager, from the same manifest.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
MANIFEST = json.loads((Path(__file__).resolve().parent / "weights.json").read_text())
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def main(dest: str) -> int:
|
||||
folder = Path(dest)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
for f in MANIFEST["files"]:
|
||||
target = folder / f["name"]
|
||||
if target.exists() and sha256(target) == f["sha256"]:
|
||||
print(f"ok {f['name']}")
|
||||
continue
|
||||
url = MANIFEST["url"].format(repo=MANIFEST["repo"], revision=MANIFEST["revision"], name=f["name"])
|
||||
partial = target.with_name(target.name + ".part")
|
||||
with urllib.request.urlopen(url, timeout=60) as r, open(partial, "wb") as out:
|
||||
while chunk := r.read(1 << 20):
|
||||
out.write(chunk)
|
||||
got = sha256(partial)
|
||||
if got != f["sha256"]:
|
||||
partial.unlink()
|
||||
print(f"HASH MISMATCH {f['name']}: {got}")
|
||||
return 1
|
||||
partial.replace(target)
|
||||
print(f"fetched {f['name']}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1]))
|
||||
@@ -0,0 +1,37 @@
|
||||
# PyInstaller spec for the frozen stem engine. ONEDIR, not onefile: a onefile
|
||||
# build re-extracts ~500 MB of torch into a temp folder on EVERY launch; the
|
||||
# folder is instead unpacked once, into app-data, by Konduktor's engine manager.
|
||||
#
|
||||
# .venv/bin/python -m PyInstaller --noconfirm --clean konduktor-engine.spec
|
||||
from PyInstaller.utils.hooks import collect_submodules
|
||||
|
||||
hidden = collect_submodules("demucs")
|
||||
|
||||
a = Analysis(
|
||||
["engine_main.py"],
|
||||
pathex=["."],
|
||||
hiddenimports=hidden,
|
||||
excludes=[
|
||||
# Never used for inference, and large.
|
||||
"tkinter", "matplotlib", "IPython", "notebook", "tensorboard",
|
||||
"torchvision", "torchaudio", "PIL",
|
||||
# The engine never goes online: Konduktor downloads the weights.
|
||||
"huggingface_hub", "hf_xet",
|
||||
],
|
||||
)
|
||||
# torch ships C++ headers (tens of MB, thousands of files) that only matter for
|
||||
# building extensions; they are also the deepest paths in the tree, which is
|
||||
# what trips Windows' 260-character limit.
|
||||
a.datas = [d for d in a.datas if "/include/" not in d[0].replace("\\", "/")
|
||||
and not d[0].replace("\\", "/").startswith("torch/include")]
|
||||
pyz = PYZ(a.pure)
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
[],
|
||||
exclude_binaries=True,
|
||||
name="konduktor-engine",
|
||||
console=True,
|
||||
upx=False,
|
||||
)
|
||||
coll = COLLECT(exe, a.binaries, a.datas, name="konduktor-engine", upx=False)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Konduktor's stem engine: Demucs htdemucs_ft behind a small process protocol.
|
||||
|
||||
A separate program from Konduktor's backend — it carries torch, which the
|
||||
backend deliberately does not — built and released on its own channel
|
||||
(`engine-v*`) and downloaded on first use. It imports nothing from `konduktor`.
|
||||
"""
|
||||
|
||||
#: Bumped whenever the engine's behaviour or protocol changes; the app names the
|
||||
#: engine version it needs.
|
||||
VERSION = "1.0.0"
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Command line: `info` and a one-shot `separate`.
|
||||
|
||||
Audio crosses as RAW planar float32 files — shape (2, n), C order — rather than
|
||||
WAV: nothing to parse, `np.fromfile`/`memmap` either side, and no clamping (a
|
||||
mastered track decodes above 0 dBFS as float, and its stems may too).
|
||||
|
||||
Protocol output is JSON lines on stdout; everything else (torch and demucs
|
||||
print) goes to stderr, so a stray print can never corrupt a message.
|
||||
|
||||
python -m konduktor_engine info
|
||||
python -m konduktor_engine separate --input mix.f32 --samples N \\
|
||||
--output-dir OUT --weights DIR [--device auto|cpu|gpu|mps|cuda] [--seed 0]
|
||||
python -m konduktor_engine serve --weights DIR [--device auto] (see serve.py)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from . import VERSION
|
||||
|
||||
|
||||
def _protocol():
|
||||
"""A private copy of stdout for messages; `sys.stdout` becomes stderr."""
|
||||
fd = os.dup(1)
|
||||
os.dup2(2, 1)
|
||||
sys.stdout = sys.stderr
|
||||
return os.fdopen(fd, "w", buffering=1, encoding="utf-8")
|
||||
|
||||
|
||||
_EMIT = threading.Lock()
|
||||
|
||||
|
||||
def _emit(out, **msg) -> None:
|
||||
# Locked: `serve` writes from two threads, and two half-lines would be
|
||||
# one unparseable message.
|
||||
line = json.dumps(msg) + "\n"
|
||||
with _EMIT:
|
||||
out.write(line)
|
||||
out.flush()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="konduktor-engine")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
sub.add_parser("info")
|
||||
sep = sub.add_parser("separate")
|
||||
sep.add_argument("--input", required=True)
|
||||
sep.add_argument("--samples", type=int, required=True)
|
||||
sep.add_argument("--output-dir", required=True)
|
||||
sep.add_argument("--weights", required=True)
|
||||
sep.add_argument("--device", default="auto")
|
||||
sep.add_argument("--seed", type=int, default=0)
|
||||
srv = sub.add_parser("serve")
|
||||
srv.add_argument("--weights", required=True)
|
||||
srv.add_argument("--device", default="auto")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
out = _protocol()
|
||||
from . import core
|
||||
|
||||
if args.command == "info":
|
||||
import torch
|
||||
|
||||
cuda = None
|
||||
if torch.cuda.is_available():
|
||||
# What the backend needs to decide whether to offer this engine: the
|
||||
# card, its compute capability, and the capabilities torch was
|
||||
# built for (a card outside that list fails at the first kernel).
|
||||
cuda = {"name": torch.cuda.get_device_name(0),
|
||||
"capability": ".".join(map(str, torch.cuda.get_device_capability(0))),
|
||||
"arch_list": torch.cuda.get_arch_list(),
|
||||
"memory": torch.cuda.get_device_properties(0).total_memory}
|
||||
_emit(out, event="info", version=VERSION, torch=torch.__version__,
|
||||
devices=core.available_devices(), model=core.MODEL,
|
||||
cuda_build=torch.version.cuda, cuda=cuda)
|
||||
return 0
|
||||
|
||||
if args.command == "serve":
|
||||
from . import serve
|
||||
|
||||
try:
|
||||
return serve.run(out, lambda **m: _emit(out, **m), args.weights, args.device)
|
||||
except Exception as ex: # noqa: BLE001 — e.g. weights missing: say so, then exit
|
||||
_emit(out, event="error", message=f"{type(ex).__name__}: {ex}")
|
||||
return 1
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
device = core.pick_device(args.device)
|
||||
pcm = np.fromfile(args.input, dtype=np.float32)
|
||||
if pcm.size != 2 * args.samples:
|
||||
raise ValueError(f"{args.input}: expected {2 * args.samples} floats, found {pcm.size}")
|
||||
pcm = pcm.reshape(2, args.samples)
|
||||
t0 = time.time()
|
||||
model = core.load_model(args.weights)
|
||||
_emit(out, event="loaded", device=device, seconds=round(time.time() - t0, 2))
|
||||
stems = core.separate(model, pcm, device, seed=args.seed,
|
||||
on_progress=lambda f: _emit(out, event="progress", fraction=round(f, 4)))
|
||||
folder = Path(args.output_dir)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
for name, x in stems.items():
|
||||
x.tofile(folder / f"{name}.f32")
|
||||
_emit(out, event="done", seconds=round(time.time() - t0, 2), device=device)
|
||||
return 0
|
||||
except Exception as ex: # noqa: BLE001 — reported to the caller, not raised
|
||||
_emit(out, event="error", message=f"{type(ex).__name__}: {ex}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,95 @@
|
||||
"""The separation itself: htdemucs_ft over a stereo 44.1 kHz mix.
|
||||
|
||||
Kept free of I/O and protocol so the CLI (`__main__`), the frozen engine and
|
||||
the golden test all run the same code. Weights are loaded from a LOCAL folder
|
||||
(the four `.safetensors` of `adefossez/HTDemucs-ft` plus `htdemucs_ft.yaml`):
|
||||
the engine never goes online — Konduktor downloads and verifies the weights,
|
||||
since their licence rules out shipping them inside the engine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import numpy as np
|
||||
|
||||
#: Demucs' outputs, in the order the stem file stores them after the mix.
|
||||
SOURCES = ("drums", "bass", "other", "vocals")
|
||||
MODEL = "htdemucs_ft"
|
||||
SAMPLE_RATE = 44100
|
||||
#: As benchmarked (M3 Pro, 2026-09-29): one random shift, 25 % overlap.
|
||||
SHIFTS, OVERLAP = 1, 0.25
|
||||
|
||||
|
||||
def available_devices() -> list[str]:
|
||||
import torch
|
||||
|
||||
devices = ["cpu"]
|
||||
if torch.backends.mps.is_available():
|
||||
devices.insert(0, "mps")
|
||||
if torch.cuda.is_available():
|
||||
devices.insert(0, "cuda")
|
||||
return devices
|
||||
|
||||
|
||||
def pick_device(requested: str = "auto") -> str:
|
||||
"""`auto` = the fastest available; `gpu` = MPS or CUDA, else CPU."""
|
||||
devices = available_devices()
|
||||
if requested in ("auto", "gpu"):
|
||||
return devices[0]
|
||||
if requested not in devices:
|
||||
raise ValueError(f"Device {requested!r} is not available here ({', '.join(devices)})")
|
||||
return requested
|
||||
|
||||
|
||||
def load_model(weights: Path | str):
|
||||
"""The htdemucs_ft bag from a local weights folder."""
|
||||
import yaml
|
||||
from demucs.apply import BagOfModels
|
||||
from demucs.hf import load_safetensors_model
|
||||
|
||||
folder = Path(weights)
|
||||
with open(folder / f"{MODEL}.yaml", encoding="utf-8") as f:
|
||||
bag = yaml.safe_load(f)
|
||||
models = [load_safetensors_model(folder / f"{sig}.safetensors") for sig in bag["models"]]
|
||||
model = BagOfModels(models, bag.get("weights"), bag.get("segment"))
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
|
||||
def separate(model, pcm: np.ndarray, device: str, *, seed: int = 0,
|
||||
on_progress: Callable[[float], None] | None = None) -> dict[str, np.ndarray]:
|
||||
"""Four stems, each shaped like `pcm` (2, n) float32.
|
||||
|
||||
Seeded per call: `shifts=1` applies a RANDOM time shift, so without a seed
|
||||
the same track separates slightly differently each time (measured: Vox 9.2
|
||||
vs 9.6 dB SDR between runs) and a re-conversion would not be reproducible.
|
||||
The shift is drawn from Python's `random` module (`demucs.apply`:
|
||||
`random.randint`), NOT torch's generator — seeding torch alone left every
|
||||
run different — so both are seeded.
|
||||
"""
|
||||
import random
|
||||
|
||||
import torch
|
||||
from demucs.apply import apply_model
|
||||
|
||||
if pcm.ndim != 2 or pcm.shape[0] != 2:
|
||||
raise ValueError("Expected a stereo mix shaped (2, n)")
|
||||
n = pcm.shape[1]
|
||||
random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
|
||||
def callback(d: dict) -> None:
|
||||
if on_progress is None or d.get("state") != "end":
|
||||
return
|
||||
models = max(1, int(d.get("models", 1)))
|
||||
done = min(1.0, (int(d.get("segment_offset", 0)) + 1) / max(1, n))
|
||||
on_progress(min(1.0, (int(d.get("model_idx_in_bag", 0)) + done) / models))
|
||||
|
||||
mix = torch.from_numpy(np.ascontiguousarray(pcm, dtype=np.float32))[None]
|
||||
with torch.no_grad():
|
||||
out = apply_model(model, mix, shifts=SHIFTS, split=True, overlap=OVERLAP,
|
||||
progress=False, device=device, callback=callback)[0]
|
||||
out = out.cpu().numpy().astype(np.float32, copy=False)
|
||||
order = [model.sources.index(name) for name in SOURCES]
|
||||
return {name: np.ascontiguousarray(out[i]) for name, i in zip(SOURCES, order)}
|
||||
@@ -0,0 +1,137 @@
|
||||
"""`serve`: one engine process per batch, the model loaded once.
|
||||
|
||||
Requests are JSON lines on stdin, replies JSON lines on the protocol stream
|
||||
(a private copy of stdout — see `__main__._protocol`):
|
||||
|
||||
-> {"id": "t1", "cmd": "separate", "input": "mix.f32", "samples": N,
|
||||
"output_dir": "out/", "seed": 0}
|
||||
<- {"id": "t1", "event": "progress", "fraction": 0.42}
|
||||
<- {"id": "t1", "event": "done", "seconds": 61.2, "device": "mps"}
|
||||
(or "error" with "message", or "cancelled")
|
||||
-> {"cmd": "cancel", "id": "t1"} the running separation stops at its next
|
||||
progress step; the model stays loaded
|
||||
-> {"cmd": "ping"} <- {"event": "pong"}
|
||||
|
||||
**stdin closing means the parent is gone** — the backend exits without killing
|
||||
its children — so a reader THREAD watches it and ends the process at once, even
|
||||
mid-separation (the main thread is busy inside torch and could not notice).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class Cancelled(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _lower_priority() -> None:
|
||||
"""A batch may run for hours: stay out of the way of the DJ app itself."""
|
||||
try:
|
||||
if sys.platform == "win32":
|
||||
import ctypes
|
||||
|
||||
BELOW_NORMAL = 0x00004000
|
||||
ctypes.windll.kernel32.SetPriorityClass(ctypes.windll.kernel32.GetCurrentProcess(), BELOW_NORMAL)
|
||||
else:
|
||||
os.nice(10)
|
||||
except Exception: # noqa: BLE001 — a hint, never a failure
|
||||
pass
|
||||
|
||||
|
||||
def run(out, emit, weights: str, device_request: str) -> int:
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from . import core
|
||||
|
||||
_lower_priority()
|
||||
torch.set_num_threads(max(1, (os.cpu_count() or 2) - 1))
|
||||
|
||||
requests: "queue.Queue[dict]" = queue.Queue()
|
||||
cancel: set[str] = set()
|
||||
lock = threading.Lock()
|
||||
|
||||
def reader() -> None:
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
msg = json.loads(line)
|
||||
except ValueError:
|
||||
emit(event="error", message=f"not JSON: {line[:80]}")
|
||||
continue
|
||||
if msg.get("cmd") == "cancel":
|
||||
with lock:
|
||||
cancel.add(str(msg.get("id")))
|
||||
else:
|
||||
requests.put(msg)
|
||||
os._exit(0) # the parent is gone: do not linger, whatever is running
|
||||
|
||||
threading.Thread(target=reader, name="stdin", daemon=True).start()
|
||||
|
||||
device = core.pick_device(device_request)
|
||||
t0 = time.time()
|
||||
model = core.load_model(weights)
|
||||
emit(event="ready", device=device, seconds=round(time.time() - t0, 2))
|
||||
|
||||
while True:
|
||||
msg = requests.get()
|
||||
cmd = msg.get("cmd")
|
||||
if cmd == "ping":
|
||||
emit(event="pong")
|
||||
continue
|
||||
if cmd == "shutdown":
|
||||
return 0
|
||||
if cmd != "separate":
|
||||
emit(event="error", message=f"unknown command {cmd!r}")
|
||||
continue
|
||||
rid = str(msg.get("id"))
|
||||
started = time.time()
|
||||
try:
|
||||
n = int(msg["samples"])
|
||||
pcm = np.fromfile(msg["input"], dtype=np.float32)
|
||||
if pcm.size != 2 * n:
|
||||
raise ValueError(f"expected {2 * n} floats, found {pcm.size}")
|
||||
pcm = pcm.reshape(2, n)
|
||||
|
||||
def progress(f: float) -> None:
|
||||
with lock:
|
||||
if rid in cancel:
|
||||
raise Cancelled()
|
||||
emit(id=rid, event="progress", fraction=round(f, 4))
|
||||
|
||||
used = device
|
||||
try:
|
||||
stems = core.separate(model, pcm, device, seed=int(msg.get("seed", 0)), on_progress=progress)
|
||||
except torch.OutOfMemoryError:
|
||||
# A long track on a small GPU: finish it on the CPU rather than fail.
|
||||
if device == "cpu":
|
||||
raise
|
||||
torch.cuda.empty_cache() if device == "cuda" else None
|
||||
used = "cpu"
|
||||
emit(id=rid, event="fallback", device="cpu")
|
||||
stems = core.separate(model, pcm, "cpu", seed=int(msg.get("seed", 0)), on_progress=progress)
|
||||
folder = Path(msg["output_dir"])
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
for name, x in stems.items():
|
||||
x.tofile(folder / f"{name}.f32")
|
||||
emit(id=rid, event="done", seconds=round(time.time() - started, 2), device=used)
|
||||
except Cancelled:
|
||||
emit(id=rid, event="cancelled")
|
||||
except BaseException as ex: # noqa: BLE001 — reported, the process lives on
|
||||
# demucs re-raises a callback's exception wrapped; unwrap a cancel.
|
||||
if isinstance(ex.__cause__, Cancelled) or isinstance(ex.__context__, Cancelled):
|
||||
emit(id=rid, event="cancelled")
|
||||
else:
|
||||
emit(id=rid, event="error", message=f"{type(ex).__name__}: {ex}")
|
||||
finally:
|
||||
with lock:
|
||||
cancel.discard(rid)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Archive a frozen engine for release: tar.gz, split under GitHub's asset cap.
|
||||
|
||||
python package.py TARGET DIST_DIR OUT_DIR
|
||||
|
||||
Writes `konduktor-engine-<version>-<target>.tar.gz[.partNN]` and
|
||||
`<target>.json` (the parts with sizes and SHA-256, plus the whole archive's
|
||||
hash) for the release job to fold into `engine-manifest.json`.
|
||||
|
||||
tar.gz, not zip: `zipfile` drops the executable bit on macOS. Split because a
|
||||
release asset is capped at 2 GiB and the CUDA engine is bigger than that.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from konduktor_engine import VERSION # noqa: E402
|
||||
|
||||
PART = 1_900 * 1024 * 1024 # below the 2 GiB cap with room to spare
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def main(target: str, dist: str, out: str) -> int:
|
||||
src = Path(dist) / "konduktor-engine"
|
||||
out_dir = Path(out)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Symlinks are archived as links (the macOS build has several), so they
|
||||
# must not be counted — following them counted torch's libraries twice.
|
||||
files = [p for p in src.rglob("*") if p.is_file() and not p.is_symlink()]
|
||||
unpacked = sum(p.lstat().st_size for p in files)
|
||||
longest = max(len(p.relative_to(src.parent).as_posix()) for p in files)
|
||||
base = f"konduktor-engine-{VERSION}-{target}.tar.gz"
|
||||
archive = out_dir / base
|
||||
with tarfile.open(archive, "w:gz", compresslevel=6) as tar:
|
||||
tar.add(src, arcname="konduktor-engine")
|
||||
whole = sha256_file(archive)
|
||||
size = archive.stat().st_size
|
||||
parts = []
|
||||
if size <= PART:
|
||||
parts.append({"name": base, "size": size, "sha256": whole})
|
||||
else:
|
||||
with open(archive, "rb") as f:
|
||||
n = 0
|
||||
while chunk := f.read(PART):
|
||||
name = f"{base}.part{n:02d}"
|
||||
(out_dir / name).write_bytes(chunk)
|
||||
parts.append({"name": name, "size": len(chunk), "sha256": hashlib.sha256(chunk).hexdigest()})
|
||||
n += 1
|
||||
archive.unlink()
|
||||
info = {"target": target, "version": VERSION, "archive": base, "size": size, "sha256": whole,
|
||||
"unpacked_size": unpacked, "files": len(files), "longest_path": longest, "parts": parts}
|
||||
(out_dir / f"{target}.json").write_text(json.dumps(info, indent=1))
|
||||
print(json.dumps({k: v for k, v in info.items() if k != "parts"}), f"{len(parts)} part(s)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(*sys.argv[1:4]))
|
||||
@@ -0,0 +1,11 @@
|
||||
# Konduktor stem engine — Python 3.12. NOT the backend's requirements: this is a
|
||||
# separate program (it carries torch; the backend deliberately does not).
|
||||
# Pinned to the versions the 2026-09-29 benchmark and the user's listening test
|
||||
# ran on. Hashes are added when the frozen build (engine.yml) lands.
|
||||
torch==2.14.0
|
||||
demucs==4.1.0
|
||||
numpy==2.5.3
|
||||
safetensors==0.8.0
|
||||
pyyaml==6.0.3
|
||||
einops==0.8.2
|
||||
julius==0.2.8
|
||||
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user