Implemented STEM playback

This commit is contained in:
patben8 committed 2026-10-01 10:55:09 +02:00
1 parent ae03a93f98
commit ecc0e4c8df
13 files changed
+775 -61

No files matched your search

+55 -1
View File
@@ -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 `<STEMS>`: 105 plain
MP3 entries in the real collection carry that element."""
import json
import av
path = Path(path)
try:
raw = read_stem_box(path)
if raw is None:
return None
stems = json.loads(raw).get("stems") or []
with av.open(str(path), metadata_errors="ignore") as c:
streams = len(c.streams.audio)
except (OSError, ValueError, av.FFmpegError):
return None
if not stems or streams < 1 + len(stems):
return None
return [{"name": str(s.get("name") or f"Stem {i + 1}"), "color": str(s.get("color") or "#FFFFFF")}
for i, s in enumerate(stems)]
def 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",
]
+51 -4
View File
@@ -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 <audio> element can share
@@ -1705,7 +1738,7 @@ def source_track_cues(track_id: str) -> TrackCues:
@app.get("/api/source/tracks/audio")
def source_track_audio(track_id: str) -> FileResponse:
def source_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
"""Stream a track's audio straight off the source drive.
So the deck can audition a track BEFORE importing it, which is most of the
@@ -1717,10 +1750,17 @@ def source_track_audio(track_id: str) -> FileResponse:
raise HTTPException(404, "Track not found")
if not path.exists():
raise HTTPException(404, f"Audio file not found: {path}")
if stem is not None:
return _stem_audio(path, stem)
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
return FileResponse(path, media_type=mime)
@app.get("/api/source/tracks/stems")
def source_track_stems(track_id: str) -> dict:
return _stem_layout_of(require_source().audio_path(track_id))
# ---- drives and folders -----------------------------------------------
#
# The sidebar's Devices and Local Storage trees. Browsing a folder is READ-ONLY
@@ -1820,14 +1860,21 @@ def folder_track_cues(track_id: str) -> TrackCues:
@app.get("/api/folder/tracks/audio")
def folder_track_audio(track_id: str) -> FileResponse:
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
path = _folder_track(track_id).audio_path(track_id)
if path is None or not path.is_file():
raise HTTPException(404, "Audio file not found")
if stem is not None:
return _stem_audio(path, stem)
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
return FileResponse(path, media_type=mime)
@app.get("/api/folder/tracks/stems")
def folder_track_stems(track_id: str) -> dict:
return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
def _folder_add_plan(body: FolderAddRequest):
dest = require_adapter()
tracks = []
+75
View File
@@ -0,0 +1,75 @@
"""The deck's stem audio: one stream of a stem file, as a file of its own.
A browser decodes only the FIRST audio stream of an MP4, so the deck cannot get
at a stem file's stems from the file itself. Each is copied out (packets, not
re-encoded — `stem_file.extract_stream`) into a small cache in app-data, keyed
by the source's path, size and mtime, so an edited or replaced file is never
served stale and loading the same track twice costs nothing the second time.
The cache is bounded (`LIMIT` bytes, least recently used first) — a stem is
2-10 MB, so the limit holds a few hundred tracks' worth. Files are written as a
partial then renamed, so two requests racing for the same stem, or a crash
mid-write, can never serve a truncated file.
"""
from __future__ import annotations
import hashlib
import os
import threading
from pathlib import Path
from .. import paths
from ..core import stem_file
LIMIT = 2 * 1024 ** 3
_lock = threading.Lock()
def root() -> Path:
d = paths.app_data_dir() / "stems" / "playback"
d.mkdir(parents=True, exist_ok=True)
return d
def _key(path: Path, stream: int) -> str:
st = path.stat()
raw = f"{path.resolve()}\0{st.st_size}\0{st.st_mtime_ns}\0{stream}".encode()
return hashlib.sha256(raw).hexdigest()[:32]
def stem_file_for(path: Path, stem: int) -> Path:
"""The cached single-stream file for stem `stem` (0-based: stream stem+1)."""
path = Path(path)
stream = stem + 1
target = root() / f"{_key(path, stream)}.m4a"
if target.exists():
os.utime(target) # most recently used
return target
partial = target.with_name(f"{target.name}.{os.getpid()}.{threading.get_ident()}.part")
try:
with open(partial, "wb") as fp:
stem_file.extract_stream(path, stream, fp)
os.replace(partial, target)
finally:
partial.unlink(missing_ok=True)
_prune(keep=target)
return target
def _prune(keep: Path) -> None:
with _lock:
files = []
for p in root().glob("*.m4a"):
try:
st = p.stat()
except OSError:
continue
files.append((st.st_mtime, st.st_size, p))
total = sum(size for _, size, _ in files)
for _, size, p in sorted(files):
if total <= LIMIT:
break
if p == keep:
continue
p.unlink(missing_ok=True)
total -= size
+1 -1
View File
@@ -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_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+153
View File
@@ -0,0 +1,153 @@
"""Stem playback on the deck — the backend half: a stem file's stems served one
by one, because a browser decodes only an MP4's first audio stream (the mix).
Pins what would fail silently:
* a served stem is BIT-IDENTICAL to decoding that stream in place, edit list
and all — a stem shifted by its priming would flam against the others and
sit off every cue;
* "is this a stem file" is read from the FILE: an MP3 whose collection entry
carries `<STEMS>` (105 real ones do) has no stems to play;
* the cache follows the file (an edited file is not served stale) and stays
within its limit without evicting what it just wrote;
* all three origins (collection, device, folder) serve them.
Everything is generated: a stem file built with a FAKE separator whose four
stems are distinct scalings of the mix, so each served stem can be told apart.
"""
from __future__ import annotations
import 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-stemplay-appdata-")
import av # noqa: E402
import numpy as np # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
from konduktor.core import stem_file as sf # noqa: E402
from konduktor.stems import stream_cache # noqa: E402
from stem_test_support import make_mp3 # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def decode(path: Path, stream: int = 0) -> np.ndarray:
with av.open(str(path)) as c:
return np.concatenate([f.to_ndarray() for f in c.decode(c.streams.audio[stream])], axis=1)
GAINS = (0.5, 0.25, -0.2, 0.1)
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-stemplay-"))
music = ROOT / "Music"
music.mkdir()
stem = music / "Tune.stem.m4a"
sf.build(make_mp3(ROOT / "src.mp3", seconds=6), stem, lambda p: [p * g for g in GAINS])
plain = make_mp3(music / "Plain.mp3", seed=7)
tagged = make_mp3(music / "Tagged.mp3", seed=8) # its ENTRY will carry <STEMS>
print("== stem_file: what a file carries ==")
layout = sf.stem_layout(stem)
check("a stem file lists its four stems with names and colours, in stream order",
[s["name"] for s in layout or []] == ["Drums", "Bass", "Synths", "Vox"]
and all(s["color"].startswith("#") for s in layout), str(layout))
check("a plain MP3 has none", sf.stem_layout(plain) is None)
check("a missing file has none (no exception)", sf.stem_layout(ROOT / "nope.stem.m4a") is None)
print("== a temp collection pointing at them ==")
work = ROOT / "collection.nml"
shutil.copy2(REAL, work)
st = TraktorStore(work)
entries = [e for e in st._nml.collection.entry if e.location][:3]
ids = []
for e, path in zip(entries, (stem, plain, tagged)):
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
ids.append(st._key_of(e))
from traktor_nml_utils.models.collection import Stemstype # noqa: E402
entries[2].stems = Stemstype(stems=sf.NML_STEMS_JSON)
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
st.save()
stem_id, plain_id, tagged_id = ids
with TestClient(main.app) as c:
assert c.post("/api/library/open", json={"path": str(work)}).status_code == 200
print("== the collection routes ==")
r = c.get("/api/tracks/stems", params={"track_id": stem_id}).json()
check("/api/tracks/stems lists the stem file's stems", r["stems"] == layout, str(r))
check("…none for a plain MP3", c.get("/api/tracks/stems", params={"track_id": plain_id}).json()["stems"] == [])
tagged_track = c.get("/api/tracks", params={"limit": 20000}).json()
tagged_kind = next((t["media_kind"] for t in tagged_track["items"] if t["id"] == tagged_id), None) \
if isinstance(tagged_track, dict) and "items" in tagged_track else None
check("…and none for an MP3 the COLLECTION calls a stem track (decided by the file)",
c.get("/api/tracks/stems", params={"track_id": tagged_id}).json()["stems"] == [],
f"media_kind={tagged_kind}")
mix = decode(stem, 0)
for k in range(4):
r = c.get("/api/tracks/audio", params={"track_id": stem_id, "stem": k})
ok = r.status_code == 200 and r.headers["content-type"].startswith("audio/mp4")
got = ROOT / f"served-{k}.m4a"
got.write_bytes(r.content if ok else b"")
same = ok and np.array_equal(decode(got), decode(stem, k + 1))
check(f"stem {k} is served as its own MP4, bit-identical to stream {k + 1} in place", same)
if same:
s = decode(got)
n = min(s.shape[1], mix.shape[1])
# The fake stems are the mix scaled: the right stream, not just A stream.
ratio = float(np.dot(s[0, :n], mix[0, :n]) / np.dot(mix[0, :n], mix[0, :n]))
check(f"…and it is stem {k} (gain {GAINS[k]:+.2f}, measured {ratio:+.2f}), same length as the mix",
abs(ratio - GAINS[k]) < 0.05 and s.shape[1] == mix.shape[1], f"{ratio} {s.shape} {mix.shape}")
check("the plain audio route still serves the whole file",
c.get("/api/tracks/audio", params={"track_id": stem_id}).content == stem.read_bytes())
check("a stem out of range is 404",
c.get("/api/tracks/audio", params={"track_id": stem_id, "stem": 4}).status_code == 404)
check("asking a plain MP3 for a stem is 404",
c.get("/api/tracks/audio", params={"track_id": plain_id, "stem": 0}).status_code == 404)
print("== the cache ==")
cached = stream_cache.stem_file_for(stem, 0)
check("a second request reuses the cached file", stream_cache.stem_file_for(stem, 0) == cached)
st_ = stem.stat()
os.utime(stem, ns=(st_.st_atime_ns, st_.st_mtime_ns + 10_000_000_000))
check("an edited source gets a fresh file, never the stale one", stream_cache.stem_file_for(stem, 0) != cached)
before = sorted(stream_cache.root().glob("*.m4a"))
stream_cache.LIMIT = 1 # everything is over the limit now
newest = stream_cache.stem_file_for(stem, 3)
after = sorted(stream_cache.root().glob("*.m4a"))
check("over its limit the cache evicts the least recently used…", len(before) >= 2 and after == [newest],
f"{len(before)} -> {[p.name for p in after]}")
check("…but never the file it just wrote", newest.exists() and newest in after)
check("no partial file is left behind", not list(stream_cache.root().glob("*.part")))
stream_cache.LIMIT = 2 * 1024 ** 3
print("== the folder origin ==")
listing = c.get("/api/folder/tracks", params={"path": str(music)})
check("(setup) the folder lists", listing.status_code == 200, listing.text[:200])
fid = str(stem)
r = c.get("/api/folder/tracks/stems", params={"track_id": fid})
check("a stem file browsed in a folder lists its stems", r.status_code == 200 and r.json()["stems"] == layout,
r.text[:200])
r = c.get("/api/folder/tracks/audio", params={"track_id": fid, "stem": 1})
got = ROOT / "folder-1.m4a"
got.write_bytes(r.content)
check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2)))
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)