From ecc0e4c8df7af96a09c7e1546ecffef0b6de7d33 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Wed, 30 Sep 2026 23:51:04 +0200 Subject: [PATCH] Implemented STEM playback --- CLAUDE.md | 35 +++++ backend/konduktor/core/stem_file.py | 56 ++++++- backend/konduktor/main.py | 55 ++++++- backend/konduktor/stems/stream_cache.py | 75 ++++++++++ backend/run_tests.sh | 2 +- backend/test_stem_playback.py | 153 ++++++++++++++++++++ frontend/src/api.ts | 21 +++ frontend/src/components/MainWaveform.tsx | 65 ++++++++- frontend/src/components/PrepStrip.tsx | 92 +++++++++++- frontend/src/components/ShortcutsDialog.tsx | 4 + frontend/src/lib/playbackEngine.ts | 99 +++++++++---- frontend/src/lib/scratchEngine.ts | 50 +++++++ frontend/src/lib/waveform.ts | 129 +++++++++++++++-- 13 files changed, 775 insertions(+), 61 deletions(-) create mode 100644 backend/konduktor/stems/stream_cache.py create mode 100644 backend/test_stem_playback.py diff --git a/CLAUDE.md b/CLAUDE.md index dcaa1e6..d7f69e6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -381,6 +381,17 @@ Two independent apps that talk over HTTP: relocation, import, folder add, history restore and reload answer 409 (`_require_no_pending_stems`): each would save or drop the swap. `/api/state` reports `pending_stems`, `stem_job`, `stem_recovery`. + **`stream_cache.py` — stem PLAYBACK.** A browser decodes only an MP4's + FIRST audio stream (the mix), so each stem is served as a file of its own: + the three audio routes (collection / `source` / `folder`) take + `?stem=0..3`, and `/api/…/tracks/stems` report `[{name, color}]` read from + the FILE (`stem_file.stem_layout`: the box, and enough streams — never the + library's ``, which plain MP3s carry). `stem_file.extract_stream` + COPIES packets into an `ipod` MP4 — measured bit-identical to decoding the + stream in place, edit list and priming (1024 / 2112) intact, on commercial + stems too, so stems stay sample-locked to the mix and the cues. Cached in + app-data keyed by path + size + mtime, LRU under 2 GB, written partial → + rename; ~0.1 s per stem uncached. - `app_state.py` — the one loaded library, and the **version-history commit**. **`discard()`** (`POST /api/discard`, SaveBar's "Discard changes…", the quit prompt's Discard) drops every unsaved edit through the adapter's own @@ -645,6 +656,24 @@ Two independent apps that talk over HTTP: browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open` outside Tauri; "Skip this version" persists `skippedUpdateVersion` to userprefs via `/api/prefs`; all failures are silent). + - **Stem playback** (decided 2026-09-30): a stem FILE always loads its four + stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays + their SUM, as Traktor's stem deck does — the mix stream is never decoded, + which also saves a full-length buffer. `PlaybackEngine.load` takes several + buffers: one source + gain each, all started at ONE scheduled context + time (so they stay sample-locked through seeks and loops), mute/solo as + ramped gains, never a restart. `ScratchEngine.loadStems` keeps ONE summed + copy of the audible stems (not four), re-summed in slices on a mute change. + `analyzeStems` returns the overview's three-band columns (of the sum) plus + one amplitude lane per stem, each normalised to its own 99.5th percentile + but never below 5% of the loudest (a silent stem stays silent). + `MainWaveform` draws the lanes in the file's own colours with a mute + button at each lane's left edge (click = mute, Alt/Option-click = solo); + Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the + mutes (every other stem muted), so each stem stays freely mutable after + it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is + the cost: ~140 MB per stem for 6 minutes, i.e. the same four buffers as + the file holds streams, and no more. - **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it, in three rows. **Header**: cover, title/artist · album · genre, a Read-only badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` — @@ -809,6 +838,12 @@ serialization path.** It enforces: one bad track fails alone; destination+add mirrors into a new playlist; crash recovery restores (or finishes a committed save) and a re-run REUSES the kept stem files without calling the engine. +- `test_stem_playback.py` — stem playback's backend half on a generated stem + file (fake stems = distinct scalings of the mix): the layout is read from + the FILE (an MP3 whose entry carries `` has none); each served stem + is its own MP4, bit-identical to that stream in place and the RIGHT stem; + out-of-range / non-stem requests 404; the cache reuses, follows an edited + file, evicts LRU but never what it just wrote; the folder origin serves too. - `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/konduktor/core/stem_file.py b/backend/konduktor/core/stem_file.py index 2939c17..f0feefe 100644 --- a/backend/konduktor/core/stem_file.py +++ b/backend/konduktor/core/stem_file.py @@ -347,8 +347,62 @@ def is_stem_file(path: Path | str) -> bool: return False +def stem_layout(path: Path | str) -> list[dict] | None: + """The stems a file carries, for PLAYBACK: `[{"name", "color"}]` in stream + order (stream k+1 is stem k), or None when the file is not a playable stem + file — no `stem` box, a box that does not parse, or fewer audio streams than + it names. Read from the FILE, never from the library's ``: 105 plain + MP3 entries in the real collection carry that element.""" + import json + + import av + + path = Path(path) + try: + raw = read_stem_box(path) + if raw is None: + return None + stems = json.loads(raw).get("stems") or [] + with av.open(str(path), metadata_errors="ignore") as c: + streams = len(c.streams.audio) + except (OSError, ValueError, av.FFmpegError): + return None + if not stems or streams < 1 + len(stems): + return None + return [{"name": str(s.get("name") or f"Stem {i + 1}"), "color": str(s.get("color") or "#FFFFFF")} + for i, s in enumerate(stems)] + + +def extract_stream(path: Path | str, stream: int, fp) -> None: + """Copy audio stream `stream` (0 = the mix, 1-4 the stems) into its own MP4, + written to the file object `fp` — packets COPIED, never re-encoded. + + A browser decodes only an MP4's first audio stream, so this is how the deck + gets at the stems. Measured bit-identical to decoding the stream in place, + with the edit list (and so the priming: 1024 for FFmpeg's encoder, 2112 for + Apple's) carried across — on Konduktor's files and commercial ones alike, so + every stem stays sample-locked to the mix and to the cue timeline. + """ + import av + + with av.open(str(path), metadata_errors="ignore") as inp: + if not 0 <= stream < len(inp.streams.audio): + raise StemFileError(f"The file has no audio stream {stream}") + ist = inp.streams.audio[stream] + out = av.open(fp, "w", format="ipod") + try: + ost = out.add_stream_from_template(ist) + for pkt in inp.demux(ist): + if pkt.dts is None: + continue # the demuxer's end-of-stream flush packet + pkt.stream = ost + out.mux(pkt) + finally: + out.close() + + __all__ = [ "DEMUCS_ORDER", "NML_STEMS_JSON", "SR", "STEM_BOX_JSON", "STEM_NAMES", "Source", "StemFileError", "Written", "add_stem_box", "build", "choose_bitrate", "decode", - "default_encoder", "is_stem_file", "read_stem_box", "stem_target_name", "verify", + "default_encoder", "extract_stream", "is_stem_file", "read_stem_box", "stem_layout", "stem_target_name", "verify", ] diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 7fc2f49..cced2a2 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -1080,14 +1080,47 @@ _AUDIO_MIME = { } +def _stem_audio(path: Path, stem: int) -> FileResponse: + """One stem of a stem file as a file of its own (see stems/stream_cache.py): + a browser only ever decodes an MP4's first stream, which is the mix.""" + from .core import stem_file + from .stems import stream_cache + + layout = stem_file.stem_layout(path) + if layout is None or not 0 <= stem < len(layout): + raise HTTPException(404, "That file has no such stem") + try: + return FileResponse(stream_cache.stem_file_for(path, stem), media_type="audio/mp4") + except (stem_file.StemFileError, OSError) as ex: + raise HTTPException(500, f"Could not read the stem: {ex}") + + +def _stem_layout_of(path: Path | None) -> dict: + from .core import stem_file + + if path is None or not path.exists(): + raise HTTPException(404, "Audio file not found") + return {"stems": stem_file.stem_layout(path) or []} + + +@app.get("/api/tracks/stems") +def track_stems(track_id: str) -> dict: + """The stems a track's FILE carries for playback — `[{name, color}]`, empty + for anything that is not a stem file (whatever the library says).""" + return _stem_layout_of(require_adapter().audio_path(track_id)) + + @app.get("/api/tracks/audio") -def track_audio(track_id: str) -> FileResponse: - """Stream a track's audio file for playback (supports HTTP Range/seeking).""" +def track_audio(track_id: str, stem: int | None = None) -> FileResponse: + """Stream a track's audio file for playback (supports HTTP Range/seeking); + with `stem`, that stem of a stem file (0-based) instead.""" path = require_adapter().audio_path(track_id) if path is None: raise HTTPException(404, "Track not found") if not path.exists(): raise HTTPException(404, f"Audio file not found: {path}") + if stem is not None: + return _stem_audio(path, stem) # .stem.m4a and other MP4s serve as audio/mp4; browsers play the first track. mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream") # Cacheable so the waveform's decode-fetch and the