diff --git a/CLAUDE.md b/CLAUDE.md index 73901f9..db5379f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -110,6 +110,26 @@ Two independent apps that talk over HTTP: `backend/bench_grid_detect.py` scores it against any library's single-marker grids and reports that constant separately from detection error (29 Rekordbox references: old 1/29 BPMs, new 27/29). + - `stem_file.py` + `tag_copy.py` — **writing a native-instruments STEM + file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz + streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0, + muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place + (moov is last, so only two sizes change). The separation is a CALLBACK — + the backend never imports torch; the engine (below) supplies it, the + tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB, + so mono is duplicated by hand; resampling does not move time; both + encoders (`aac_at` on macOS, `aac` elsewhere) are timing-exact but decode + up to ~2 frames LONGER, so length checks allow 0..2048 samples and the + duration reported is the source's; AAC pre-echo fools threshold onsets, + so alignment is checked by cross-correlation. **Two JSON literals**: the + box exactly as the commercial files hold it and `` exactly as + Traktor writes it — they differ in key order AND float digits (Traktor's + 16 digits do not round-trip the same double; both are the same float32), + so neither is derived from the other. `tag_copy` carries every canonical + tag (ID3 / Vorbis / MP4 -> MP4, incl. `tmpo` and freeform `initialkey`, + the atoms the user's commercial stems use) and the cover, opening the + target as `MP4` explicitly because the batch writes `*.konduktor-partial` + files that `audio_tags.write_cover` would refuse by suffix. - `places.py` — where a person keeps things on THIS computer: the user's own folders (via `platformdirs` — hardcoding is wrong on every OS differently: `~/Videos` is `Movies` on macOS, Linux's are user-configurable localised @@ -142,6 +162,24 @@ Two independent apps that talk over HTTP: - `adapters/traktor/` — everything that knows NML exists. - `store.py` (`TraktorStore`) — the retained native model: owns the parsed dataclass NML, applies every edit, renders + saves. See "Write path". + **`apply_stem_swaps`** is Convert to Stems' library side (generic + `StemSwap` / `StemSwapResult` in `core/adapter.py`, gated on + `tracks.stem_convertible`; Rekordbox/OneLibrary refuse): all swaps are + validated before any applies. "repoint" moves the entry to the stem file + (id changes; playlists follow as `TYPE="STEM"`); "add" deep-copies it + (plus its pending tag fields and staged art, so Save still writes them to + the new file). Either sets `` (the literal from `core/stem_file`), + INFO bitrate/playtime/playtime_float/filesize(KB), VOLUMEID only where it + still names the volume, and clears AUDIO_ID (`_KEEP_AUDIO_ID_ON_STEM`, + pending the Traktor check). **Every START shifts by the time-base + difference**, the old offset read from `StemSwap.original_audio` — the + original's bytes where they are NOW (parked, under a non-audio name, so + `timebase.offset_ms(..., suffix=)` takes the original's suffix). Read + from the old path it would be 0 and every cue ~51 ms late + (`test_stem_swap.py` pins that failure). An anchor pushed below 0 moves + forward by whole beats with its companion; a hotcue there clamps to 0 and + is reported. The journal records scope `stem` (not `track/add`, which + would exclude the entry from the tag sync). - `adapter.py` (`TraktorAdapter`) — owns the store **and** the `TrackIndex` built from it, so projection and native model cannot drift. Translates the generic cue vocabulary to Traktor's integers (the only place that mapping @@ -356,6 +394,16 @@ Two independent apps that talk over HTTP: OneLibrary library is a drive. `prefs` keeps last-opened **per platform**: offering a Rekordbox `master.db` to someone who just chose Traktor is an offer that cannot be taken. +- **`engine/`** — the **stem engine**, a separate program (`konduktor_engine`, + Python 3.12, torch + demucs 4.1 pinned in `engine/requirements.txt`) that + imports nothing from `konduktor`. `core.py` loads htdemucs_ft from a LOCAL + weights folder (never online — the weights' licence rules out shipping them, + so the app downloads them) and separates, seeded (shifts=1 is random). + Audio crosses as raw planar float32 files; protocol messages are JSON lines + on a private copy of stdout, with `sys.stdout` pointed at stderr so torch's + prints cannot corrupt one. For now a one-shot `separate` CLI; the persistent + `serve` mode and the frozen per-OS build come next. `backend/dev_stems.py` + (dev only) converts files with the real writer through an unfrozen engine. - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). - `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**: @@ -468,7 +516,9 @@ Two independent apps that talk over HTTP: (right-click → multi-field metadata + album-art edit), `StatusBar`, `RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`, `UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows - even on the picker screen: on startup fetches the latest GitHub release and, + even on the picker screen: on startup lists recent GitHub releases and takes the + newest non-draft, non-prerelease `v…` tag — NOT `/releases/latest`, since the + stem engine publishes `engine-v*` releases in the same repo — and, if its tag's **semver part** is newer than `__APP_VERSION__` — build-number `-b` bumps don't count — shows an update dialog with the release's "What's Changed" bullets; Download opens the release page in the system @@ -604,6 +654,21 @@ serialization path.** It enforces: (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 projection refreshing after every command family, cue-type translation, capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity` diff --git a/backend/dev_stems.py b/backend/dev_stems.py new file mode 100644 index 0000000..63fc4c6 --- /dev/null +++ b/backend/dev_stems.py @@ -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/ \\ + [--out-dir DIR] [--device auto] FILE... + +Each FILE becomes `.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 (`..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()) diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index 47aefd8..f129130 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -257,6 +257,9 @@ class OneLibraryAdapter: def remove_tracks(self, track_ids: list[str]) -> int: self._refuse("Removing tracks") + def apply_stem_swaps(self, swaps, *, add_to_playlist=None): + self._refuse("Converting tracks to stems") + def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: self._refuse("Editing track metadata") diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index 975969d..1575d26 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -412,6 +412,10 @@ class RekordboxAdapter: # which of those Rekordbox expects to be deleted together is unmeasured. 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: self._refuse("Editing cover art") diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index c6a23d0..89bb5ab 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -163,6 +163,15 @@ class TraktorAdapter: self._rebuild() return n + # ---- stem conversion -------------------------------------------------- + def apply_stem_swaps(self, swaps: list, *, add_to_playlist: str | None = None): + with _translate(): + result = self._store.apply_stem_swaps(swaps, add_to_playlist=add_to_playlist) + # One rebuild for the whole batch: ids changed (repoint) or appeared + # (add), and `TrackIndex` has no per-id remove. + self._rebuild() + return result + # ---- adding tracks ---------------------------------------------------- def add_tracks(self, items: list) -> list[str]: """Add tracks that came from somewhere else, with their prep. diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index e6eac5a..6f4d71f 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -60,6 +60,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: editable_fields=sorted(editable_fields), media_kinds=["audio", "stem"], removable=True, + stem_convertible=True, # `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA, # but only on Windows, and a file added on one OS must play on both. audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"], diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index d328ae1..4e948d0 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -18,6 +18,8 @@ Playlists are identified by their stable UUID; folders by a synthetic path id """ from __future__ import annotations +import copy +import math import threading import uuid as uuidlib from dataclasses import dataclass @@ -38,16 +40,18 @@ from traktor_nml_utils.models.collection import ( Nodetype, Playlisttype, Primarykeytype, + Stemstype, Subnodestype, Tempotype, ) from xsdata.formats.dataclass.serializers import XmlSerializer -from ...core.adapter import InvalidCommand, SaveOutcome +from ...core.adapter import InvalidCommand, SaveOutcome, StemSwapResult from ...core.edit_journal import EditJournal from ...core.pathmap import common_dir_prefix from ...core.pathmap import PathMapping from ...core.relocate import PathGroup +from ...core.stem_file import NML_STEMS_JSON from ...schemas import PlaylistNode from . import beatgrid, timebase from .locations import os_path_to_location, resolve_path @@ -1236,6 +1240,180 @@ class TraktorStore: self.dirty = True return key_remap + # ---- stem conversion --------------------------------------------------- + #: Whether a converted entry keeps Traktor's analysis fingerprint. It is a + #: fingerprint of the OLD file; cleared, Traktor re-analyses the new one on + #: load (the import precedent: prep survives). Settled by the milestone-2 + #: check in Traktor 4.5. + _KEEP_AUDIO_ID_ON_STEM = False + + 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 `` 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, `` and the file-describing INFO fields, for the stem file.""" + volume, dir_, file = loc + old_volume = entry.location.volume if entry.location else None + volumeid = entry.location.volumeid if entry.location else None + if volume != old_volume: + # VOLUMEID names a volume, so it cannot follow the file to another one; + # borrow it from any entry already on that volume, else leave it for + # Traktor to fill in (as `add_entry` does). + volumeid = next( + (e.location.volumeid for e in self._nml.collection.entry + if e.location and e.location.volume == volume and e.location.volumeid), + None, + ) + entry.location = Locationtype(volume=volume, dir=dir_, file=file, volumeid=volumeid) + entry.stems = Stemstype(stems=NML_STEMS_JSON) + if entry.info is None: + entry.info = Infotype() + entry.info.bitrate = int(swap.bit_rate) + entry.info.playtime = int(round(swap.duration)) + entry.info.playtime_float = float(swap.duration) + entry.info.filesize = int(round(swap.size / 1024)) + if not self._KEEP_AUDIO_ID_ON_STEM: + entry.audio_id = None + + def _retime(self, entry: Entrytype, shift_ms: float) -> list[int]: + """Shift every cue and grid marker by `shift_ms`; returns the hotcue + slots clamped at 0. Companions move WITH their marker, as the same float, + so the pairing survives exactly.""" + if not shift_ms or not entry.cue_v2: + return [] + markers = beatgrid.grid_markers(entry) + comps = beatgrid.companions(entry) + comp_ids = {id(c) for c in comps.values()} + clamped: list[int] = [] + for c in entry.cue_v2: + if c.grid is not None or id(c) in comp_ids: + continue + start = (c.start or 0.0) + shift_ms + if start < 0: + if c.hotcue is not None and c.hotcue >= 0: + clamped.append(c.hotcue) + start = 0.0 + c.start = start + for i, m in enumerate(markers): + start = (m.start or 0.0) + shift_ms + if start < 0: + bpm = m.grid.bpm if m.grid and m.grid.bpm else 0.0 + if bpm > 0: + beat = 60000.0 / bpm + start += math.ceil(-start / beat) * beat + nxt = markers[i + 1].start + shift_ms if i + 1 < len(markers) else None + if nxt is not None and start >= nxt: + start = 0.0 # a pathological grid: keep the order, lose the phase + else: + start = 0.0 + m.start = start + if i in comps: + comps[i].start = m.start + self._sort_cues(entry) + return clamped + def _entry_field_value(self, entry: Entrytype, field: str): """Read a single editable field's current value from the model, in the shape file_tags expects (rating as 0–5 stars).""" diff --git a/backend/konduktor/adapters/traktor/timebase.py b/backend/konduktor/adapters/traktor/timebase.py index 345d645..bf4ba62 100644 --- a/backend/konduktor/adapters/traktor/timebase.py +++ b/backend/konduktor/adapters/traktor/timebase.py @@ -38,14 +38,18 @@ from pathlib import Path from ...core import mp3_gapless -def offset_samples(path: Path | str | None) -> tuple[int, int]: +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 `..konduktor-parked` until Save. """ - if not path or Path(path).suffix.lower() != ".mp3": + 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: @@ -53,9 +57,9 @@ def offset_samples(path: Path | str | None) -> tuple[int, int]: return start.samples_per_frame + start.trimmed, start.sample_rate -def offset_ms(path: Path | str | None) -> float: +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) + samples, rate = offset_samples(path, suffix) return samples * 1000.0 / rate if samples else 0.0 diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 8b8ef68..be83db2 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -75,6 +75,44 @@ class NewTrack: 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): """Base for every failure an adapter reports to the HTTP layer.""" @@ -143,6 +181,13 @@ class LibraryAdapter(Protocol): # `capabilities().tracks.removable`. def remove_tracks(self, track_ids: list[str]) -> int: ... + # Swap converted stem files into the library (see `StemSwap`), all at once: + # every swap is validated before any is applied, so a clash leaves the + # library untouched. Gated on `capabilities().tracks.stem_convertible`. + # `add_to_playlist` receives the entries "add" mode creates, in order. + def apply_stem_swaps(self, swaps: list["StemSwap"], *, + add_to_playlist: str | None = None) -> "StemSwapResult": ... + # ---- commands: track metadata / art --------------------------------- def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ... def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ... diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index a29e223..9efe1a5 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -63,6 +63,9 @@ class TrackCapabilities(BaseModel): # Tracks can be removed from the library (and so from its playlists). The # audio file is never touched either way. removable: bool = False + # Tracks can be converted to native-instruments STEM files, which this + # platform plays as stems (`apply_stem_swaps`). + stem_convertible: bool = False # The audio files this library can hold, as lower-case suffixes. What a # browsed folder offers to add — a file the library would refuse, or that # the DJ app cannot play, is not worth listing as addable. diff --git a/backend/konduktor/core/edit_journal.py b/backend/konduktor/core/edit_journal.py index 35818b8..951d54f 100644 --- a/backend/konduktor/core/edit_journal.py +++ b/backend/konduktor/core/edit_journal.py @@ -134,6 +134,9 @@ class EditJournal: n_removed = len(self.removed_tracks()) if n_removed: parts.append(f"removed {tracks(n_removed)} from the collection") + n_stems = len({c.target for c in self.changes if c.scope == "stem" and c.target}) + if n_stems: + parts.append(f"converted {tracks(n_stems)} to stems") # --- track metadata + cover art (already counted per-track) --- n_meta = len(self.edited_tracks() | (extra_tracks or set())) diff --git a/backend/konduktor/core/stem_file.py b/backend/konduktor/core/stem_file.py new file mode 100644 index 0000000..2939c17 --- /dev/null +++ b/backend/konduktor/core/stem_file.py @@ -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 `` 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 `` 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 `` 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", +] diff --git a/backend/konduktor/core/tag_copy.py b/backend/konduktor/core/tag_copy.py new file mode 100644 index 0000000..43e5634 --- /dev/null +++ b/backend/konduktor/core/tag_copy.py @@ -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 diff --git a/backend/konduktor/jobs.py b/backend/konduktor/jobs.py index dad471b..94937e6 100644 --- a/backend/konduktor/jobs.py +++ b/backend/konduktor/jobs.py @@ -58,6 +58,9 @@ class Job: started_at: float = field(default_factory=time.time) finished_at: float | None = None _cancel: threading.Event = field(default_factory=threading.Event, repr=False) + #: Set once the thread has finished — cancelled, failed or done — so a caller + #: that cancels can WAIT for the work to actually stop touching things. + _done: threading.Event = field(default_factory=threading.Event, repr=False) @property def finished(self) -> bool: @@ -118,14 +121,26 @@ class JobCancelled(Exception): """ +class JobBusy(Exception): + """`submit(..., exclusive_with=...)` found one of those kinds running.""" + + class JobRegistry: def __init__(self) -> None: self._jobs: dict[str, Job] = {} self._lock = threading.Lock() - def submit(self, kind: str, fn: Callable[[JobHandle], Any]) -> Job: + def submit(self, kind: str, fn: Callable[[JobHandle], Any], *, + exclusive_with: tuple[str, ...] = ()) -> Job: + """Start `fn` on its own thread. With `exclusive_with`, refuse (JobBusy) + if a job of any of those kinds is still running — checked and registered + under ONE lock, so two requests arriving together cannot both start.""" job = Job(id=uuid.uuid4().hex, kind=kind) with self._lock: + if exclusive_with and any( + not j.finished and j.kind in exclusive_with for j in self._jobs.values() + ): + raise JobBusy(kind) self._jobs[job.id] = job self._prune() @@ -142,6 +157,7 @@ class JobRegistry: job.error = str(ex) or ex.__class__.__name__ finally: job.finished_at = time.time() + job._done.set() threading.Thread(target=run, name=f"job-{kind}-{job.id[:8]}", daemon=True).start() return job @@ -162,6 +178,12 @@ class JobRegistry: job._cancel.set() return True + def wait(self, job_id: str, timeout: float | None = None) -> bool: + """Block until the job has finished; False on timeout. An unknown id + counts as finished (pruned jobs are long done).""" + job = self.get(job_id) + return True if job is None else job._done.wait(timeout) + def active(self, kind: str | None = None) -> list[Job]: with self._lock: return [ diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index a8c6192..a6aa0be 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -6,6 +6,7 @@ in the environment auto-loads that file on startup (used by dev and tests). """ from __future__ import annotations +import logging import os from pathlib import Path @@ -30,7 +31,7 @@ from .core.adapter import ( Unsupported, ) from .core.capabilities import Capabilities -from .jobs import JOBS +from .jobs import JOBS, Job, JobBusy from .core.pathmap import PathMapping from .schemas import ( Relocation, @@ -96,6 +97,8 @@ from .schemas import ( TrackPage, ) +log = logging.getLogger(__name__) + app = FastAPI(title="Konduktor API", version=__version__) app.add_middleware( @@ -159,10 +162,16 @@ def open_collection(body: OpenCollection) -> CollectionStatus: # This checks only that the path is there at all; `can_open()` decides. if not path.exists(): raise HTTPException(400, f"Not found: {path}") - # A running analysis writes into the library being replaced; stop it. - for kind in BATCH_JOBS: - for job in JOBS.active(kind): - JOBS.cancel(job.id) + # A running analysis writes into the library being replaced; stop it, and + # WAIT for it to stop — a job still finishing its current track would + # otherwise keep writing (or, for file work, keep moving files) after the + # switch. 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; opening anyway", job.id, job.kind) try: STATE.open(path) except AdapterError as ex: @@ -1031,10 +1040,19 @@ BATCH_JOBS = (GRID_JOB, CUE_JOB) def _require_no_batch() -> None: + """An early, friendly refusal. Not race-free on its own — the batch routes + START through `_submit_batch`, which re-checks under the registry's lock.""" if any(JOBS.active(k) for k in BATCH_JOBS): raise HTTPException(409, "A batch analysis is already running") +def _submit_batch(kind: str, run) -> "Job": + try: + return JOBS.submit(kind, run, exclusive_with=BATCH_JOBS) + except JobBusy: + raise HTTPException(409, "A batch analysis is already running") + + def _analyse_grid(a, track_id: str) -> TrackCues: """Detect and write one track's grid — shared by the deck's Analyze and the batch job, so the two cannot come to mean different things.""" @@ -1090,7 +1108,7 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: handle.progress(done=i + 1) return result - job = JOBS.submit(GRID_JOB, run) + job = _submit_batch(GRID_JOB, run) return JobStatus(**job.as_dict()) @@ -1141,7 +1159,7 @@ def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus: handle.progress(done=i + 1) return result - job = JOBS.submit(CUE_JOB, run) + job = _submit_batch(CUE_JOB, run) return JobStatus(**job.as_dict()) diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 52b2a95..f4550ca 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_timebase.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; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_grid_batch.py b/backend/test_grid_batch.py index 8fd2dc0..0362ad5 100644 --- a/backend/test_grid_batch.py +++ b/backend/test_grid_batch.py @@ -193,8 +193,26 @@ with tempfile.TemporaryDirectory() as d: other = Path(d) / "other.nml" shutil.copy2(REAL, other) c.post("/api/library/open", json={"path": str(other)}) + check("opening another library has STOPPED the run by the time it returns", + main.JOBS.get(jid).finished and main.JOBS.get(jid).state == "cancelled", + main.JOBS.get(jid).state) check("opening another library cancels the run", wait(c, jid)["state"] == "cancelled") + # Exclusive submit is checked and registered under one lock: a second + # batch cannot start while one runs, however the requests interleave. + from konduktor.jobs import JobBusy + import threading as _th + gate = _th.Event() + first = main.JOBS.submit(main.GRID_JOB, lambda h: gate.wait(5), exclusive_with=main.BATCH_JOBS) + try: + main.JOBS.submit(main.CUE_JOB, lambda h: None, exclusive_with=main.BATCH_JOBS) + check("a second batch kind is refused while one runs", False, "it started") + except JobBusy: + check("a second batch kind is refused while one runs", True) + check("wait() times out on a running job", main.JOBS.wait(first.id, timeout=0.05) is False) + gate.set() + check("…and returns once it has finished", main.JOBS.wait(first.id, timeout=5) is True) + check("nothing was written to disk (edits stay in memory until Save)", work.read_bytes() == REAL.read_bytes()) diff --git a/backend/test_stem_file.py b/backend/test_stem_file.py new file mode 100644 index 0000000..a6a7f66 --- /dev/null +++ b/backend/test_stem_file.py @@ -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' 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) diff --git a/backend/test_stem_swap.py b/backend/test_stem_swap.py new file mode 100644 index 0000000..e2c514f --- /dev/null +++ b/backend/test_stem_swap.py @@ -0,0 +1,262 @@ +"""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() + 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 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") + 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("") + 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) diff --git a/engine/konduktor_engine/__init__.py b/engine/konduktor_engine/__init__.py new file mode 100644 index 0000000..bc6900a --- /dev/null +++ b/engine/konduktor_engine/__init__.py @@ -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" diff --git a/engine/konduktor_engine/__main__.py b/engine/konduktor_engine/__main__.py new file mode 100644 index 0000000..327f296 --- /dev/null +++ b/engine/konduktor_engine/__main__.py @@ -0,0 +1,87 @@ +"""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] +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +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") + + +def _emit(out, **msg) -> None: + out.write(json.dumps(msg) + "\n") + 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) + args = parser.parse_args(argv) + + out = _protocol() + from . import core + + if args.command == "info": + import torch + + _emit(out, event="info", version=VERSION, torch=torch.__version__, + devices=core.available_devices(), model=core.MODEL) + return 0 + + 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()) diff --git a/engine/konduktor_engine/core.py b/engine/konduktor_engine/core.py new file mode 100644 index 0000000..030a830 --- /dev/null +++ b/engine/konduktor_engine/core.py @@ -0,0 +1,89 @@ +"""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. + """ + 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] + 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)} diff --git a/engine/requirements.txt b/engine/requirements.txt new file mode 100644 index 0000000..f5dea9c --- /dev/null +++ b/engine/requirements.txt @@ -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 diff --git a/frontend/src/api.ts b/frontend/src/api.ts index aa71168..524a7fe 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -247,6 +247,8 @@ export interface Capabilities { media_kinds: MediaKind[] /** Tracks can be removed from the library (audio files are never touched). */ removable: boolean + /** Tracks can be converted to native-instruments STEM files. */ + stem_convertible: boolean /** Lower-case suffixes this library can hold — what a browsed folder lists. */ audio_formats: string[] artwork: boolean diff --git a/frontend/src/components/UpdateDialog.tsx b/frontend/src/components/UpdateDialog.tsx index 6202ee4..bbb73ed 100644 --- a/frontend/src/components/UpdateDialog.tsx +++ b/frontend/src/components/UpdateDialog.tsx @@ -20,14 +20,26 @@ interface GithubRelease { tag_name: string html_url: string 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 { - 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' }, }) 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]). */