Compare commits

...
Author SHA1 Message Date
patben8 f655bb4cf2 Implemented demucs engine 2026-09-30 19:26:00 +02:00
patben8 e4e98eda3f Implemented Discard changes button 2026-09-30 17:07:26 +02:00
patben8 4e875958a7 Implemented foundation of STEM support 2026-09-30 17:07:06 +02:00
patben8 387f97853d Fixed track collision bug 2026-09-30 15:54:49 +02:00
patben8 3c4238f60c Refined Rekordbox timing fix 2026-09-30 13:18:56 +02:00
patben8 d087310a9d Refined traktor timing fix 2026-09-30 11:18:10 +02:00
patben8 2a4c403d43 Implemented traktor utility fixes 2026-09-30 10:10:37 +02:00
56 changed files with 4163 additions and 114 deletions

No files matched your search

+142
View File
@@ -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.
+4
View File
@@ -47,3 +47,7 @@ backend/userprefs.json
# build_sidecar.sh are source and ARE tracked. # build_sidecar.sh are source and ARE tracked.
backend/build/ backend/build/
backend/dist/ backend/dist/
# ---- Stem engine (PyInstaller onedir build) ----
engine/build/
engine/dist/
+165 -10
View File
@@ -102,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 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 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 or a syncopated bassline. Positions are in the **decoded audio's** time
base (libsndfile = CoreAudio to the sample on MP3). **Rekordbox's grids sit base (libsndfile = CoreAudio to the sample on MP3). **Rekordbox's and
a constant ~25 ms later on lossy files** and at 0 on WAV — a platform Traktor's clocks both differ from it, per FILE** (an MP3's header, an
time-base difference, deliberately NOT corrected here; Traktor's is M4A's edit list), and are deliberately NOT corrected here but at each
unmeasured. `backend/bench_grid_detect.py` scores it against any library's 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 single-marker grids and reports that constant separately from detection
error (29 Rekordbox references: old 1/29 BPMs, new 27/29). 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 - `places.py` — where a person keeps things on THIS computer: the user's own
folders (via `platformdirs` — hardcoding is wrong on every OS differently: folders (via `platformdirs` — hardcoding is wrong on every OS differently:
`~/Videos` is `Movies` on macOS, Linux's are user-configurable localised `~/Videos` is `Movies` on macOS, Linux's are user-configurable localised
@@ -140,6 +162,25 @@ Two independent apps that talk over HTTP:
- `adapters/traktor/` — everything that knows NML exists. - `adapters/traktor/` — everything that knows NML exists.
- `store.py` (`TraktorStore`) — the retained native model: owns the parsed - `store.py` (`TraktorStore`) — the retained native model: owns the parsed
dataclass NML, applies every edit, renders + saves. See "Write path". 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` - `adapter.py` (`TraktorAdapter`) — owns the store **and** the `TrackIndex`
built from it, so projection and native model cannot drift. Translates the built from it, so projection and native model cannot drift. Translates the
generic cue vocabulary to Traktor's integers (the only place that mapping generic cue vocabulary to Traktor's integers (the only place that mapping
@@ -149,6 +190,21 @@ Two independent apps that talk over HTTP:
- `driver.py`/`discovery.py` — `can_open`, default-location detection, restore. - `driver.py`/`discovery.py` — `can_open`, default-location detection, restore.
- `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion - `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion
rules, LOCATION ↔ OS path conversion, and its capability set. 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; - `adapters/rekordbox/` — **track metadata, playlists and hot cues writable;
the beatgrid still read-only** (milestones 2 and 3a). Also home to the beatgrid still read-only** (milestones 2 and 3a). Also home to
`anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format, `anlz_writer.py`, which BUILDS analysis files from nothing — Pioneer's format,
@@ -267,6 +323,16 @@ Two independent apps that talk over HTTP:
know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place
that choice is made. that choice is made.
- `app_state.py` — the one loaded library, and the **version-history commit**. - `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, 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. 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 - `library_id.py` — a **stable identity for a library that survives it being
@@ -339,6 +405,38 @@ Two independent apps that talk over HTTP:
OneLibrary library is a drive. `prefs` keeps last-opened **per platform**: OneLibrary library is a drive. `prefs` keeps last-opened **per platform**:
offering a Rekordbox `master.db` to someone who just chose Traktor is an offering a Rekordbox `master.db` to someone who just chose Traktor is an
offer that cannot be taken. 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 - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
- `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**: - `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**:
@@ -413,7 +511,13 @@ Two independent apps that talk over HTTP:
same menu and the row's hover buttons, which share one set of actions. 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` 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 `/`, 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 `TrackTable` (**the one track list** — All Tracks, playlists, exports and
devices. TanStack Table + **virtualized** grid; per-row play button, devices. TanStack Table + **virtualized** grid; per-row play button,
configurable columns, header sorting, inline double-click editing, and configurable columns, header sorting, inline double-click editing, and
@@ -451,7 +555,9 @@ Two independent apps that talk over HTTP:
(right-click → multi-field metadata + album-art edit), `StatusBar`, (right-click → multi-field metadata + album-art edit), `StatusBar`,
`RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`, `RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`,
`UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows `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 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 `-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 "What's Changed" bullets; Download opens the release page in the system
@@ -566,10 +672,42 @@ serialization path.** It enforces:
real flexible grids in the collection project correctly (K); and real flexible grids in the collection project correctly (K); and
**removing a track from the collection** drops its `<ENTRY>` and its **removing a track from the collection** drops its `<ENTRY>` and its
PRIMARYKEYs from exactly the playlists that held it — the only ADDED lines are 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. The guard that catches serialization regressions like the lxml reformatting bug.
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. 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_traktor_adapter.py` — the **generic layer**: one parse per open, the - `test_traktor_adapter.py` — the **generic layer**: one parse per open, the
projection refreshing after every command family, cue-type translation, projection refreshing after every command family, cue-type translation,
capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity` capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity`
@@ -697,6 +835,12 @@ serialization path.** It enforces:
removable library is never written beside, an unwritable location falls back removable library is never written beside, an unwritable location falls back
rather than failing, and `paths.write_json` is atomic (curated user work, so 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). `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 - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
imports another platform's library (checked on real imports via AST, so merely 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 naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately
@@ -1026,9 +1170,20 @@ that number and nothing else — everything derives from it:
first marker on the first DOWNBEAT — the generic first marker is bar 1 — and 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; `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 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 1105 samples (~25 ms) Traktor as well as on export. **Rekordbox's clock runs behind the decoded
behind the decoded audio on MP3/AAC** — the codec delay it does not trim; audio by the start padding it does not trim, which depends on the FILE**:
measured +25.0 ms on 16 MP3s, +24.5 on 4 M4As, 0 on WAV. The generic model is 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 the decoded time base, so `adapters/rekordbox/timebase.py` is applied at EVERY
Pioneer boundary: both exporters add it, the OneLibrary reader and the Pioneer boundary: both exporters add it, the OneLibrary reader and the
Rekordbox adapter subtract it on read and add it on write (`set_cue`, Rekordbox adapter subtract it on read and add it on write (`set_cue`,
+129
View File
@@ -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())
@@ -257,6 +257,9 @@ class OneLibraryAdapter:
def remove_tracks(self, track_ids: list[str]) -> int: def remove_tracks(self, track_ids: list[str]) -> int:
self._refuse("Removing tracks") 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: def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata") self._refuse("Editing track metadata")
@@ -80,7 +80,9 @@ class RekordboxAdapter:
self._store.close() self._store.close()
def reload(self) -> None: 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._cloud_synced = self._store.cloud_synced
self._rebuild() self._rebuild()
@@ -412,6 +414,10 @@ class RekordboxAdapter:
# which of those Rekordbox expects to be deleted together is unmeasured. # which of those Rekordbox expects to be deleted together is unmeasured.
self._refuse("Removing tracks") self._refuse("Removing tracks")
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: def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art") self._refuse("Editing cover art")
@@ -99,9 +99,15 @@ def beats_from_markers(
n = 1 n = 1
# Guard against a zero/negative span producing an endless loop. # Guard against a zero/negative span producing an endless loop.
while t < end - 1e-9 and step > 0: while t < end - 1e-9 and step > 0:
beat_nums.append(n) # A beat before the audio starts is skipped but still COUNTED, so the
bpms.append(m.bpm) # next one keeps its place in the bar. The generic model can hold one
times.append(t) # (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 n = n % 4 + 1
t += step t += step
return beat_nums, bpms, times return beat_nums, bpms, times
+23 -5
View File
@@ -101,6 +101,24 @@ class RekordboxStore:
self._content_cache: list | None = None self._content_cache: list | None = None
self._by_id: dict[str, object] | 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._load()
def close(self) -> None: def close(self) -> None:
"""Release the session AND the pooled connection. """Release the session AND the pooled connection.
@@ -322,11 +340,11 @@ class RekordboxStore:
def time_offset(self, track_id: str) -> float: def time_offset(self, track_id: str) -> float:
"""Seconds rekordbox's clock runs behind the decoded audio for this """Seconds rekordbox's clock runs behind the decoded audio for this
track (~25 ms on MP3/AAC, 0 lossless). Added on every position written, track — per FILE (an MP3's header, an M4A's edit list; 0 lossless).
subtracted on every position read — see `timebase`. Decided by the Added on every position written, subtracted on every position read —
stored FolderPath's format, so it holds even when the file is offline.""" see `timebase`. Read from the file as it resolves here (path mapping
folder = getattr(self.content(track_id), "FolderPath", None) applied); a file that is offline falls back to its format's default."""
return timebase.offset(str(folder) if folder else None) return timebase.offset(self.audio_path(track_id))
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
"""The art embedded in the audio file, else Rekordbox's own copy. """The art embedded in the audio file, else Rekordbox's own copy.
@@ -1,30 +1,53 @@
"""Pioneer's clock vs the decoded audio's — one rule, used at every boundary. """Pioneer's clock vs the decoded audio's — one rule, used at every boundary.
**On MP3 and AAC, rekordbox's time 0 is NOT the decoded audio's time 0.** It does **rekordbox's time 0 is not always the decoded audio's time 0**, and by how much
not trim the codec delay a decoder removes, so every position it stores — beats, depends on the FILE, not just its format. rekordbox does not trim the start
cues, loops — sits a constant 1105 samples (~25 ms at 44.1 kHz) LATER than the padding a gapless decoder removes, so every position it stores — beats, cues,
same moment in the decoded audio. Lossless files have no such delay. loops — sits LATER than the same moment in the decoded audio by exactly that
padding:
Measured, not assumed: Konduktor's grid detector (which works in the decoded * **MP3 with a Xing/Info header**: the header's encoder delay + 529 decoder
time base) against rekordbox's own grids for the local library gave a median of delay — 1105 samples (~25 ms at 44.1 kHz) for LAME's usual 576. rekordbox
+25.0 ms on 16 MP3s, +24.5 ms on 4 M4As and 0.0 ms on 7 WAVs. 1105 samples is the SKIPS the header frame (Traktor does not — see `adapters/traktor/timebase.py`),
classic MP3 codec delay (576 encoder + 529 decoder). 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.
The generic model is in the DECODED time base — it is what Konduktor's deck plays, Measured 2026-09-30 in rekordbox 7 with kit 4 (see the stem-conversion discussion
what Traktor's positions line up with, and what the grid detector measures. So a log): blinded hotcues Konduktor wrote on a synthetic kick landed on it only at
Pioneer adapter ADDS the offset on every write and SUBTRACTS it on every read. these offsets, hot cues placed by hand read back at them to rekordbox's 1 ms
Get it wrong and nothing fails: every cue and beat is simply 25 ms early in resolution, and rekordbox's own grids agree. It replaced a fixed 1105 samples
rekordbox (as the first OneLibrary exports were), or late in Konduktor. 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 __future__ import annotations
from functools import lru_cache from functools import lru_cache
from pathlib import Path from pathlib import Path
#: The codec delay rekordbox does not trim. 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 CODEC_DELAY_SAMPLES = 1105
#: Formats that carry one. `.stem.m4a` (a Traktor STEM) is AAC. #: Formats that carry a start padding. `.stem.m4a` (a Traktor STEM) is AAC.
LOSSY = frozenset({".mp3", ".m4a", ".mp4", ".aac"}) LOSSY = frozenset({".mp3", ".m4a", ".mp4", ".aac"})
_MP4 = frozenset({".m4a", ".mp4"})
_DEFAULT_RATE = 44100 _DEFAULT_RATE = 44100
@@ -39,23 +62,43 @@ def _sample_rate(path: str) -> int:
return _DEFAULT_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: def offset(path: Path | str | None) -> float:
"""Seconds to ADD to a decoded-audio time to get rekordbox's; 0 if lossless. """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 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 file to say which format it is, and guessing lossy would move a lossless
track's cues. track's cues. A path to a lossy file that cannot be read gets the fallback.
""" """
if not path: if not path:
return 0.0 return 0.0
p = Path(path) p = Path(path)
if p.suffix.lower() not in LOSSY: if p.suffix.lower() not in LOSSY:
return 0.0 return 0.0
measured = _measured(p)
if measured is not None:
return measured
return CODEC_DELAY_SAMPLES / _sample_rate(str(p)) return CODEC_DELAY_SAMPLES / _sample_rate(str(p))
def to_pioneer(seconds: float, off: float) -> float: def to_pioneer(seconds: float, off: float) -> float:
return seconds + off """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: def from_pioneer(seconds: float, off: float) -> float:
+13 -2
View File
@@ -50,7 +50,7 @@ class TraktorAdapter:
if entry is None: if entry is None:
return TrackCues() return TrackCues()
self._index.replace(projection.to_track(entry)) 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 ------------------------------------------------------------ # ---- read ------------------------------------------------------------
@property @property
@@ -75,7 +75,9 @@ class TraktorAdapter:
def track_cues(self, track_id: str) -> TrackCues | None: def track_cues(self, track_id: str) -> TrackCues | None:
entry = self._store.model_entry(track_id) 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 -------------------------------------------- # ---- transitional shims --------------------------------------------
# main.py still drives the store directly and calls replace_track after each # main.py still drives the store directly and calls replace_track after each
@@ -161,6 +163,15 @@ class TraktorAdapter:
self._rebuild() self._rebuild()
return n 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 ---------------------------------------------------- # ---- adding tracks ----------------------------------------------------
def add_tracks(self, items: list) -> list[str]: def add_tracks(self, items: list) -> list[str]:
"""Add tracks that came from somewhere else, with their prep. """Add tracks that came from somewhere else, with their prep.
@@ -60,6 +60,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
editable_fields=sorted(editable_fields), editable_fields=sorted(editable_fields),
media_kinds=["audio", "stem"], media_kinds=["audio", "stem"],
removable=True, removable=True,
stem_convertible=True,
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA, # `.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. # 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"], audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
@@ -8,7 +8,7 @@ from __future__ import annotations
import re import re
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid from . import beatgrid, timebase
from .cue_types import NATIVE_TO_CUE_TYPE from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"), # 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) _OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", 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})$") _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]: 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}" 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: def primary_key(location) -> str:
"""Reconstruct the Traktor primary key used by playlist entries.""" """Reconstruct the Traktor primary key used by playlist entries."""
vol = location.volume or "" vol = location.volume or ""
@@ -132,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. """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 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, 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 because they occupy real hotcue slots. Each is tagged with the marker it sits
@@ -146,7 +175,7 @@ def to_track_cues(entry) -> TrackCues:
marker_of = {id(c): i for i, c in comps.items()} marker_of = {id(c): i for i, c in comps.items()}
grid_markers = [ grid_markers = [
GridMarker( 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, bpm=m.grid.bpm if m.grid and m.grid.bpm else 0.0,
name=m.name, name=m.name,
companion=comps[i].hotcue if i in comps else None, companion=comps[i].hotcue if i in comps else None,
@@ -167,7 +196,7 @@ def to_track_cues(entry) -> TrackCues:
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"), type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
# Every Traktor cue lives in the hotcue bank. # Every Traktor cue lives in the hotcue bank.
role="hotcue", 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, length=(c.len or 0.0) / 1000.0,
slot=slot, slot=slot,
color=c.color, color=c.color,
+294 -30
View File
@@ -18,6 +18,8 @@ Playlists are identified by their stable UUID; folders by a synthetic path id
""" """
from __future__ import annotations from __future__ import annotations
import copy
import math
import threading import threading
import uuid as uuidlib import uuid as uuidlib
from dataclasses import dataclass from dataclasses import dataclass
@@ -38,19 +40,22 @@ from traktor_nml_utils.models.collection import (
Nodetype, Nodetype,
Playlisttype, Playlisttype,
Primarykeytype, Primarykeytype,
Stemstype,
Subnodestype, Subnodestype,
Tempotype, Tempotype,
) )
from xsdata.formats.dataclass.serializers import XmlSerializer 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.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping from ...core.pathmap import PathMapping
from ...core.relocate import PathGroup from ...core.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON
from ...schemas import PlaylistNode from ...schemas import PlaylistNode
from . import beatgrid from . import beatgrid, timebase
from .locations import os_path_to_location, resolve_path 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 # 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. # this email is what makes the stars show up in Traktor itself.
@@ -385,6 +390,10 @@ class TraktorStore:
if entry.album is None: if entry.album is None:
entry.album = Albumtype() entry.album = Albumtype()
entry.album.title = v or None 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: elif k in self._INFO_FIELDS:
setattr(entry.info, k, v or None) setattr(entry.info, k, v or None)
elif k == "comment2": elif k == "comment2":
@@ -440,8 +449,9 @@ class TraktorStore:
key=getattr(track, "key", None) or None, key=getattr(track, "key", None) or None,
bitrate=getattr(track, "bitrate", None) or None, bitrate=getattr(track, "bitrate", None) or None,
playcount=getattr(track, "playcount", None) or None, playcount=getattr(track, "playcount", None) or None,
release_date=getattr(track, "release_date", None) or None, # The generic model carries ISO dates; Traktor writes "YYYY/M/D".
import_date=getattr(track, "import_date", None) or None, 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 # Traktor's RANKING is stars x 51; an unrated track has no
# attribute at all rather than a zero. # attribute at all rather than a zero.
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None, ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
@@ -597,7 +607,9 @@ class TraktorStore:
raise PlaylistError(f"Unsupported cue type: {cue_type}") raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock: with self._lock:
entry = self._entry_or_raise(track_id) 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) len_ms = max(0.0, length_sec * 1000.0)
existing = next( existing = next(
(c for c in (entry.cue_v2 or []) if c.hotcue == slot), None (c for c in (entry.cue_v2 or []) if c.hotcue == slot), None
@@ -752,7 +764,7 @@ class TraktorStore:
raise PlaylistError(f"BPM must be positive: {bpm}") raise PlaylistError(f"BPM must be positive: {bpm}")
with self._lock: with self._lock:
entry = self._entry_or_raise(track_id) 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) markers = beatgrid.grid_markers(entry)
for m in markers: for m in markers:
if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS: if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS:
@@ -812,7 +824,7 @@ class TraktorStore:
with self._lock: with self._lock:
entry = self._entry_or_raise(track_id) entry = self._entry_or_raise(track_id)
markers, marker = self._markers_or_raise(entry, index) 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: if index > 0:
lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS
start_ms = max(start_ms, lo) start_ms = max(start_ms, lo)
@@ -876,6 +888,7 @@ class TraktorStore:
raise PlaylistError(f"BPM must be positive: {bpm}") raise PlaylistError(f"BPM must be positive: {bpm}")
with self._lock: with self._lock:
entry = self._entry_or_raise(track_id) entry = self._entry_or_raise(track_id)
off_ms = self.time_offset_ms(entry)
self._drop_grid(entry) self._drop_grid(entry)
if entry.cue_v2 is None: if entry.cue_v2 is None:
entry.cue_v2 = [] entry.cue_v2 = []
@@ -887,7 +900,7 @@ class TraktorStore:
name="AutoGrid" if i == 0 else "n.n.", name="AutoGrid" if i == 0 else "n.n.",
displ_order=0, displ_order=0,
type=4, type=4,
start=max(0.0, start_sec * 1000.0), start=timebase.to_traktor_ms(start_sec, off_ms),
len=0.0, len=0.0,
repeats=-1, repeats=-1,
hotcue=-1, hotcue=-1,
@@ -1046,6 +1059,12 @@ class TraktorStore:
path = self._resolve(entry.location) path = self._resolve(entry.location)
return file_tags.read_cover(path) if path else None 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": def audio_path(self, track_id: str) -> "Path | None":
"""Resolve a track's audio file to an OS path (for playback streaming).""" """Resolve a track's audio file to an OS path (for playback streaming)."""
with self._lock: with self._lock:
@@ -1082,10 +1101,51 @@ class TraktorStore:
ranked = [g for g in ranked if g["prefix"]] ranked = [g for g in ranked if g["prefix"]]
return {"primary": ranked[0]["prefix"] if ranked else "", "groups": ranked[:5]} 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: def remap_preview(self, mapping: PathMapping) -> dict:
"""How a mapping would affect the collection, without changing anything: """How a mapping would affect the collection, without changing anything:
total tracks, how many match ``from``, and how many exist at ``to`` total tracks, how many match ``from``, how many exist at ``to``, and how
(plus a few samples). Powers the mapping editor's validation line.""" 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: with self._lock:
total = matched = existing = 0 total = matched = existing = 0
@@ -1104,7 +1164,17 @@ class TraktorStore:
existing += 1 existing += 1
if len(samples) < 5: if len(samples) < 5:
samples.append({"from": str(base), "to": str(target), "exists": ok}) 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]: def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
"""Permanently rewrite matching track LOCATIONs to the mapping's ``to`` """Permanently rewrite matching track LOCATIONs to the mapping's ``to``
@@ -1116,29 +1186,44 @@ class TraktorStore:
untouched. Returns ``{old track id: new track id}`` for every track untouched. Returns ``{old track id: new track id}`` for every track
rewritten — callers holding ids (export sets) follow them with it, and rewritten — callers holding ids (export sets) follow them with it, and
must not rebuild it from paths; the caller saves. 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: if mapping.empty:
return {} return {}
with self._lock: with self._lock:
key_remap: dict[str, str] = {} moves, clashes = self._plan_remap(mapping)
for e in self._nml.collection.entry: if clashes:
loc = e.location paths = [self._display_key(k) for k in sorted(clashes)]
if not loc: shown = ", ".join(paths[:3]) + (f" and {len(paths) - 3} more" if len(paths) > 3 else "")
continue raise PlaylistError(
base = resolve_path(loc.volume, loc.dir, loc.file) f"Remapping would give {len(paths)} path{'s' if len(paths) != 1 else ''} to more "
if not mapping.matches(base): f"than one track ({shown}). Two entries sharing a path corrupt the collection, "
continue "so nothing was changed."
target = mapping.apply(base) )
volume, dir_, file = os_path_to_location(target) if not moves:
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:
return {} 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. # Rewrite playlist entry primary keys that referenced moved tracks.
for node in self._iter_nodes(self._root()): for node in self._iter_nodes(self._root()):
pl = node.playlist pl = node.playlist
@@ -1150,12 +1235,188 @@ class TraktorStore:
pk.key = key_remap[pk.key] pk.key = key_remap[pk.key]
# Track ids derive from the LOCATION, so a remap renames them. Carry # 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. # 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_many(key_remap)
self._journal.retarget(old_key, new_key)
self._note("remap", str(len(key_remap))) self._note("remap", str(len(key_remap)))
self.dirty = True self.dirty = True
return key_remap 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): def _entry_field_value(self, entry: Entrytype, field: str):
"""Read a single editable field's current value from the model, in the """Read a single editable field's current value from the model, in the
shape file_tags expects (rating as 0–5 stars).""" shape file_tags expects (rating as 0–5 stars)."""
@@ -1170,6 +1431,9 @@ class TraktorStore:
return round(r / 51) if r else 0 return round(r / 51) if r else 0
if field == "comment2": if field == "comment2":
return entry.info.rating if entry.info else None 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 return getattr(entry.info, field, None) if entry.info else None
def count_playlists(self) -> int: def count_playlists(self) -> int:
@@ -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
View File
@@ -25,6 +25,7 @@ human summary, and this module versions them.
from __future__ import annotations from __future__ import annotations
import os import os
import threading
from pathlib import Path from pathlib import Path
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
@@ -51,6 +52,11 @@ class AppState:
# This open's missing-files check (see `relocation.py`). A new one per # 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. # open, which is what makes the dialog ask again on a reopen.
self.relocation: RelocationCheck | None = None 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()
@property @property
def loaded(self) -> bool: def loaded(self) -> bool:
@@ -95,6 +101,10 @@ class AppState:
pass pass
def open(self, path: Path) -> None: 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 — # 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 # 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. # an unrecognised or unparseable file; only commit once it has parsed.
@@ -146,6 +156,10 @@ class AppState:
cannot restore from. cannot restore from.
""" """
assert self.adapter is not None and self.path is not None 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() outcome = self.adapter.save()
# Not every platform is versioned. A library that is more than one file # 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 # has no single blob that IS the library, and it says so through its
@@ -158,6 +172,17 @@ class AppState:
) )
return outcome, commit 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:
self.adapter.reload()
STATE = AppState() STATE = AppState()
+45
View File
@@ -75,6 +75,44 @@ class NewTrack:
cues: TrackCues | None = None cues: TrackCues | 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): class AdapterError(Exception):
"""Base for every failure an adapter reports to the HTTP layer.""" """Base for every failure an adapter reports to the HTTP layer."""
@@ -143,6 +181,13 @@ class LibraryAdapter(Protocol):
# `capabilities().tracks.removable`. # `capabilities().tracks.removable`.
def remove_tracks(self, track_ids: list[str]) -> int: ... 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 --------------------------------- # ---- commands: track metadata / art ---------------------------------
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ... 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: ... def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
+3
View File
@@ -63,6 +63,9 @@ class TrackCapabilities(BaseModel):
# Tracks can be removed from the library (and so from its playlists). The # Tracks can be removed from the library (and so from its playlists). The
# audio file is never touched either way. # audio file is never touched either way.
removable: bool = False removable: 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 # 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 # browsed folder offers to add — a file the library would refuse, or that
# the DJ app cannot play, is not worth listing as addable. # the DJ app cannot play, is not worth listing as addable.
+13 -3
View File
@@ -95,11 +95,18 @@ class EditJournal:
"""Follow a track whose id changed (a path remap rewrites LOCATIONs, and """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 id is derived from the location). Without this, edits made earlier in
the session would silently stop syncing to the file.""" 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 return
for i, c in enumerate(self.changes): for i, c in enumerate(self.changes):
if c.target == old_id and c.scope in ("track", "cue", "grid", "lock"): if c.target in renames and c.scope in ("track", "cue", "grid", "lock"):
self.changes[i] = Change(c.scope, c.op, new_id, c.detail, c.before, c.after) self.changes[i] = Change(c.scope, c.op, renames[c.target], c.detail, c.before, c.after)
# ---- the version-history message -------------------------------------- # ---- the version-history message --------------------------------------
def summary(self, extra_tracks: set[str] | None = None) -> str: def summary(self, extra_tracks: set[str] | None = None) -> str:
@@ -127,6 +134,9 @@ class EditJournal:
n_removed = len(self.removed_tracks()) n_removed = len(self.removed_tracks())
if n_removed: if n_removed:
parts.append(f"removed {tracks(n_removed)} from the collection") 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) --- # --- track metadata + cover art (already counted per-track) ---
n_meta = len(self.edited_tracks() | (extra_tracks or set())) n_meta = len(self.edited_tracks() | (extra_tracks or set()))
+4
View File
@@ -233,6 +233,10 @@ class RemapPreview(BaseModel):
matched: int # how many match the `from` prefix matched: int # how many match the `from` prefix
existing: int # of matched, how many exist at the `to` target existing: int # of matched, how many exist at the `to` target
samples: list[RemapSample] = [] 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): class PrefixGroup(BaseModel):
+127
View File
@@ -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
+106
View File
@@ -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
+354
View File
@@ -0,0 +1,354 @@
"""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 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
__all__ = [
"DEMUCS_ORDER", "NML_STEMS_JSON", "SR", "STEM_BOX_JSON", "STEM_NAMES", "Source",
"StemFileError", "Written", "add_stem_box", "build", "choose_bitrate", "decode",
"default_encoder", "is_stem_file", "read_stem_box", "stem_target_name", "verify",
]
+218
View File
@@ -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
+23 -1
View File
@@ -58,6 +58,9 @@ class Job:
started_at: float = field(default_factory=time.time) started_at: float = field(default_factory=time.time)
finished_at: float | None = None finished_at: float | None = None
_cancel: threading.Event = field(default_factory=threading.Event, repr=False) _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 @property
def finished(self) -> bool: def finished(self) -> bool:
@@ -118,14 +121,26 @@ class JobCancelled(Exception):
""" """
class JobBusy(Exception):
"""`submit(..., exclusive_with=...)` found one of those kinds running."""
class JobRegistry: class JobRegistry:
def __init__(self) -> None: def __init__(self) -> None:
self._jobs: dict[str, Job] = {} self._jobs: dict[str, Job] = {}
self._lock = threading.Lock() 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) job = Job(id=uuid.uuid4().hex, kind=kind)
with self._lock: 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._jobs[job.id] = job
self._prune() self._prune()
@@ -142,6 +157,7 @@ class JobRegistry:
job.error = str(ex) or ex.__class__.__name__ job.error = str(ex) or ex.__class__.__name__
finally: finally:
job.finished_at = time.time() job.finished_at = time.time()
job._done.set()
threading.Thread(target=run, name=f"job-{kind}-{job.id[:8]}", daemon=True).start() threading.Thread(target=run, name=f"job-{kind}-{job.id[:8]}", daemon=True).start()
return job return job
@@ -162,6 +178,12 @@ class JobRegistry:
job._cancel.set() job._cancel.set()
return True 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]: def active(self, kind: str | None = None) -> list[Job]:
with self._lock: with self._lock:
return [ return [
+48 -7
View File
@@ -6,6 +6,7 @@ in the environment auto-loads that file on startup (used by dev and tests).
""" """
from __future__ import annotations from __future__ import annotations
import logging
import os import os
from pathlib import Path from pathlib import Path
@@ -30,7 +31,7 @@ from .core.adapter import (
Unsupported, Unsupported,
) )
from .core.capabilities import Capabilities from .core.capabilities import Capabilities
from .jobs import JOBS from .jobs import JOBS, Job, JobBusy
from .core.pathmap import PathMapping from .core.pathmap import PathMapping
from .schemas import ( from .schemas import (
Relocation, Relocation,
@@ -96,6 +97,8 @@ from .schemas import (
TrackPage, TrackPage,
) )
log = logging.getLogger(__name__)
app = FastAPI(title="Konduktor API", version=__version__) app = FastAPI(title="Konduktor API", version=__version__)
app.add_middleware( app.add_middleware(
@@ -159,10 +162,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
# This checks only that the path is there at all; `can_open()` decides. # This checks only that the path is there at all; `can_open()` decides.
if not path.exists(): if not path.exists():
raise HTTPException(400, f"Not found: {path}") raise HTTPException(400, f"Not found: {path}")
# A running analysis writes into the library being replaced; stop it. _stop_batches()
for kind in BATCH_JOBS:
for job in JOBS.active(kind):
JOBS.cancel(job.id)
try: try:
STATE.open(path) STATE.open(path)
except AdapterError as ex: except AdapterError as ex:
@@ -730,6 +730,22 @@ def state() -> EditState:
return EditState(dirty=require_adapter().dirty, library=_library_info()) return EditState(dirty=require_adapter().dirty, library=_library_info())
@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") @app.post("/api/reload")
def reload_collection() -> dict: def reload_collection() -> dict:
if not STATE.loaded: if not STATE.loaded:
@@ -1030,11 +1046,36 @@ CUE_JOB = "auto-hotcues"
BATCH_JOBS = (GRID_JOB, CUE_JOB) BATCH_JOBS = (GRID_JOB, CUE_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: 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): if any(JOBS.active(k) for k in BATCH_JOBS):
raise HTTPException(409, "A batch analysis is already running") 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: def _analyse_grid(a, track_id: str) -> TrackCues:
"""Detect and write one track's grid — shared by the deck's Analyze and the """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.""" batch job, so the two cannot come to mean different things."""
@@ -1090,7 +1131,7 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
handle.progress(done=i + 1) handle.progress(done=i + 1)
return result return result
job = JOBS.submit(GRID_JOB, run) job = _submit_batch(GRID_JOB, run)
return JobStatus(**job.as_dict()) return JobStatus(**job.as_dict())
@@ -1141,7 +1182,7 @@ def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus:
handle.progress(done=i + 1) handle.progress(done=i + 1)
return result return result
job = JOBS.submit(CUE_JOB, run) job = _submit_batch(CUE_JOB, run)
return JobStatus(**job.as_dict()) return JobStatus(**job.as_dict())
+4
View File
@@ -446,6 +446,10 @@ class JobStatus(BaseModel):
state: str # running | done | failed | cancelled state: str # running | done | failed | cancelled
total: int total: int
done: 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 message: str
result: dict | None = None result: dict | None = None
error: str | None = None error: str | None = None
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate source .venv/bin/activate
fail=0 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_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; do for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.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 "──────────────────────────────────────────"
echo "▶ $t" echo "▶ $t"
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
+131
View File
@@ -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)
+23
View File
@@ -193,11 +193,34 @@ with tempfile.TemporaryDirectory() as d:
other = Path(d) / "other.nml" other = Path(d) / "other.nml"
shutil.copy2(REAL, other) shutil.copy2(REAL, other)
c.post("/api/library/open", json={"path": str(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") 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)
check("nothing was written to disk (edits stay in memory until Save)", check("nothing was written to disk (edits stay in memory until Save)",
work.read_bytes() == REAL.read_bytes()) 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()
print("FAILED" if failed else "RESULT: ALL PASSED") print("FAILED" if failed else "RESULT: ALL PASSED")
raise SystemExit(1 if failed else 0) raise SystemExit(1 if failed else 0)
+204
View File
@@ -515,6 +515,164 @@ with tempfile.TemporaryDirectory() as d:
check("H2: old playlist PRIMARYKEY gone", old_key not in all_pl_keys) 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) 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 --------- # ---- Invariant I: flexible (multi-marker) beatgrids round-trip ---------
print("== I. flexible beatgrid: add/move/delete markers, localized + reversible ==") 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))) 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") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+252
View File
@@ -0,0 +1,252 @@
"""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)")
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)
+265
View File
@@ -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)
+279
View File
@@ -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)
+7
View File
@@ -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())
+51
View File
@@ -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]))
+37
View File
@@ -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)
+10
View File
@@ -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"
+118
View File
@@ -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())
+95
View File
@@ -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)}
+137
View File
@@ -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)
+69
View File
@@ -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]))
+11
View File
@@ -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
+163
View File
@@ -0,0 +1,163 @@
"""The stem engine's process protocol, and (with --frozen) the golden test.
.venv/bin/python test_engine.py --weights DIR [--frozen dist/konduktor-engine/konduktor-engine]
Needs the htdemucs_ft weights folder (`htdemucs_ft.yaml` + four
`.safetensors`); defaults to the Hugging Face cache snapshot when present.
Runs on CPU so results are comparable across machines (CI runners have no GPU).
Pins what would fail silently or hang the app:
* `serve` loads once, separates repeatedly, and the SAME seed gives the SAME
stems — a re-conversion is reproducible;
* a cancel stops the running separation and the process stays usable;
* closing stdin (the backend died) ends the process even mid-separation —
otherwise an orphaned engine keeps a CPU pinned for an hour;
* the frozen build separates bit-for-bit like the unfrozen code (golden).
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import tempfile
import time
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
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 default_weights() -> str | None:
snaps = sorted(Path.home().glob(".cache/huggingface/hub/models--adefossez--HTDemucs-ft/snapshots/*/"))
return str(snaps[-1]) if snaps else None
def clip(seconds: float, seed: int = 0) -> np.ndarray:
"""Something with drums, bass and a tone: enough for every model in the bag."""
sr = 44100
n = int(seconds * sr)
t = np.arange(n) / sr
rng = np.random.default_rng(seed)
x = 0.3 * np.sin(2 * np.pi * 55 * t) + 0.1 * np.sin(2 * np.pi * 440 * t)
for start in range(0, n, sr // 2):
k = min(2000, n - start)
x[start:start + k] += rng.uniform(-0.6, 0.6, k) * np.linspace(1, 0, k)
return np.stack([x, x * 0.9]).astype(np.float32)
class Engine:
def __init__(self, cmd: list[str], weights: str):
self.proc = subprocess.Popen(cmd + ["serve", "--weights", weights, "--device", "cpu"],
cwd=HERE, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, bufsize=1)
def send(self, **msg):
self.proc.stdin.write(json.dumps(msg) + "\n")
self.proc.stdin.flush()
def recv(self) -> dict:
line = self.proc.stdout.readline()
if not line:
raise EOFError("engine closed its output")
return json.loads(line)
def until(self, *events, rid=None):
seen = []
while True:
m = self.recv()
seen.append(m)
if m.get("event") in events and (rid is None or m.get("id") == rid):
return m, seen
def separate(self, rid, pcm, out: Path, seed=0):
src = out / f"{rid}.f32"
pcm.tofile(src)
self.send(cmd="separate", id=rid, input=str(src), samples=pcm.shape[1], output_dir=str(out / rid), seed=seed)
def read_stems(folder: Path):
return {n: np.fromfile(folder / f"{n}.f32", dtype=np.float32) for n in ("drums", "bass", "other", "vocals")}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--weights", default=default_weights())
ap.add_argument("--frozen")
args = ap.parse_args()
if not args.weights:
print("no weights folder: pass --weights")
return 2
unfrozen = [sys.executable, "-m", "konduktor_engine"]
tmp = Path(tempfile.mkdtemp(prefix="konduktor-engine-test-"))
print("== info ==")
info = json.loads(subprocess.run(unfrozen + ["info"], cwd=HERE, capture_output=True, text=True).stdout)
check("info reports the version, model and devices",
info.get("event") == "info" and info.get("model") == "htdemucs_ft" and "cpu" in info.get("devices", []), str(info))
print("== serve ==")
e = Engine(unfrozen, args.weights)
ready = e.recv()
check("serve loads the model once and says so", ready.get("event") == "ready", str(ready))
e.send(cmd="ping")
check("ping -> pong", e.recv().get("event") == "pong")
pcm = clip(8)
e.separate("a", pcm, tmp, seed=0)
done, seen = e.until("done", "error", rid="a")
check("a separation completes", done["event"] == "done", str(done))
check("…reporting progress on the way", any(m.get("event") == "progress" for m in seen))
a = read_stems(tmp / "a")
check("four stems, each the mix's size", all(x.size == pcm.size for x in a.values()))
e.separate("b", pcm, tmp, seed=0)
e.until("done", rid="b")
b = read_stems(tmp / "b")
check("the same seed gives the SAME stems (reproducible)", all(np.array_equal(a[k], b[k]) for k in a))
e.separate("c", clip(30, seed=1), tmp)
e.until("progress", rid="c")
e.send(cmd="cancel", id="c")
m, _ = e.until("cancelled", "done", "error", rid="c")
check("a cancel stops the running separation", m["event"] == "cancelled", str(m))
e.send(cmd="ping")
check("…and the engine is still usable", e.until("pong")[0]["event"] == "pong")
e.separate("d", clip(60, seed=2), tmp)
e.until("progress", rid="d")
t0 = time.time()
e.proc.stdin.close() # the backend died
try:
e.proc.wait(timeout=10)
check("closing stdin ends the engine even mid-separation", True)
except subprocess.TimeoutExpired:
e.proc.kill()
check("closing stdin ends the engine even mid-separation", False, "still running after 10 s")
print(f" (exited {time.time() - t0:.2f} s after stdin closed)")
if args.frozen:
print("== golden: frozen vs unfrozen ==")
fe = Engine([args.frozen], args.weights)
check("the frozen engine starts and loads the model", fe.recv().get("event") == "ready")
fe.separate("f", pcm, tmp, seed=0)
fdone, _ = fe.until("done", "error", rid="f")
check("the frozen engine separates", fdone["event"] == "done", str(fdone))
f = read_stems(tmp / "f")
worst = max(float(np.max(np.abs(f[k] - a[k]))) for k in a)
check("…bit-for-bit like the unfrozen code", worst == 0.0, f"max |diff| {worst:.3g}")
fe.proc.stdin.close()
fe.proc.wait(timeout=10)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+13
View File
@@ -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"}
]
}
+84 -6
View File
@@ -5,21 +5,94 @@
// it to actually accept connections, then create the app window with an // it to actually accept connections, then create the app window with an
// initialization script that hands the frontend its API base // initialization script that hands the frontend its API base
// (`window.__KONDUKTOR_API__`). The sidecar is killed when the app exits. // (`window.__KONDUKTOR_API__`). The sidecar is killed when the app exits.
//
// Quitting ASKS FIRST. Closing the window or Cmd/Ctrl+Q is prevented and
// becomes a `konduktor://quit-requested` event; the frontend (QuitGuard.tsx)
// acknowledges it, checks for unsaved changes and either quits (`quit_now`) or
// asks Save / Discard / Cancel. The sidecar must outlive that question — a
// Save or Discard runs in it — so it is killed only once the app really exits.
// If the webview does not acknowledge within ~2 s (hung, or not loaded yet),
// the app quits anyway: a broken page must never make the app unquittable.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex; use std::sync::Mutex;
use std::time::Duration; use std::time::Duration;
use tauri::{Manager, WebviewUrl, WebviewWindowBuilder}; use tauri::{AppHandle, Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent};
use tauri_plugin_shell::process::{CommandChild, CommandEvent}; use tauri_plugin_shell::process::{CommandChild, CommandEvent};
use tauri_plugin_shell::ShellExt; use tauri_plugin_shell::ShellExt;
/// Holds the running sidecar child so we can terminate it on exit. /// Holds the running sidecar child so we can terminate it on exit.
struct Sidecar(Mutex<Option<CommandChild>>); struct Sidecar(Mutex<Option<CommandChild>>);
/// Quit handshake state: `allowed` once the frontend (or the timeout) has said
/// quit; `acked` once the frontend has seen the current request.
struct Quit {
allowed: AtomicBool,
acked: AtomicBool,
}
fn kill_sidecar(app: &AppHandle) {
if let Some(child) = app.state::<Sidecar>().0.lock().unwrap().take() {
let _ = child.kill();
}
}
fn exit_now(app: &AppHandle) {
app.state::<Quit>().allowed.store(true, Ordering::SeqCst);
kill_sidecar(app);
app.exit(0);
}
/// Hand the quit decision to the frontend, with a deadline for it to answer.
fn request_quit(app: &AppHandle) {
app.state::<Quit>().acked.store(false, Ordering::SeqCst);
if app.emit("konduktor://quit-requested", ()).is_err() {
exit_now(app);
return;
}
let handle = app.clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(Duration::from_secs(2)).await;
if !handle.state::<Quit>().acked.load(Ordering::SeqCst) {
exit_now(&handle);
}
});
}
/// The frontend has seen the quit request (it may now take as long as it likes).
#[tauri::command]
fn quit_ack(app: AppHandle) {
app.state::<Quit>().acked.store(true, Ordering::SeqCst);
}
/// The user chose Cancel: forget the request.
#[tauri::command]
fn quit_cancel(app: AppHandle) {
app.state::<Quit>().acked.store(false, Ordering::SeqCst);
}
/// Quit for real (nothing unsaved, or Save / Discard has finished).
#[tauri::command]
fn quit_now(app: AppHandle) {
exit_now(&app);
}
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
tauri::Builder::default() tauri::Builder::default()
.plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_shell::init())
.manage(Sidecar(Mutex::new(None))) .manage(Sidecar(Mutex::new(None)))
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
.invoke_handler(tauri::generate_handler![quit_ack, quit_cancel, quit_now])
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
let app = window.app_handle();
if !app.state::<Quit>().allowed.load(Ordering::SeqCst) {
api.prevent_close();
request_quit(app);
}
}
})
.setup(|app| { .setup(|app| {
if cfg!(debug_assertions) { if cfg!(debug_assertions) {
app.handle().plugin( app.handle().plugin(
@@ -99,12 +172,17 @@ pub fn run() {
}) })
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while building the Tauri application") .expect("error while building the Tauri application")
.run(|app_handle, event| { .run(|app_handle, event| match event {
// Terminate the sidecar when the app is quitting. // Cmd/Ctrl+Q, the app menu's Quit, the last window closing: ask
if let tauri::RunEvent::ExitRequested { .. } = event { // first, unless the answer is already in.
if let Some(child) = app_handle.state::<Sidecar>().0.lock().unwrap().take() { RunEvent::ExitRequested { api, .. } => {
let _ = child.kill(); if !app_handle.state::<Quit>().allowed.load(Ordering::SeqCst) {
api.prevent_exit();
request_quit(app_handle);
} }
} }
// Really exiting: only now may the backend go.
RunEvent::Exit => kill_sidecar(app_handle),
_ => {}
}); });
} }
+7 -1
View File
@@ -5,6 +5,7 @@ import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { writeHint } from './lib/platformCopy' import { writeHint } from './lib/platformCopy'
import { invalidateTrackLists } from './lib/trackQueries' import { invalidateTrackLists } from './lib/trackQueries'
import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type Track, type TrackOrigin } from './api' import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved'
import { import {
COLUMN_MENU, COLUMN_MENU,
DEFAULT_COLUMN_ORDER, DEFAULT_COLUMN_ORDER,
@@ -1034,6 +1035,7 @@ export default function App() {
onSwitchLibrary={() => setForcePicker(true)} onSwitchLibrary={() => setForcePicker(true)}
onDone={(msg) => notify('success', msg)} onDone={(msg) => notify('success', msg)}
onOpenPathMapping={() => setShowPaths(true)} onOpenPathMapping={() => setShowPaths(true)}
onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)}
/> />
<CapabilitiesContext.Provider value={viewCaps}> <CapabilitiesContext.Provider value={viewCaps}>
@@ -1353,7 +1355,11 @@ export default function App() {
} }
loading={loading} loading={loading}
collectionName={capabilities.data ? libraryName : null} collectionName={capabilities.data ? libraryName : null}
onChangeCollection={() => setForcePicker(true)} onChangeCollection={() => {
// The same question the sidebar header asks: this button used to
// switch library without it, silently dropping unsaved edits.
void confirmDiscardUnsaved().then((ok) => ok && setForcePicker(true))
}}
/> />
</div> </div>
</CapabilitiesContext.Provider> </CapabilitiesContext.Provider>
+8
View File
@@ -247,6 +247,8 @@ export interface Capabilities {
media_kinds: MediaKind[] media_kinds: MediaKind[]
/** Tracks can be removed from the library (audio files are never touched). */ /** Tracks can be removed from the library (audio files are never touched). */
removable: boolean removable: boolean
/** Tracks can be converted to native-instruments STEM files. */
stem_convertible: boolean
/** Lower-case suffixes this library can hold — what a browsed folder lists. */ /** Lower-case suffixes this library can hold — what a browsed folder lists. */
audio_formats: string[] audio_formats: string[]
artwork: boolean artwork: boolean
@@ -556,6 +558,10 @@ export interface RemapPreview {
matched: number matched: number
existing: number existing: number
samples: RemapSample[] samples: RemapSample[]
/** Target paths more than one track would land on. Non-zero = the rewrite
* would be refused (two entries sharing a path corrupt the library). */
collisions: number
collision_samples: string[]
} }
/** One place a stored volume's tracks were found — a mapping the user can pick. */ /** One place a stored volume's tracks were found — a mapping the user can pick. */
@@ -752,6 +758,8 @@ export const api = {
patchPrefs: (patch: Record<string, unknown>) => patchPrefs: (patch: Record<string, unknown>) =>
send<Record<string, unknown>>('PATCH', '/api/prefs', patch), send<Record<string, unknown>>('PATCH', '/api/prefs', patch),
save: () => send<SaveResult>('POST', '/api/save'), save: () => send<SaveResult>('POST', '/api/save'),
/** Drop every unsaved edit; the library re-reads itself from disk. */
discard: () => send<EditState>('POST', '/api/discard'),
// ---- version history ---- // ---- version history ----
history: () => getJSON<HistoryEntry[]>('/api/history'), history: () => getJSON<HistoryEntry[]>('/api/history'),
+17 -1
View File
@@ -102,7 +102,10 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
} }
} }
const canCommit = !!from.trim() && !!to.trim() // The backend refuses a rewrite that would give two tracks one path; say so
// here rather than only after the click.
const collides = (preview?.collisions ?? 0) > 0
const canCommit = !!from.trim() && !!to.trim() && !collides
return createPortal( return createPortal(
<div <div
@@ -191,6 +194,19 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
{preview.matched} exist at the target. {preview.matched} exist at the target.
</span> </span>
)} )}
{collides && (
<div className="mt-1.5 text-pink">
{preview.collisions} target path{preview.collisions === 1 ? '' : 's'} would
belong to more than one track, so the paths can’t be rewritten:
<ul className="mt-1 list-disc pl-4 text-muted">
{preview.collision_samples.map((p) => (
<li key={p} className="truncate" title={p}>
{p}
</li>
))}
</ul>
</div>
)}
</div> </div>
)} )}
+150
View File
@@ -0,0 +1,150 @@
import { createPortal } from 'react-dom'
import { useEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
/**
* Ask before quitting with unsaved changes: Save · Discard · Cancel.
*
* The desktop shell (src-tauri/src/lib.rs) no longer quits on its own. Closing
* the window or Cmd/Ctrl+Q is PREVENTED there and becomes a
* `konduktor://quit-requested` event; this answers it. It acknowledges at once
* (`quit_ack`) — the shell quits anyway after ~2 s without one, so a webview
* that has hung can never trap the user — then either quits (`quit_now`) or
* asks. Discard goes through the backend rather than just letting the process
* die, because unsaved state may include files to put back (a stem
* conversion's parked originals).
*
* In a plain browser (dev) there is no shell to prevent anything, so the most
* that can be done is the browser's own `beforeunload` warning.
*
* Mounted once in main.tsx, beside App, so it works on the picker screen too.
*/
export function QuitGuard() {
const [asking, setAsking] = useState(false)
const [busy, setBusy] = useState<null | 'save' | 'discard'>(null)
const [error, setError] = useState<string | null>(null)
const askingRef = useRef(false)
const state = useQuery({ queryKey: ['state'], queryFn: api.state, retry: false })
const dirty = state.data?.dirty ?? false
// Tauri: answer the shell's quit request.
useEffect(() => {
if (!('__TAURI_INTERNALS__' in window)) return
let unlisten: (() => void) | undefined
let cancelled = false
void (async () => {
const [{ listen }, { invoke }] = await Promise.all([
import('@tauri-apps/api/event'),
import('@tauri-apps/api/core'),
])
const off = await listen('konduktor://quit-requested', async () => {
await invoke('quit_ack')
if (askingRef.current) return // already asking: a second Cmd+Q changes nothing
const unsaved = await api
.state()
.then((s) => s.dirty)
.catch(() => false) // no library loaded: nothing to lose
if (!unsaved) {
await invoke('quit_now')
return
}
askingRef.current = true
setError(null)
setAsking(true)
})
if (cancelled) off()
else unlisten = off
})()
return () => {
cancelled = true
unlisten?.()
}
}, [])
// Browser dev: the browser's own warning is all there is.
useEffect(() => {
if ('__TAURI_INTERNALS__' in window || !dirty) return
const warn = (e: BeforeUnloadEvent) => {
e.preventDefault()
}
window.addEventListener('beforeunload', warn)
return () => window.removeEventListener('beforeunload', warn)
}, [dirty])
const quit = async () => {
const { invoke } = await import('@tauri-apps/api/core')
await invoke('quit_now')
}
const cancel = async () => {
askingRef.current = false
setAsking(false)
const { invoke } = await import('@tauri-apps/api/core')
await invoke('quit_cancel')
}
const act = async (kind: 'save' | 'discard') => {
setBusy(kind)
setError(null)
try {
if (kind === 'save') await api.save()
else await api.discard()
await quit()
} catch (e) {
// Stay open: a failed save must never turn into a silent loss.
setError(e instanceof Error ? e.message : String(e))
setBusy(null)
}
}
useEffect(() => {
if (!asking) return
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && !busy) void cancel()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
})
if (!asking) return null
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
>
<div className="w-full max-w-sm overflow-hidden glass-overlay">
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
Save changes before quitting?
</div>
<div className="space-y-2 px-5 py-4 text-sm text-muted">
<p>You have unsaved changes. If you quit without saving, they are lost.</p>
{error && <p className="text-pink">{error}</p>}
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
onClick={() => void cancel()}
disabled={!!busy}
className="btn-glass rounded-full px-4 py-1.5 text-sm text-muted hover:text-text disabled:opacity-40"
>
Cancel
</button>
<button
onClick={() => void act('discard')}
disabled={!!busy}
className="rounded-full bg-pink/15 px-4 py-1.5 text-sm font-semibold text-[#ffd0da] shadow-[inset_0_1px_0_rgb(255_255_255/0.12),inset_0_0_0_1px_rgb(255_122_154/0.55)] hover:bg-pink/25 disabled:opacity-50"
>
{busy === 'discard' ? 'Discarding…' : 'Discard'}
</button>
<button
autoFocus
onClick={() => void act('save')}
disabled={!!busy}
className="btn-primary rounded-full px-4 py-1.5 text-sm font-semibold disabled:opacity-50"
>
{busy === 'save' ? 'Saving…' : 'Save and quit'}
</button>
</div>
</div>
</div>,
document.body,
)
}
+34 -1
View File
@@ -4,16 +4,19 @@ import { api } from '../api'
import { useCaps } from '../lib/capabilities' import { useCaps } from '../lib/capabilities'
import { overwriteWarning, readOnlyNotice, saveLabel } from '../lib/platformCopy' import { overwriteWarning, readOnlyNotice, saveLabel } from '../lib/platformCopy'
import { Icon } from '../lib/icons' import { Icon } from '../lib/icons'
import { askConfirm } from '../lib/confirm'
interface Props { interface Props {
onError: (msg: string) => void onError: (msg: string) => void
/** Rendered to the right of the save button (the settings gear). */ /** Rendered to the right of the save button (the settings gear). */
trailing?: ReactNode trailing?: ReactNode
/** After a discard, so the owner can refresh what it holds outside queries. */
onDiscarded?: () => void
} }
// Bottom-of-sidebar save control. Shows unsaved-changes state and writes to the // Bottom-of-sidebar save control. Shows unsaved-changes state and writes to the
// NML; every save is recorded in the collection's version history. // NML; every save is recorded in the collection's version history.
export function SaveBar({ onError, trailing }: Props) { export function SaveBar({ onError, trailing, onDiscarded }: Props) {
const qc = useQueryClient() const qc = useQueryClient()
const [justSaved, setJustSaved] = useState<string | null>(null) const [justSaved, setJustSaved] = useState<string | null>(null)
const { data: state } = useQuery({ queryKey: ['state'], queryFn: api.state }) const { data: state } = useQuery({ queryKey: ['state'], queryFn: api.state })
@@ -31,6 +34,25 @@ export function SaveBar({ onError, trailing }: Props) {
onError: (e: Error) => onError(e.message), onError: (e: Error) => onError(e.message),
}) })
// The way back that did not exist: every edit since the last save goes, and
// the library re-reads itself from disk. Everything cached is refetched.
const discard = useMutation({
mutationFn: api.discard,
onSuccess: () => {
qc.invalidateQueries()
onDiscarded?.()
},
onError: (e: Error) => onError(e.message),
})
const confirmDiscard = async () => {
const ok = await askConfirm({
title: 'Discard unsaved changes?',
body: 'Every change since the last save is thrown away and the library is re-read from disk. This cannot be undone.',
confirmLabel: 'Discard changes',
})
if (ok) discard.mutate()
}
const caps = useCaps() const caps = useCaps()
const warning = overwriteWarning(caps.save) const warning = overwriteWarning(caps.save)
const dirty = state?.dirty ?? false const dirty = state?.dirty ?? false
@@ -79,6 +101,17 @@ export function SaveBar({ onError, trailing }: Props) {
</button> </button>
{trailing} {trailing}
</div> </div>
{dirty && !save.isPending && (
<div className="mt-1.5 text-center">
<button
onClick={() => void confirmDiscard()}
disabled={discard.isPending}
className="text-[11px] text-faint hover:text-pink disabled:opacity-50"
>
{discard.isPending ? 'Discarding…' : 'Discard changes…'}
</button>
</div>
)}
{justSaved && ( {justSaved && (
<div className="mt-2 text-center text-[11px] text-mint">{justSaved}</div> <div className="mt-2 text-center text-[11px] text-mint">{justSaved}</div>
)} )}
+12 -15
View File
@@ -3,11 +3,11 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistKind, type PlaylistNode } from '../api' import { api, type PlaylistKind, type PlaylistNode } from '../api'
import { useCaps } from '../lib/capabilities' import { useCaps } from '../lib/capabilities'
import { SaveBar } from './SaveBar' import { SaveBar } from './SaveBar'
import { confirmDiscardUnsaved } from '../lib/unsaved'
import { SettingsMenu } from './SettingsMenu' import { SettingsMenu } from './SettingsMenu'
import { DevicesSection } from './DevicesSection' import { DevicesSection } from './DevicesSection'
import { ExportsSection } from './ExportsSection' import { ExportsSection } from './ExportsSection'
import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog' import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog'
import { askConfirm } from '../lib/confirm'
import { ContextMenu, type MenuItem } from './ContextMenu' import { ContextMenu, type MenuItem } from './ContextMenu'
import { Icon, type IconName } from '../lib/icons' import { Icon, type IconName } from '../lib/icons'
import { PlatformIcon } from '../lib/platformIcons' import { PlatformIcon } from '../lib/platformIcons'
@@ -49,6 +49,8 @@ interface Props {
onSwitchLibrary: () => void onSwitchLibrary: () => void
onDone: (msg: string) => void onDone: (msg: string) => void
onOpenPathMapping: () => void onOpenPathMapping: () => void
/** After unsaved edits were discarded (SaveBar). */
onDiscarded?: () => void
} }
// Kind picks the icon; every behavioural question is answered by the node's own // Kind picks the icon; every behavioural question is answered by the node's own
@@ -319,27 +321,18 @@ export function Sidebar({
onSwitchLibrary, onSwitchLibrary,
onDone, onDone,
onOpenPathMapping, onOpenPathMapping,
onDiscarded,
}: Props) { }: Props) {
const qc = useQueryClient() const qc = useQueryClient()
// Both share a cache entry with App and SaveBar, so the header never // Shares a cache entry with App, so the header never disagrees with what is
// disagrees with what is loaded or with whether it has been saved. // loaded.
const library = useQuery({ queryKey: ['collection'], queryFn: api.collection }).data?.library const library = useQuery({ queryKey: ['collection'], queryFn: api.collection }).data?.library
const dirty = useQuery({ queryKey: ['state'], queryFn: api.state }).data?.dirty ?? false
// Switching library throws away every unsaved edit — the adapter holds them in // Switching library throws away every unsaved edit — the adapter holds them in
// its native model, and opening another library replaces it. Worth a confirm: // its native model, and opening another library replaces it. Worth a confirm:
// until now there was no way to switch at all, so this hazard is new. // until now there was no way to switch at all, so this hazard is new.
const switchLibrary = async () => { const switchLibrary = async () => {
if ( if (await confirmDiscardUnsaved()) onSwitchLibrary()
dirty &&
!(await askConfirm({
title: 'Discard unsaved changes?',
body: 'You have unsaved changes. Opening a different library will discard them.',
confirmLabel: 'Discard and switch',
}))
)
return
onSwitchLibrary()
} }
// There is no per-node flag for "you may create a NEW playlist" — the node // There is no per-node flag for "you may create a NEW playlist" — the node
// flags describe existing nodes — so this is the library-level gate. // flags describe existing nodes — so this is the library-level gate.
@@ -609,7 +602,11 @@ export function Sidebar({
Collection Version History Collection Version History
</button> </button>
<SaveBar onError={onError} trailing={<SettingsMenu up onOpenPathMapping={onOpenPathMapping} />} /> <SaveBar
onError={onError}
onDiscarded={onDiscarded}
trailing={<SettingsMenu up onOpenPathMapping={onOpenPathMapping} />}
/>
</aside> </aside>
) )
} }
+14 -2
View File
@@ -20,14 +20,26 @@ interface GithubRelease {
tag_name: string tag_name: string
html_url: string html_url: string
body: string | null body: string | null
draft?: boolean
prerelease?: boolean
} }
/**
* The newest APP release. Not `/releases/latest`: that is whichever release
* GitHub flags "latest", and the same repo also publishes the stem engine on
* its own `engine-v*` channel — one flagged latest by mistake would make this
* check go quiet (its tag does not parse as an app version) with no error. So
* list recent releases (newest first) and take the first app tag.
*/
async function fetchLatestRelease(): Promise<GithubRelease> { async function fetchLatestRelease(): Promise<GithubRelease> {
const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=30`, {
headers: { Accept: 'application/vnd.github+json' }, headers: { Accept: 'application/vnd.github+json' },
}) })
if (!res.ok) throw new Error(`GitHub responded ${res.status}`) if (!res.ok) throw new Error(`GitHub responded ${res.status}`)
return res.json() const releases: GithubRelease[] = await res.json()
const app = releases.find((r) => !r.draft && !r.prerelease && /^v\d/.test(r.tag_name))
if (!app) throw new Error('No app release found')
return app
} }
/** The semver triple at the start of a version/tag string ("v0.1.2-b7" → [0,1,2]). */ /** The semver triple at the start of a version/tag string ("v0.1.2-b7" → [0,1,2]). */
+10 -2
View File
@@ -29,12 +29,20 @@ describe('buildBeatGrid', () => {
expect(buildBeatGrid([{ start: Infinity, bpm: 120 }])).toBeNull() expect(buildBeatGrid([{ start: Infinity, bpm: 120 }])).toBeNull()
}) })
it('sorts unsorted input and clamps negative starts', () => { it('sorts unsorted input and keeps negative starts', () => {
const g = grid([ const g = grid([
{ start: 10, bpm: 60 }, { start: 10, bpm: 60 },
{ start: -5, bpm: 120 }, { start: -5, bpm: 120 },
]) ])
expect(g.markers.map((m) => m.start)).toEqual([0, 10]) expect(g.markers.map((m) => m.start)).toEqual([-5, 10])
})
it('a marker before the audio starts keeps its phase', () => {
// A Traktor MP3 grid anchored inside the header frame: 30 ms before the
// decoded audio. Clamping it to 0 would put every beat 30 ms late.
const g = grid([{ start: -0.03, bpm: 120 }])
expect(g.snapToBeat(0.5)).toBeCloseTo(0.47, 9)
expect(g.timeOfBeat(1)).toBeCloseTo(0.47, 9)
}) })
it('collapses markers at the same instant', () => { it('collapses markers at the same instant', () => {
+7 -2
View File
@@ -277,7 +277,8 @@ export class BeatGrid {
* *
* Tolerant by design: accepts `undefined` (so a frontend running against an * Tolerant by design: accepts `undefined` (so a frontend running against an
* older backend degrades to "no grid" rather than throwing), unsorted input, * older backend degrades to "no grid" rather than throwing), unsorted input,
* duplicate positions, negative starts, and non-finite or out-of-range BPMs. * duplicate positions and non-finite or out-of-range BPMs. Negative starts are
* kept as they are (see below).
*/ */
export function buildBeatGrid(markers?: readonly GridMarker[] | null): BeatGrid | null { export function buildBeatGrid(markers?: readonly GridMarker[] | null): BeatGrid | null {
if (!markers || markers.length === 0) return null if (!markers || markers.length === 0) return null
@@ -286,7 +287,11 @@ export function buildBeatGrid(markers?: readonly GridMarker[] | null): BeatGrid
if (!m || !Number.isFinite(m.bpm) || !Number.isFinite(m.start)) continue if (!m || !Number.isFinite(m.bpm) || !Number.isFinite(m.start)) continue
if (m.bpm <= 0) continue if (m.bpm <= 0) continue
clean.push({ clean.push({
start: Math.max(0, m.start), // NOT clamped at 0. A marker before the decoded audio's start is a real
// phase — Traktor anchors MP3 grids inside the header frame, ~51 ms
// before the audio Konduktor decodes — and clamping it would move every
// beat of the grid late by that much.
start: m.start,
bpm: Math.min(MAX_BPM, Math.max(MIN_BPM, m.bpm)), bpm: Math.min(MAX_BPM, Math.max(MIN_BPM, m.bpm)),
}) })
} }
+24
View File
@@ -0,0 +1,24 @@
import { api } from '../api'
import { askConfirm } from './confirm'
/**
* Ask before an action that throws away unsaved edits — opening a different
* library replaces the adapter that holds them. Resolves true when there is
* nothing to lose or the user agreed.
*
* Reads the state fresh rather than from a cached query: the two places that
* switch library (the sidebar header and the status bar) must not disagree, and
* the status bar's button used to skip the question entirely.
*/
export async function confirmDiscardUnsaved(): Promise<boolean> {
const dirty = await api
.state()
.then((s) => s.dirty)
.catch(() => false) // no library loaded: nothing to lose
if (!dirty) return true
return askConfirm({
title: 'Discard unsaved changes?',
body: 'You have unsaved changes. Opening a different library will discard them.',
confirmLabel: 'Discard and switch',
})
}
+3
View File
@@ -8,6 +8,7 @@ import App from './App.tsx'
import { UpdateCheck } from './components/UpdateDialog.tsx' import { UpdateCheck } from './components/UpdateDialog.tsx'
import { AmbientBackdrop } from './components/AmbientBackdrop.tsx' import { AmbientBackdrop } from './components/AmbientBackdrop.tsx'
import { ConfirmHost } from './lib/confirm.tsx' import { ConfirmHost } from './lib/confirm.tsx'
import { QuitGuard } from './components/QuitGuard.tsx'
import { preventHistoryNavigation } from './lib/noNavigation.ts' import { preventHistoryNavigation } from './lib/noNavigation.ts'
preventHistoryNavigation() preventHistoryNavigation()
@@ -31,6 +32,8 @@ createRoot(document.getElementById('root')!).render(
<UpdateCheck /> <UpdateCheck />
{/* askConfirm()'s dialogs — the app's replacement for window.confirm. */} {/* askConfirm()'s dialogs — the app's replacement for window.confirm. */}
<ConfirmHost /> <ConfirmHost />
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
<QuitGuard />
</QueryClientProvider> </QueryClientProvider>
</StrictMode>, </StrictMode>,
) )